diff --git a/.dockerignore b/.dockerignore index ff81adab56..c562ba2ae1 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,10 +1,15 @@ backend/**.db +backend/*.sqlite +backend/*.sqlite.* +**/*.sqlite +**/*.sqlite.* +backend/filebrowser.sqlite* **.crt **.key backend/tmp backend/dist backend/backend* -backend/http/dist/** +backend/internal/web/dist/** backend/vendor/** frontend/dist/** diff --git a/.github/workflows/create-dev-branch.yaml b/.github/workflows/create-dev-branch.yaml index f983d7bd7d..503e3c2bc2 100644 --- a/.github/workflows/create-dev-branch.yaml +++ b/.github/workflows/create-dev-branch.yaml @@ -11,7 +11,7 @@ on: jobs: create-dev-branch: name: Create Dev Branch - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - name: Check out repository diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 8d80641819..3cb47f3e5f 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -8,7 +8,7 @@ on: jobs: test_playwright: name: Test Playwright - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - name: Checkout uses: actions/checkout@v4 diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 0126bb02c6..3d6f844986 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -11,7 +11,7 @@ on: jobs: prime_docker_cache: name: Prime docker cache - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - name: Checkout uses: actions/checkout@v4 @@ -28,7 +28,7 @@ jobs: type=gha,mode=max,scope=${{ github.ref_name }}-playwright-base build_frontend: name: Build frontend - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - name: Checkout uses: actions/checkout@v4 @@ -40,10 +40,10 @@ jobs: uses: actions/upload-artifact@v4 with: name: dist - path: backend/http/dist + path: backend/internal/web/dist build_backend: name: Build backend - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - name: Checkout uses: actions/checkout@v4 @@ -61,7 +61,7 @@ jobs: test_playwright: needs: [build_backend, build_frontend, prime_docker_cache] name: Test Playwright - ${{ matrix.name }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm strategy: fail-fast: false matrix: @@ -103,8 +103,8 @@ jobs: run: chmod +x backend/filebrowser - name: Copy frontend build to backend run: | - mkdir -p backend/http/embed - cp -r frontend/dist/* backend/http/embed + mkdir -p backend/internal/web/embed + cp -r frontend/dist/* backend/internal/web/embed - name: Set up QEMU uses: docker/setup-qemu-action@v3.0.0 - name: Set up Docker Buildx @@ -124,7 +124,7 @@ jobs: type=gha,mode=max,scope=${{ github.ref_name }}-playwright-base push_pr_to_registry: name: Build docker image - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - name: Checkout uses: actions/checkout@v4 diff --git a/.github/workflows/promote-beta-to-stable.yaml b/.github/workflows/promote-beta-to-stable.yaml index e870e75b95..708718976c 100644 --- a/.github/workflows/promote-beta-to-stable.yaml +++ b/.github/workflows/promote-beta-to-stable.yaml @@ -11,7 +11,7 @@ on: jobs: promote-beta-to-stable: name: Promote Beta to Stable - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - name: Check out repository diff --git a/.github/workflows/promote-dev-to-beta.yaml b/.github/workflows/promote-dev-to-beta.yaml index 72b4efc8b1..24c1163197 100644 --- a/.github/workflows/promote-dev-to-beta.yaml +++ b/.github/workflows/promote-dev-to-beta.yaml @@ -11,7 +11,7 @@ on: jobs: promote-dev-to-beta: name: Promote Dev to Beta - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - name: Check out repository diff --git a/.github/workflows/regular-tests.yaml b/.github/workflows/regular-tests.yaml index 3de4d989a5..2fa059f45b 100644 --- a/.github/workflows/regular-tests.yaml +++ b/.github/workflows/regular-tests.yaml @@ -7,7 +7,7 @@ on: jobs: test-backend: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 @@ -16,7 +16,7 @@ jobs: - working-directory: backend run: go test -race -v ./... -timeout 30s lint-backend: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 @@ -28,7 +28,7 @@ jobs: working-directory: backend install-mode: goinstall format-backend: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 @@ -37,32 +37,39 @@ jobs: - working-directory: backend run: go fmt ./... lint-frontend: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 - working-directory: frontend run: npm i && npm run lint test-frontend: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 - working-directory: frontend run: npm i && npm run test check-translations: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 - working-directory: frontend run: npm i && npm run i18n:check check-docs: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: go-version: 'stable' - run: make generate-docs - - run: git diff --exit-code \ No newline at end of file + - run: git diff --exit-code + check-icons: + runs-on: ubuntu-24.04-arm + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + - working-directory: frontend + run: npm i && npm run icons:check \ No newline at end of file diff --git a/.github/workflows/release_beta.yaml b/.github/workflows/release_beta.yaml index c0b87b583e..0273533138 100644 --- a/.github/workflows/release_beta.yaml +++ b/.github/workflows/release_beta.yaml @@ -11,7 +11,7 @@ permissions: jobs: test_playwright: name: Test Playwright - regular - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - name: Checkout uses: actions/checkout@v4 @@ -36,7 +36,7 @@ jobs: create_release_tag: needs: [ test_playwright ] name: Create Release - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - name: Checkout code uses: actions/checkout@v4 @@ -59,7 +59,7 @@ jobs: target_commitish: ${{ github.sha }} token: ${{ secrets.PAT }} tag_name: ${{ steps.extract_branch.outputs.tag_name }} - prerelease: true + prerelease: false make_latest: false draft: false generate_release_notes: true diff --git a/.github/workflows/release_stable.yaml b/.github/workflows/release_stable.yaml index 0780cb3058..2431336889 100644 --- a/.github/workflows/release_stable.yaml +++ b/.github/workflows/release_stable.yaml @@ -11,7 +11,7 @@ permissions: jobs: test_playwright: name: Test Playwright - regular - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - name: Checkout uses: actions/checkout@v4 @@ -36,7 +36,7 @@ jobs: create_release_tag: needs: [ test_playwright ] name: Create Release - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - name: Checkout code uses: actions/checkout@v4 diff --git a/.github/workflows/tag.yaml b/.github/workflows/tag.yaml index fbf422681c..eb2a435c13 100644 --- a/.github/workflows/tag.yaml +++ b/.github/workflows/tag.yaml @@ -11,7 +11,7 @@ permissions: jobs: update_tag: name: Update Release tag - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm steps: - name: Checkout code uses: actions/checkout@v4 diff --git a/.github/workflows/update-build-images.yaml b/.github/workflows/update-build-images.yaml index 4f97a96006..d92e46170c 100644 --- a/.github/workflows/update-build-images.yaml +++ b/.github/workflows/update-build-images.yaml @@ -7,7 +7,7 @@ on: jobs: publish_playwright_base: name: Publish playwright-base to GHCR - runs-on: ubuntu-latest + runs-on: ubuntu-24.04-arm permissions: contents: read packages: write diff --git a/.gitignore b/.gitignore index 5d7e807574..78ba6ecce9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ *.db *.db.old -*.sqlite +# Playwright settings migration fixture (BoltDB → SQLite tests + Docker settings image) +!_docker/src/settings/backend/database.db.old +*.sqlite** *.bak *.log *.mjs @@ -21,6 +23,8 @@ frontend/tsconfig.tsbuildinfo /frontend/playwright-files /frontend/screenshots /frontend/generated +frontend/.venv-icons +frontend/.tmp-icons-* /frontend/tests/playwright-files/demo* /frontend/loginAuth.json /frontend/sharePrepStorage.json @@ -29,8 +33,8 @@ frontend/tsconfig.tsbuildinfo /backend/*test_config.yaml /backend/generated.yaml /backend/srv -/backend/http/dist -/backend/http/embed +/backend/internal/web/dist +/backend/internal/web/embed /backend/debug .DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md index 899389ab2d..cdae9abc0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,71 @@ 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.0 + +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, and the [config migration tool](https://filebrowserquantum.com/en/docs/getting-started/v2/config-migration/) to convert legacy config. + + **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 --password [value]` and `user promote `; `set -u username,password` is deprecated. See [CLI reference](https://filebrowserquantum.com/en/docs/reference/cli/). + + + **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/). + + **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 + ## v1.5.5 **BugFixes**: @@ -38,7 +103,6 @@ All notable changes to this project will be documented in this file. For commit - fix upload shares with password (#2589) (#2573) - fix token when returning from preview on shares with pass (#2588) (#2465) - fix share undefined url after editing (#2567) (#2523) - ## v1.5.0 **New Features**: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index adf9b7d659..27af31fc1d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,11 +16,6 @@ Thank you for your interest in contributing to FileBrowser Quantum! This guide w - macOS: `brew install ffmpeg` - Windows: Download from [ffmpeg.org](https://ffmpeg.org/download.html) -- **exiftool**: For photo metadata processing (RAW/HEIC previews, EXIF orientation) - - Ubuntu/Debian: `sudo apt-get install libimage-exiftool-perl` - - macOS: `brew install exiftool` - - Windows: Download from [exiftool.org](https://exiftool.org/) (install `exiftool.exe` and add it to your PATH, or set `integrations.media.exiftoolPath` in config) - - **mupdf-tools**: For PDF preview generation - Ubuntu/Debian: `sudo apt-get install mupdf-tools` - macOS: `brew install mupdf-tools` @@ -47,11 +42,12 @@ make dev ### Backend (Go) - **Entry Point**: `backend/main.go` → `backend/cmd/` -- **HTTP Server**: `backend/http/` - API routes, middleware, auth -- **Storage**: BoltDB via `backend/database/storage/` -- **Authentication**: Multiple providers in `backend/auth/` -- **Indexing**: Real-time search in `backend/indexing/` -- **Previews**: Image/video/document generation in `backend/preview/` +- **HTTP Server**: `backend/internal/web/` - API routes, middleware, auth +- **Storage**: SQLite via `backend/internal/database/` +- **Authentication**: Multiple providers in `backend/internal/auth/` +- **Indexing**: Real-time search in `backend/pkg/indexing/` +- **Previews**: Image/video/document generation in `backend/internal/preview/` +- **Activity**: Query, recording, and export logic in `backend/internal/activity/` ### Frontend (Vue.js + TypeScript) - **Framework**: Vue 3 + Vite + TypeScript diff --git a/README.md b/README.md index d7747263ed..4027cf3176 100644 --- a/README.md +++ b/README.md @@ -7,16 +7,17 @@ [![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://github.com/gtsteffaniak/filebrowser/wiki/Q&A#is-there-a-way-to-donate-or-support-this-project) - + FileBrowser Quantum logo

FileBrowser Quantum

The best free self-hosted web-based file manager.

- + FileBrowser Quantum file listing in dark mode ## Pinned :pushpin: [Read The Official Docs](https://filebrowserquantum.com/) (currently english-only) +:pushpin: [v2.0.0 is now in beta!](https://filebrowserquantum.com/en/docs/getting-started/v2/about/) ## About @@ -36,21 +37,23 @@ FileBrowser Quantum is a massive fork of the file browser open-source project wi 2. ✅ Login support for OIDC, LDAP, JWT, password + 2FA, and proxy. 3. ✅ Beautiful, Responsive, and Customizable user interface. 4. ✅ Streamlined configuration via `config.yaml` config file. - 5. ✅ Ultra-efficient Sqlite [indexing](https://github.com/gtsteffaniak/filebrowser/wiki/Indexing) + 5. ✅ Efficient search - Real-time search results as you type. - Real-time monitoring and updates in the UI. - Search supports file and folder sizes, along with various filters. 6. ✅ Better listing browsing - - Better thumbnail support including **office**, **video**, and **album artwork**, and **3D models**. + - Thumbnails support includes **office**, **video**, and **album artwork**, and **3D models**. - Faster and more responsive views with animations. - - Folder sizes are displayed and support thumbnails + - **Folder sizes** are displayed and support thumbnails - Navigating remembers the last scroll position. + - WebDAV support + - Granular permissions 7. ✅ Highly configurable and [customizable sharing options](https://filebrowserquantum.com/en/docs/shares/options/) - share expiration time - users who can access share (including anonymous) - styling and themes - file viewing, editing, and uploading permissions - 8. ✅ Directory-level access control that can be scoped to user or group. + 8. ✅ Access control that can be scoped to user or group and source path. 9. ✅ Developer API support - Ability to create long-lived API Tokens. - A helpful Swagger page is available at `/swagger` endpoint for API enabled users. @@ -65,24 +68,22 @@ FileBrowser Quantum differs significantly from the original version. Many of the The UI has a simple three-component navigation system: 1. (Left) Multi-action button with slide-out panel. - 2. (Middle) The powerful search bar. - 3. (Right) The view change toggle. + 2. (Middle) The powerful search bar / title + 3. (Right) The view change toggle / overflow menu All other functions are moved either into the action menu or pop-up menus. If the action does not depend on context, it will exist in the slide-out action panel. If the action is available based on context, it will show up as a pop-up menu. -

- -

+Aug-07-2026 14-54-55 ## Official Docs See the [Official Docs](https://filebrowserquantum.com/). Contributions are welcome and encouraged! See [FilebrowserDocs Github](https://github.com/quantumx-apps/filebrowserDocs). ## Comparison Chart -Application Name | Quantum | Filebrowser | Filestash | Nextcloud | Google_Drive | FileRun +Application Name | Quantum | Filebrowser | Filestash | Nextcloud | Google_Drive | FileRun --- | --- | --- | --- | --- | --- | --- | Filesystem support | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | Linux | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | @@ -122,10 +123,10 @@ Office file support | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | Office file previews | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | Themes | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | Branding support | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | -activity log | :construction: | ❌ | ✅ | ✅ | ✅ | ✅ | +activity log | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ Comments support | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | trash support | :construction: | ❌ | ✅ | ✅ | ✅ | ✅ | -Starred/pinned files | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | +Starred/pinned files | ✅ | ❌ | ✅ | ❌ | ✅ | ✅ | Chromecast support | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | Share collections of files | :construction: | ❌ | ❌ | ❌ | ❌ | ✅ | Can archive selected files | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | diff --git a/_docker/Dockerfile b/_docker/Dockerfile index 116baba017..16633e7e08 100644 --- a/_docker/Dockerfile +++ b/_docker/Dockerfile @@ -1,4 +1,4 @@ -FROM gtstef/ffmpeg:8.1.2-decode AS ffmpeg +FROM gtstef/ffmpeg:9.0-decode AS ffmpeg FROM golang:alpine AS base ARG VERSION ARG REVISION @@ -6,28 +6,29 @@ WORKDIR /app COPY ./backend ./ RUN apk update && apk add --no-cache gcc musl-dev ENV CGO_ENABLED=1 -RUN go build -tags mupdf,musl -ldflags="-w -s \ - -X 'github.com/gtsteffaniak/filebrowser/backend/common/version.Version=${VERSION}' \ - -X 'github.com/gtsteffaniak/filebrowser/backend/common/version.CommitSHA=${REVISION}'" \ +RUN go build -tags analytics,mupdf,musl -ldflags="-w -s \ + -X 'github.com/gtsteffaniak/filebrowser/backend/internal/version.Version=${VERSION}' \ + -X 'github.com/gtsteffaniak/filebrowser/backend/internal/version.CommitSHA=${REVISION}'" \ -o filebrowser . FROM node:jod-slim AS nbuild -WORKDIR /app -COPY ./frontend/package.json ./ +WORKDIR /build +COPY ./frontend/package.json ./frontend/ RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates \ && git config --global url."https://github.com/".insteadOf "git@github.com:" \ && git config --global url."https://github.com/".insteadOf "ssh://git@github.com/" -RUN npm i --maxsockets 1 -COPY ./frontend/ ./ +RUN cd frontend && npm i --maxsockets 1 +COPY ./frontend/ ./frontend/ +WORKDIR /build/frontend RUN npm run build:docker FROM alpine:latest COPY --from=ffmpeg [ "/ffmpeg", "/ffprobe", "/usr/local/bin/" ] ENV FILEBROWSER_FFMPEG_PATH="/usr/local/bin/" -ENV FILEBROWSER_DATABASE="/home/filebrowser/data/database.db" +ENV FILEBROWSER_DATABASE_PATH="/home/filebrowser/data/database.sqlite" ENV FILEBROWSER_CONFIG="/home/filebrowser/data/config.yaml" ENV PATH="$PATH:/home/filebrowser" -RUN apk --no-cache add ca-certificates mailcap tzdata curl exiftool +RUN apk --no-cache add ca-certificates mailcap tzdata curl RUN adduser -D -s /bin/true -u 1000 filebrowser USER filebrowser WORKDIR /home/filebrowser @@ -36,12 +37,11 @@ COPY --from=base --chown=filebrowser:1000 [ "/app/filebrowser", "./" ] COPY --from=base --chown=filebrowser:1000 [ "/app/config.yaml", "./data/config.yaml" ] COPY --from=base --chown=filebrowser:1000 [ "/app/config.yaml", "./" ] COPY --from=base --chown=filebrowser:1000 [ "/app/reduce-rounded-corners.css", "./" ] -COPY --from=nbuild --chown=filebrowser:1000 [ "/app/dist/", "./http/dist/" ] +COPY --from=nbuild --chown=filebrowser:1000 [ "/build/backend/internal/web/dist/", "./internal/web/dist/" ] ## sanity checks RUN [ "filebrowser", "version" ] RUN [ "ffmpeg", "-version" ] RUN [ "ffprobe", "-version" ] -RUN [ "exiftool", "-ver" ] # exposing default port for auto discovery. EXPOSE 80 HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \ diff --git a/_docker/Dockerfile.playwright-general b/_docker/Dockerfile.playwright-general index 5a964abb5e..ae81541e2e 100644 --- a/_docker/Dockerfile.playwright-general +++ b/_docker/Dockerfile.playwright-general @@ -9,15 +9,14 @@ COPY [ "./_docker/src/general/frontend/", "./" ] COPY [ "./frontend/tests/", "./tests" ] WORKDIR /app/backend/ -COPY [ "./backend/filebrowser*", "./"] +COPY [ "./backend/filebrowser", "./"] COPY [ "./backend/reduce-rounded-corners.css", "./no-rounded.css" ] -RUN mkdir -p ./http/dist -COPY [ "./backend/http/embed/", "./http/dist/"] +RUN mkdir -p ./internal/web/dist +COPY [ "./backend/internal/web/embed/", "./internal/web/dist/"] # generate duplicate 1.1MB files RUN dd if=/dev/zero of=/app/frontend/tests/playwright-files/1.1MB.bin bs=1024 count=1126 && dd if=/dev/zero of=/app/frontend/tests/playwright-files/1.1mb.bin bs=1024 count=1126 # Run tests ENV FILEBROWSER_PLAYWRIGHT_TEST=true -RUN ./filebrowser set -u testuser1,testuser1 -RUN ./filebrowser & sleep 2 && cd ../frontend && npx playwright test +RUN ./filebrowser user set testuser1 --password testuser1 && ./filebrowser & sleep 2 && cd ../frontend && npx playwright test diff --git a/_docker/Dockerfile.playwright-jwt b/_docker/Dockerfile.playwright-jwt index cf7fc35aa1..855270ff39 100644 --- a/_docker/Dockerfile.playwright-jwt +++ b/_docker/Dockerfile.playwright-jwt @@ -5,8 +5,8 @@ WORKDIR /app/frontend COPY [ "./frontend/tests", "./tests" ] WORKDIR /app/backend/ COPY [ "./backend/filebrowser", "./"] -RUN mkdir -p ./http/dist -COPY [ "./backend/http/embed/", "./http/dist/"] +RUN mkdir -p ./internal/web/dist +COPY [ "./backend/internal/web/embed/", "./internal/web/dist/"] RUN apt update && apt install nginx -y RUN mv default.conf /etc/nginx/conf.d/default.conf RUN sed -i 's/filebrowser/localhost/g' /etc/nginx/conf.d/default.conf diff --git a/_docker/Dockerfile.playwright-local b/_docker/Dockerfile.playwright-local index a74390dd73..1e1ada95c6 100644 --- a/_docker/Dockerfile.playwright-local +++ b/_docker/Dockerfile.playwright-local @@ -2,13 +2,21 @@ FROM ghcr.io/gtsteffaniak/playwright-base:chromium WORKDIR /app WORKDIR /app/frontend -COPY [ "./frontend/", "./" ] +COPY [ "./frontend/tests/", "./tests" ] +COPY [ "./frontend/tests/playwright-files", "/tests/playwright-files" ] WORKDIR /app/backend/ COPY [ "./backend/filebrowser*", "./"] -COPY [ "./_docker/src/screenshots/backend/*", "./"] +COPY [ "./_docker/src/settings/backend/config.yaml", "./"] +COPY [ "./_docker/src/settings/backend/database.db.old", "./"] +COPY [ "./backend/reduce-rounded-corners.css", "./no-rounded.css"] +RUN mkdir -p ./internal/web/dist +COPY [ "./backend/internal/web/embed/", "./internal/web/dist/"] -RUN mkdir -p ./http/dist -COPY [ "./backend/http/embed/", "./http/dist/"] - -ENTRYPOINT [ "./filebrowser" ] \ No newline at end of file +ENV FILEBROWSER_PLAYWRIGHT_TEST=true +RUN ./filebrowser user set testuser1 --password testuser1 +RUN ./filebrowser set rule -s access -p / -r user -v admin --allow -c config.yaml +RUN ./filebrowser set rule -s access -p /excluded/showme.txt -r user -v admin --allow -c config.yaml +RUN ./filebrowser set rule -s access -p /denied -r user -v admin -c config.yaml +RUN ./filebrowser set rule -s access -p /excluded -r user -v admin -c config.yaml +ENTRYPOINT [ "./filebrowser" ] diff --git a/_docker/Dockerfile.playwright-no-config b/_docker/Dockerfile.playwright-no-config index d97e8919a2..46309ded86 100644 --- a/_docker/Dockerfile.playwright-no-config +++ b/_docker/Dockerfile.playwright-no-config @@ -9,9 +9,9 @@ COPY [ "./_docker/src/no-config/frontend/", "./" ] COPY [ "./frontend/tests/", "./tests" ] WORKDIR /app/backend/ -COPY [ "./backend/filebrowser*", "./"] -RUN mkdir -p ./http/dist -COPY [ "./backend/http/embed/", "./http/dist/"] +COPY [ "./backend/filebrowser", "./"] +RUN mkdir -p ./internal/web/dist +COPY [ "./backend/internal/web/embed/", "./internal/web/dist/"] # Run tests ENV FILEBROWSER_PLAYWRIGHT_TEST=true diff --git a/_docker/Dockerfile.playwright-noauth b/_docker/Dockerfile.playwright-noauth index ad74f55bd7..d15bbb71bb 100644 --- a/_docker/Dockerfile.playwright-noauth +++ b/_docker/Dockerfile.playwright-noauth @@ -10,8 +10,8 @@ COPY [ "./frontend/tests/playwright-files", "./tests/playwright-files2" ] WORKDIR /app/backend/ COPY [ "./backend/filebrowser", "./"] -RUN mkdir -p ./http/dist -COPY [ "./backend/http/embed/", "./http/dist/"] +RUN mkdir -p ./internal/web/dist +COPY [ "./backend/internal/web/embed/", "./internal/web/dist/"] # Run tests ENV FILEBROWSER_PLAYWRIGHT_TEST=true diff --git a/_docker/Dockerfile.playwright-oidc b/_docker/Dockerfile.playwright-oidc index f57a9968e4..9b513aab0c 100644 --- a/_docker/Dockerfile.playwright-oidc +++ b/_docker/Dockerfile.playwright-oidc @@ -4,10 +4,10 @@ COPY [ "./_docker/src/oidc/frontend/", "./" ] COPY [ "./frontend/tests/", "./tests" ] WORKDIR /app/backend/ -RUN mkdir -p ./http/dist +RUN mkdir -p ./internal/web/dist COPY [ "./_docker/src/oidc/backend/", "./"] COPY ["./backend/filebrowser", "./"] -COPY [ "./backend/http/embed/", "./http/dist/"] +COPY [ "./backend/internal/web/embed/", "./internal/web/dist/"] # Run tests WORKDIR /app/frontend diff --git a/_docker/Dockerfile.playwright-previews b/_docker/Dockerfile.playwright-previews index c241ae2e73..f0137eb954 100644 --- a/_docker/Dockerfile.playwright-previews +++ b/_docker/Dockerfile.playwright-previews @@ -9,8 +9,8 @@ COPY [ "./frontend/tests", "./tests" ] WORKDIR /app/backend/ COPY [ "./backend/filebrowser", "./"] -RUN mkdir -p ./http/dist -COPY [ "./backend/http/embed/", "./http/dist/"] +RUN mkdir -p ./internal/web/dist +COPY [ "./backend/internal/web/embed/", "./internal/web/dist/"] # Run tests ENV FILEBROWSER_PLAYWRIGHT_TEST=true diff --git a/_docker/Dockerfile.playwright-proxy b/_docker/Dockerfile.playwright-proxy index 4493d2f8e3..887297a2b3 100644 --- a/_docker/Dockerfile.playwright-proxy +++ b/_docker/Dockerfile.playwright-proxy @@ -5,8 +5,8 @@ WORKDIR /app/frontend COPY [ "./frontend/tests", "./tests" ] WORKDIR /app/backend/ COPY [ "./backend/filebrowser", "./"] -RUN mkdir -p ./http/dist -COPY [ "./backend/http/embed/", "./http/dist/"] +RUN mkdir -p ./internal/web/dist +COPY [ "./backend/internal/web/embed/", "./internal/web/dist/"] RUN apt update && apt install nginx -y RUN mv default.conf /etc/nginx/conf.d/default.conf RUN mv .htpasswd /etc/nginx/conf.d/.htpasswd diff --git a/_docker/Dockerfile.playwright-screenshots b/_docker/Dockerfile.playwright-screenshots index 90ba92ff64..17b5ffe10a 100644 --- a/_docker/Dockerfile.playwright-screenshots +++ b/_docker/Dockerfile.playwright-screenshots @@ -2,14 +2,15 @@ FROM ghcr.io/gtsteffaniak/playwright-base:chromium WORKDIR /app WORKDIR /app/frontend -COPY [ "./frontend/", "./" ] +COPY [ "./frontend/tests", "./tests" ] +COPY [ "./_docker/src/screenshots/frontend/", "./" ] WORKDIR /app/backend/ -COPY [ "./backend/filebrowser*", "./"] +COPY [ "./backend/filebrowser", "./"] COPY [ "./_docker/src/screenshots/backend/*", "./"] -RUN mkdir -p ./http/dist -COPY [ "./backend/http/embed/", "./http/dist/"] +RUN mkdir -p ./internal/web/dist +COPY [ "./backend/internal/web/embed/", "./internal/web/dist/"] ENV FILEBROWSER_PLAYWRIGHT_TEST=true RUN ./filebrowser & sleep 2 && cd ../frontend && npx playwright test --project dark-screenshots \ No newline at end of file diff --git a/_docker/Dockerfile.playwright-settings b/_docker/Dockerfile.playwright-settings index d89c8ac2c2..ba207535d3 100644 --- a/_docker/Dockerfile.playwright-settings +++ b/_docker/Dockerfile.playwright-settings @@ -10,16 +10,16 @@ COPY [ "./frontend/tests/", "./tests" ] COPY [ "./frontend/tests/playwright-files", "/tests/playwright-files" ] WORKDIR /app/backend/ -COPY [ "./backend/filebrowser*", "./"] +COPY [ "./backend/filebrowser", "./"] COPY [ "./backend/reduce-rounded-corners.css", "./no-rounded.css"] -RUN mkdir -p ./http/dist -COPY [ "./backend/http/embed/", "./http/dist/"] +RUN mkdir -p ./internal/web/dist +COPY [ "./backend/internal/web/embed/", "./internal/web/dist/"] # Run tests ENV FILEBROWSER_PLAYWRIGHT_TEST=true -RUN ./filebrowser set -u testuser1,testuser1 -RUN ./filebrowser set rule -s access -p / -r user -v admin -allow -c config.yaml -RUN ./filebrowser set rule -s access -p /excluded/showme.txt -r user -v admin -allow -c config.yaml +RUN ./filebrowser user set testuser1 --password testuser1 +RUN ./filebrowser set rule -s access -p / -r user -v admin --allow -c config.yaml +RUN ./filebrowser set rule -s access -p /excluded/showme.txt -r user -v admin --allow -c config.yaml RUN ./filebrowser set rule -s access -p /denied -r user -v admin -c config.yaml RUN ./filebrowser set rule -s access -p /excluded -r user -v admin -c config.yaml RUN ./filebrowser & sleep 2 && cd ../frontend && npx playwright test diff --git a/_docker/Dockerfile.playwright-sharing b/_docker/Dockerfile.playwright-sharing index 47cb529504..d3a8de6987 100644 --- a/_docker/Dockerfile.playwright-sharing +++ b/_docker/Dockerfile.playwright-sharing @@ -9,9 +9,9 @@ COPY [ "./_docker/src/sharing/frontend/", "./" ] COPY [ "./frontend/tests/", "./tests" ] WORKDIR /app/backend/ -COPY [ "./backend/filebrowser*", "./"] -RUN mkdir -p ./http/dist -COPY [ "./backend/http/embed/", "./http/dist/"] +COPY [ "./backend/filebrowser", "./"] +RUN mkdir -p ./internal/web/dist +COPY [ "./backend/internal/web/embed/", "./internal/web/dist/"] # Run tests ENV FILEBROWSER_PLAYWRIGHT_TEST=true diff --git a/_docker/Dockerfile.slim b/_docker/Dockerfile.slim index afe342e2fd..c007c5bb1f 100644 --- a/_docker/Dockerfile.slim +++ b/_docker/Dockerfile.slim @@ -4,23 +4,24 @@ ARG REVISION WORKDIR /app COPY ./backend ./ RUN apk update && apk add -RUN go build -ldflags="-w -s \ - -X 'github.com/gtsteffaniak/filebrowser/backend/common/version.Version=${VERSION}' \ - -X 'github.com/gtsteffaniak/filebrowser/backend/common/version.CommitSHA=${REVISION}'" \ +RUN go build -tags analytics -ldflags="-w -s \ + -X 'github.com/gtsteffaniak/filebrowser/backend/internal/version.Version=${VERSION}' \ + -X 'github.com/gtsteffaniak/filebrowser/backend/internal/version.CommitSHA=${REVISION}'" \ -o filebrowser . FROM node:jod-slim AS nbuild -WORKDIR /app -COPY ./frontend/package.json ./ +WORKDIR /build +COPY ./frontend/package.json ./frontend/ RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates \ && git config --global url."https://github.com/".insteadOf "git@github.com:" \ && git config --global url."https://github.com/".insteadOf "ssh://git@github.com/" -RUN npm i -COPY ./frontend/ ./ +RUN cd frontend && npm i +COPY ./frontend/ ./frontend/ +WORKDIR /build/frontend RUN npm run build:docker FROM alpine:latest -ENV FILEBROWSER_DATABASE="/home/filebrowser/data/database.db" +ENV FILEBROWSER_DATABASE_PATH="/home/filebrowser/data/database.sqlite" ENV FILEBROWSER_CONFIG="/home/filebrowser/data/config.yaml" ENV PATH="$PATH:/home/filebrowser" RUN apk --no-cache add ca-certificates mailcap tzdata curl @@ -31,7 +32,7 @@ COPY --from=base --chown=filebrowser:1000 [ "/app/filebrowser", "./" ] COPY --from=base --chown=filebrowser:1000 [ "/app/config.yaml", "./data/config.yaml" ] COPY --from=base --chown=filebrowser:1000 [ "/app/config.yaml", "./" ] COPY --from=base --chown=filebrowser:1000 [ "/app/reduce-rounded-corners.css", "./" ] -COPY --from=nbuild --chown=filebrowser:1000 [ "/app/dist/", "./http/dist/" ] +COPY --from=nbuild --chown=filebrowser:1000 [ "/build/backend/internal/web/dist/", "./internal/web/dist/" ] ## sanity checks RUN [ "filebrowser", "version" ] # exposing default port for auto discovery. diff --git a/_docker/docker-compose.yaml b/_docker/docker-compose.yaml index a0dc66c376..37fa3458c3 100644 --- a/_docker/docker-compose.yaml +++ b/_docker/docker-compose.yaml @@ -12,7 +12,7 @@ services: - ../frontend/generated:/app/frontend/generated entrypoint: ["/bin/sh", "-c", "./filebrowser & sleep 2 && cd ../frontend && npx playwright test --project dark-screenshots && npx playwright test --project light-screenshots"] build: - dockerfile: ./_docker/Dockerfile.playwright-local + dockerfile: ./_docker/Dockerfile.playwright-screenshots context: ../ nginx-proxy-auth: image: nginx diff --git a/_docker/src/general/backend/config.yaml b/_docker/src/general/backend/config.yaml index 12d561d508..fc2cd5bace 100644 --- a/_docker/src/general/backend/config.yaml +++ b/_docker/src/general/backend/config.yaml @@ -1,5 +1,7 @@ server: <<: *server-main +http: + <<: *http-main frontend: <<: *frontend-main @@ -12,7 +14,6 @@ userDefaults: models: true office: true highQuality: true - permissions: - download: true - create: true - share: true + account: + permissions: + share: true diff --git a/_docker/src/general/backend/server-config.yaml b/_docker/src/general/backend/server-config.yaml index dea4483ea7..f12ca5c232 100644 --- a/_docker/src/general/backend/server-config.yaml +++ b/_docker/src/general/backend/server-config.yaml @@ -1,6 +1,7 @@ -server-main: &server-main +http-main: &http-main port: 80 baseURL: "/" +server-main: &server-main logging: - levels: "info|error|warning|debug" apiFilter: 'disabled' @@ -9,6 +10,11 @@ server-main: &server-main name: "playwright + files" config: defaultEnabled: true + defaultPermissions: + view: true + download: true + modify: true + create: true - path: "." name: "docker" config: diff --git a/_docker/src/jwt/backend/config.yaml b/_docker/src/jwt/backend/config.yaml index 4ff67f8448..fe38cfea67 100644 --- a/_docker/src/jwt/backend/config.yaml +++ b/_docker/src/jwt/backend/config.yaml @@ -1,5 +1,6 @@ -server: +http: port: 8080 +server: logging: - levels: "info|error|warning|debug" apiFilter: 'disabled' @@ -8,6 +9,11 @@ server: config: defaultEnabled: true createUserDir: true + defaultPermissions: + view: true + download: true + modify: true + create: true frontend: name: "Graham's Filebrowser" @@ -31,19 +37,17 @@ auth: groupsClaim: "mygroup" adminGroup: "admin" userDefaults: + ui: + darkMode: true + account: + disableSettings: false + permissions: + share: true + listing: + singleClick: false preview: image: true popup: true video: true office: true highQuality: true - darkMode: true - disableSettings: false - singleClick: false - permissions: - admin: false - modify: true - share: true - api: false - download: true - create: true \ No newline at end of file diff --git a/_docker/src/noauth/backend/config.yaml b/_docker/src/noauth/backend/config.yaml index 8518362e84..720ccd09d3 100644 --- a/_docker/src/noauth/backend/config.yaml +++ b/_docker/src/noauth/backend/config.yaml @@ -1,6 +1,7 @@ -server: +http: port: 80 baseURL: "/files/" +server: logging: - levels: "info|error|warning|debug" apiFilter: 'disabled' @@ -9,6 +10,11 @@ server: name: "exclude" config: defaultEnabled: true + defaultPermissions: + view: true + download: true + modify: true + create: true rules: - folderPath: "excluded" - folderPath: "excludedButVisible" @@ -28,16 +34,13 @@ server: - filePath: "/subfolderExclusions/exclusionlist.sh" - folderPath: "/subfolderExclusions/folderItem" viewable: true - conditionals: - rules: - - fileStartsWith: "startsWith" - - folderEndsWith: "Folder" - - folderNames: 'folderNames' - - fileNames: 'fileNames' - - folderName: 'folderName' - - fileName: 'fileName' - - folderName: '.hiddenDir' - - fileName: '.hidden' + - fileStartsWith: "startsWith" + - folderEndsWith: "Folder" + - folderName: "folderName" + - fileName: "fileName" + - fileName: "fileNames" + - folderName: ".hiddenDir" + - fileName: ".hidden" auth: methods: @@ -54,13 +57,11 @@ frontend: disableEventThemes: true userDefaults: - showHidden: true + listing: + showHidden: true preview: image: true popup: true video: true office: true - highQuality: true - permissions: - download: true - create: true \ No newline at end of file + highQuality: true \ No newline at end of file diff --git a/_docker/src/oidc/backend/config.yaml b/_docker/src/oidc/backend/config.yaml index 2b3ccc3ece..ab4d22e470 100644 --- a/_docker/src/oidc/backend/config.yaml +++ b/_docker/src/oidc/backend/config.yaml @@ -7,6 +7,11 @@ server: config: defaultEnabled: true createUserDir: true + defaultPermissions: + view: true + download: true + modify: true + create: true frontend: name: "Graham's Filebrowser" @@ -36,13 +41,13 @@ userDefaults: video: true office: true highQuality: true - darkMode: true - disableSettings: false - singleClick: false - permissions: - admin: false - modify: true - share: false - api: false - download: true - create: true \ No newline at end of file + ui: + darkMode: true + listing: + singleClick: false + account: + disableSettings: false + permissions: + admin: false + share: false + api: false \ No newline at end of file diff --git a/_docker/src/previews/backend/config.yaml b/_docker/src/previews/backend/config.yaml index 9bde69cab3..8eb07bd76b 100644 --- a/_docker/src/previews/backend/config.yaml +++ b/_docker/src/previews/backend/config.yaml @@ -1,11 +1,18 @@ -server: +http: port: 80 baseURL: "/" +server: logging: - levels: "info|error|warning|debug" apiFilter: 'disabled' sources: - path: "../frontend/tests/playwright-files" + config: + defaultPermissions: + view: true + download: true + modify: true + create: true auth: methods: @@ -22,7 +29,8 @@ frontend: disableEventThemes: true userDefaults: - showHidden: true + listing: + showHidden: true preview: image: true popup: true @@ -31,6 +39,3 @@ userDefaults: office: true models: true highQuality: true - permissions: - download: true - create: true diff --git a/_docker/src/proxy/backend/config.yaml b/_docker/src/proxy/backend/config.yaml index c4886b48d6..393d0cfc4e 100644 --- a/_docker/src/proxy/backend/config.yaml +++ b/_docker/src/proxy/backend/config.yaml @@ -1,6 +1,8 @@ -server: +http: port: 8080 - baseURL: "/subpath" + baseURL: "/subpath" + trustProxyHeaders: true +server: logging: - levels: "info|error|warning|debug" apiFilter: 'disabled' @@ -9,6 +11,11 @@ server: config: defaultEnabled: true createUserDir: true + defaultPermissions: + view: true + download: true + modify: true + create: true frontend: name: "Graham's Filebrowser" @@ -30,19 +37,6 @@ auth: logoutRedirectUrl: "https://localhost/api/auth/logout2" userDefaults: - preview: - image: true - popup: true - video: true - office: true - highQuality: true - darkMode: true - disableSettings: false - singleClick: false - permissions: - admin: false - modify: true - share: true - api: false - download: true - create: true \ No newline at end of file + account: + permissions: + share: true diff --git a/_docker/src/screenshots/backend/config.yaml b/_docker/src/screenshots/backend/config.yaml index dcaeb34e9c..56587c32c0 100644 --- a/_docker/src/screenshots/backend/config.yaml +++ b/_docker/src/screenshots/backend/config.yaml @@ -1,6 +1,7 @@ -server: +http: port: 8080 baseURL: "/files/" +server: logging: - levels: "info|error|warning|debug" apiFilter: 'disabled' diff --git a/_docker/src/settings/backend/config.yaml b/_docker/src/settings/backend/config.yaml index eb85625b96..462aa3fd6d 100644 --- a/_docker/src/settings/backend/config.yaml +++ b/_docker/src/settings/backend/config.yaml @@ -1,6 +1,9 @@ -server: +http: port: 80 baseURL: "/" +server: + database: + migrateFrom: "database.db.old" logging: - levels: "info|error|warning|debug" apiFilter: 'disabled' @@ -9,6 +12,8 @@ server: name: "playwright + files" config: defaultEnabled: true + defaultPermissions: + modify: false - path: "." name: "docker" config: @@ -38,4 +43,8 @@ frontend: auth: methods: password: - signup: true \ No newline at end of file + signup: true + +userDefaults: + listing: + showHidden: true \ No newline at end of file diff --git a/_docker/src/settings/backend/database.db.old b/_docker/src/settings/backend/database.db.old new file mode 100644 index 0000000000..8e8b4057f8 Binary files /dev/null and b/_docker/src/settings/backend/database.db.old differ diff --git a/_docker/src/sharing/backend/config.yaml b/_docker/src/sharing/backend/config.yaml index 6ec28f114b..b2bc94b30a 100644 --- a/_docker/src/sharing/backend/config.yaml +++ b/_docker/src/sharing/backend/config.yaml @@ -1,6 +1,7 @@ -server: +http: port: 80 baseURL: "/" +server: logging: - levels: "info|error|warning|debug" apiFilter: 'disabled' diff --git a/backend/.air.toml b/backend/.air.toml index 0a31cdfcac..6396ca59ee 100644 --- a/backend/.air.toml +++ b/backend/.air.toml @@ -2,11 +2,11 @@ root = "." tmp_dir = "tmp" [build] - cmd = "go build -o ./tmp/filebrowser --tags=mupdf --ldflags=\"-w -s -X 'github.com/gtsteffaniak/filebrowser/backend/common/version.CommitSHA=commitSHA' -X 'github.com/gtsteffaniak/filebrowser/backend/common/version.Version=version'\" ." - bin = "tmp/filebrowser" + cmd = "go build -o ./tmp/filebrowser --tags=mupdf --ldflags=\"-w -s -X 'github.com/gtsteffaniak/filebrowser/backend/internal/version.CommitSHA=commitSHA' -X 'github.com/gtsteffaniak/filebrowser/backend/internal/version.Version=version'\" ." + entrypoint = "./tmp/filebrowser" full_bin = "FILEBROWSER_DEVMODE=true CGO_ENABLED=1 ./tmp/filebrowser -c test_config.yaml" include_ext = ["go", "tpl", "tmpl", "html"] - exclude_dir = ["tmp", "vendor", "http/dist", "http/embed", "swagger/docs", "preview/thumbnails", "preview/heic"] + exclude_dir = ["tmp", "vendor", "internal/web/dist", "internal/web/embed", "internal/preview/testdata", "internal/preview/thumbnails", "internal/preview/heic", "swagger/docs"] log = "air.log" delay = 1000 # ms diff --git a/backend/.air.windows.toml b/backend/.air.windows.toml index ba5b9273c2..a69b309d41 100644 --- a/backend/.air.windows.toml +++ b/backend/.air.windows.toml @@ -2,11 +2,11 @@ root = "." tmp_dir = "tmp" [build] - cmd = "go build -o ./tmp/filebrowser.exe --ldflags=\"-w -s -X 'github.com/gtsteffaniak/filebrowser/backend/common/version.CommitSHA=commitSHA' -X 'github.com/gtsteffaniak/filebrowser/backend/common/version.Version=version'\" ." - bin = "tmp/filebrowser.exe" - args_bin = ["-c", "test_config.yaml"] + cmd = "go build -o ./tmp/filebrowser.exe --ldflags=\"-w -s -X 'github.com/gtsteffaniak/filebrowser/backend/internal/version.CommitSHA=commitSHA' -X 'github.com/gtsteffaniak/filebrowser/backend/internal/version.Version=version'\" ." + entrypoint = "./tmp/filebrowser.exe" + full_bin = "FILEBROWSER_DEVMODE=true CGO_ENABLED=1 ./tmp/filebrowser.exe -c test_config.yaml" include_ext = ["go", "tpl", "tmpl", "html"] - exclude_dir = ["tmp", "vendor", "http\\dist", "http\\embed", "swagger\\docs"] + exclude_dir = ["tmp", "vendor", "internal\\web\\dist", "internal\\web\\embed", "internal\\preview\\testdata", "internal\\preview\\thumbnails", "internal\\preview\\heic", "swagger\\docs"] exclude_unchanged = true follow_symlink = false poll = true diff --git a/backend/.goreleaser.yaml b/backend/.goreleaser.yaml index 535fc05363..a37b658616 100644 --- a/backend/.goreleaser.yaml +++ b/backend/.goreleaser.yaml @@ -9,10 +9,11 @@ builds: - CGO_ENABLED=1 - CC=zig cc -target x86_64-linux-musl tags: + - analytics - mupdf - musl ldflags: &ldflags - - -s -w -X github.com/gtsteffaniak/filebrowser/backend/common/version.Version=v{{ .Version }} -X github.com/gtsteffaniak/filebrowser/backend/common/version.CommitSHA={{ .ShortCommit }} + - -s -w -X github.com/gtsteffaniak/filebrowser/backend/internal/version.Version=v{{ .Version }} -X github.com/gtsteffaniak/filebrowser/backend/internal/version.CommitSHA={{ .ShortCommit }} main: main.go binary: filebrowser goos: @@ -32,6 +33,7 @@ builds: - CGO_ENABLED=1 - CC=zig cc -target aarch64-linux-musl tags: + - analytics - mupdf - musl goos: @@ -47,6 +49,8 @@ builds: ldflags: *ldflags main: main.go binary: filebrowser + tags: + - analytics goos: - linux goarch: @@ -64,6 +68,7 @@ builds: - CGO_ENABLED=1 - CC=zig cc -target x86_64-windows tags: + - analytics - mupdf ldflags: *ldflags main: main.go @@ -81,6 +86,8 @@ builds: ldflags: *ldflags main: main.go binary: filebrowser + tags: + - analytics goos: - freebsd goarch: @@ -91,6 +98,8 @@ builds: ldflags: *ldflags main: main.go binary: filebrowser + tags: + - analytics goos: - darwin goarch: diff --git a/backend/adapters/fs/fileutils/file_test.go b/backend/adapters/fs/fileutils/file_test.go deleted file mode 100644 index abef1029a0..0000000000 --- a/backend/adapters/fs/fileutils/file_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package fileutils - -import ( - "os" - "testing" -) - -func TestUnixModeToFileMode_setgid(t *testing.T) { - m := unixModeToFileMode(0o2770) - if got := m.Perm(); got != 0o770 { - t.Fatalf("Perm() = %#o, want 0770", got) - } - if m&os.ModeSetgid == 0 { - t.Fatal("expected ModeSetgid") - } - if m&os.ModeSetuid != 0 || m&os.ModeSticky != 0 { - t.Fatalf("unexpected special bits: %#o", m) - } -} - -func TestCommonPrefix(t *testing.T) { - testCases := map[string]struct { - paths []string - want string - }{ - "same lvl": { - paths: []string{ - "/home/user/file1", - "/home/user/file2", - }, - want: "/home/user", - }, - "sub folder": { - paths: []string{ - "/home/user/folder", - "/home/user/folder/file", - }, - want: "/home/user/folder", - }, - "relative path": { - paths: []string{ - "/home/user/folder", - "/home/user/folder/../folder2", - }, - want: "/home/user", - }, - "no common path": { - paths: []string{ - "/home/user/folder", - "/etc/file", - }, - want: "", - }, - } - for name, tt := range testCases { - t.Run(name, func(t *testing.T) { - if got := CommonPrefix('/', tt.paths...); got != tt.want { - t.Errorf("CommonPrefix() = %v, want %v", got, tt.want) - } - }) - } -} diff --git a/backend/auth/json.go b/backend/auth/json.go deleted file mode 100644 index ae95f65494..0000000000 --- a/backend/auth/json.go +++ /dev/null @@ -1,121 +0,0 @@ -package auth - -import ( - "encoding/json" - "fmt" - "net/http" - "net/url" - "os" - "strings" - - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/users" -) - -// JSONAuth is a json implementation of an Auther. -type JSONAuth struct { - ReCaptcha *ReCaptcha `json:"recaptcha" yaml:"recaptcha"` - DisableOtp bool `json:"disableOtp" yaml:"disableOtp"` -} - -// Auth authenticates the user via a json in content body. -func (auther JSONAuth) Auth(r *http.Request, userStore *users.Storage) (*users.User, error) { - username := r.URL.Query().Get("username") - recaptcha := r.URL.Query().Get("recaptcha") - password := r.Header.Get("X-Password") - totpCode := r.Header.Get("X-Secret") - // URL-decode password to support special characters in headers - password, err := url.QueryUnescape(password) - if err != nil { - return nil, fmt.Errorf("invalid password encoding: %v", err) - } - - // If ReCaptcha is enabled, check the code. - if auther.ReCaptcha != nil && len(auther.ReCaptcha.Secret) > 0 { - ok, err := auther.ReCaptcha.Ok(recaptcha) //nolint:govet - - if err != nil { - return nil, err - } - - if !ok { - return nil, os.ErrPermission - } - } - - user, getErr := userStore.Get(username) - var passwordHash string - if getErr != nil { - passwordHash = utils.InvalidPasswordHash - } else { - passwordHash = user.Password - } - // always run checkPwd to prevent timing attacks - err = utils.CheckPwd(password, passwordHash) - if err != nil { - return nil, err - } - if getErr != nil { - return nil, fmt.Errorf("unable to get user from store: %v", err) - } - if user.TOTPSecret != "" && !auther.DisableOtp { - if totpCode == "" { - return nil, errors.ErrNoTotpProvided - } - err = VerifyTotpCode(user, totpCode, userStore) - if err != nil { - return nil, err - } - } - - if user.LoginMethod != users.LoginMethodPassword { - return nil, errors.ErrWrongLoginMethod - } - - return user, nil - -} - -const reCaptchaAPI = "/recaptcha/api/siteverify" - -// ReCaptcha identifies a recaptcha connection. -type ReCaptcha struct { - Host string `json:"host"` - Key string `json:"key"` - Secret string `json:"secret"` -} - -// Ok checks if a reCaptcha responde is correct. -func (r *ReCaptcha) Ok(response string) (bool, error) { - body := url.Values{} - body.Set("secret", r.Secret) - body.Add("response", response) - - client := &http.Client{} - - resp, err := client.Post( - r.Host+reCaptchaAPI, - "application/x-www-form-urlencoded", - strings.NewReader(body.Encode()), - ) - if err != nil { - return false, err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return false, nil - } - - var data struct { - Success bool `json:"success"` - } - - err = json.NewDecoder(resp.Body).Decode(&data) - if err != nil { - return false, err - } - - return data.Success, nil -} diff --git a/backend/auth/none.go b/backend/auth/none.go deleted file mode 100644 index ccfce876c9..0000000000 --- a/backend/auth/none.go +++ /dev/null @@ -1,18 +0,0 @@ -package auth - -import ( - "net/http" - - "github.com/gtsteffaniak/filebrowser/backend/database/users" -) - -// MethodNoAuth is used to identify no auth. -const MethodNoAuth = "noauth" - -// NoAuth is no auth implementation of auther. -type NoAuth struct{} - -// Auth uses authenticates user 1. -func (a NoAuth) Auth(r *http.Request, usr *users.Storage) (*users.User, error) { - return usr.Get(uint(1)) -} diff --git a/backend/auth/proxy.go b/backend/auth/proxy.go deleted file mode 100644 index d3c8b19493..0000000000 --- a/backend/auth/proxy.go +++ /dev/null @@ -1,28 +0,0 @@ -package auth - -import ( - "net/http" - "os" - - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/database/users" -) - -// MethodProxyAuth is used to identify no auth. -const MethodProxyAuth = "proxy" - -// ProxyAuth is a proxy implementation of an auther. -type ProxyAuth struct { - Header string `json:"header"` -} - -// Auth authenticates the user via an HTTP header. -func (a ProxyAuth) Auth(r *http.Request, usr *users.Storage) (*users.User, error) { - username := r.Header.Get(a.Header) - user, err := usr.Get(username) - if err == errors.ErrNotExist { - return nil, os.ErrPermission - } - - return user, err -} diff --git a/backend/cmd/access.go b/backend/cmd/access.go index b649c1342e..6445f8946e 100644 --- a/backend/cmd/access.go +++ b/backend/cmd/access.go @@ -4,27 +4,23 @@ import ( "fmt" "strings" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/database/access" + "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/internal/database/access" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" "github.com/gtsteffaniak/go-logger/logger" ) // validateAccessRules migrates old-style access rules (without trailing slashes) to new format func validateAccessRules() { - if store.Access == nil { - return - } - // Get all sources for sourcePath := range settings.Config.Server.SourceMap { - // Get all rules for this source - rules, err := store.Access.GetAllRules(sourcePath) + rules, err := state.GetAllRules(sourcePath) if err != nil { logger.Errorf("Failed to get access rules for source %s: %v", sourcePath, err) continue } - // Check if there are any rules that need migration needsMigration := false for oldPath := range rules { if oldPath != "/" && !strings.HasSuffix(oldPath, "/") { @@ -39,78 +35,55 @@ func validateAccessRules() { migratedCount := 0 for oldPath, rule := range rules { - // Check if this path needs migration (doesn't have trailing slash and isn't root) if oldPath != "/" && !strings.HasSuffix(oldPath, "/") { - // Create the new path with trailing slash newPath := oldPath + "/" - // Migrate the rule to the new path - if err := migrateAccessRule(sourcePath, oldPath, newPath, rule); err != nil { + if err := migrateAccessRule(sourcePath, newPath, rule); err != nil { logger.Errorf("Failed to migrate rule from %s to %s: %v", oldPath, newPath, err) continue } - // Remove the old rule - if err := removeOldAccessRule(sourcePath, oldPath); err != nil { - logger.Errorf("Failed to remove old rule %s: %v", oldPath, err) - continue - } - + state.RemoveRuleByPathKey(sourcePath, oldPath) migratedCount++ } } - // After migration, clear cache if migratedCount > 0 { logger.Infof("Migrated %d access rules for source %s", migratedCount, sourcePath) } } } -// migrateAccessRule creates a new access rule with the new path format -func migrateAccessRule(sourcePath, oldPath, newPath string, rule access.FrontendAccessRule) error { - // Add deny users +func migrateAccessRule(sourcePath, newPath string, rule access.FrontendAccessRule) error { for _, user := range rule.Deny.Users { - if err := store.Access.DenyUser(sourcePath, newPath, user); err != nil && err != errors.ErrExist { + if err := state.DenyUser(sourcePath, utils.IndexPathFromNormalized(newPath, true), user); err != nil && err != errors.ErrExist { return fmt.Errorf("failed to add deny user %s: %w", user, err) } } - // Add deny groups for _, group := range rule.Deny.Groups { - if err := store.Access.DenyGroup(sourcePath, newPath, group); err != nil && err != errors.ErrExist { + if err := state.DenyGroup(sourcePath, utils.IndexPathFromNormalized(newPath, true), group); err != nil && err != errors.ErrExist { return fmt.Errorf("failed to add deny group %s: %w", group, err) } } - // Add allow users for _, user := range rule.Allow.Users { - if err := store.Access.AllowUser(sourcePath, newPath, user); err != nil && err != errors.ErrExist { + if err := state.AllowUser(sourcePath, utils.IndexPathFromNormalized(newPath, true), user); err != nil && err != errors.ErrExist { return fmt.Errorf("failed to add allow user %s: %w", user, err) } } - // Add allow groups for _, group := range rule.Allow.Groups { - if err := store.Access.AllowGroup(sourcePath, newPath, group); err != nil && err != errors.ErrExist { + if err := state.AllowGroup(sourcePath, utils.IndexPathFromNormalized(newPath, true), group); err != nil && err != errors.ErrExist { return fmt.Errorf("failed to add allow group %s: %w", group, err) } } - // Add deny all rule if needed if rule.DenyAll { - if err := store.Access.DenyAll(sourcePath, newPath); err != nil && err != errors.ErrExist { + if err := state.DenyAll(sourcePath, utils.IndexPathFromNormalized(newPath, true)); err != nil && err != errors.ErrExist { return fmt.Errorf("failed to add deny all rule: %w", err) } } return nil } - -// removeOldAccessRule removes the old access rule by directly accessing the internal storage -func removeOldAccessRule(sourcePath, oldPath string) error { - // Access the internal storage directly to remove the old rule - // We need to use the unnormalized path since that's how it was stored originally - store.Access.RemoveRuleByPath(sourcePath, oldPath) - return nil -} diff --git a/backend/cmd/admin_share_test.go b/backend/cmd/admin_share_test.go new file mode 100644 index 0000000000..458dc12866 --- /dev/null +++ b/backend/cmd/admin_share_test.go @@ -0,0 +1,204 @@ +package cmd + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/app" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" +) + +func TestAdminHasSharePermissionAfterPlaywrightStartup(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + sharingConfig := "../../_docker/src/sharing/backend/config.yaml" + settings.Initialize(sharingConfig) + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := state.Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + app.MustWireServices(state.Default()) + t.Cleanup(func() { _ = state.Close() }) + + validateUserInfo(true) + + admin, err := state.GetUserByUsername("admin") + if err != nil { + t.Fatal(err) + } + if !admin.Permissions.Share { + t.Fatalf("admin Share=false after validateUserInfo; perms=%+v", admin.Permissions) + } + if !admin.Permissions.Admin { + t.Fatalf("admin Admin=false; perms=%+v", admin.Permissions) + } + + _ = state.Close() + _, err = state.Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + app.MustWireServices(state.Default()) + admin, err = state.GetUserByUsername("admin") + if err != nil { + t.Fatal(err) + } + if !admin.Permissions.Share { + t.Fatalf("admin Share=false after DB reload; perms=%+v", admin.Permissions) + } +} + +func TestAdminHasSharePermissionAfterSettingsMigration(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize(settingsMigrationConfigPath(t)) + settings.Env.IsPlaywright = true + alignSettingsSourcesForMigrationFixture(t) + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + settings.Config.Server.DatabaseV2.Path = dbPath + settings.Config.Server.DatabaseV2.MigrateFrom = settingsMigrationBoltPath(t) + + if err := migrateFromBoltToSQLite(); err != nil { + t.Fatal(err) + } + + _, err := state.Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + app.MustWireServices(state.Default()) + t.Cleanup(func() { _ = state.Close() }) + + validateUserInfo(false) + + admin, err := state.GetUserByUsername("admin") + if err != nil { + t.Fatal(err) + } + if !admin.Permissions.Share { + t.Fatalf("admin Share=false after settings migration; perms=%+v", admin.Permissions) + } + assertSourceSidebarLinkCount(t, &admin, 3) +} + +func TestGrahamNoAccessAfterSettingsMigrationStartup_dockerSourcePaths(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + configPath := filepath.Join(t.TempDir(), "config.yaml") + configYAML := `server: + sources: + - path: "/app/frontend/tests/playwright-files" + name: "playwright + files" + config: + defaultEnabled: true + - path: "/app/backend" + name: "docker" + config: + defaultEnabled: true + - path: "/tests/playwright-files" + name: "access" + config: + defaultEnabled: true + denyByDefault: true +auth: + methods: + password: + enabled: true +` + if err := os.WriteFile(configPath, []byte(configYAML), 0o600); err != nil { + t.Fatal(err) + } + settings.Initialize(configPath) + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + settings.Config.Server.DatabaseV2.Path = dbPath + settings.Config.Server.DatabaseV2.MigrateFrom = settingsMigrationBoltPath(t) + if err := migrateFromBoltToSQLite(); err != nil { + t.Fatal(err) + } + + _, err := state.Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + app.MustWireServices(state.Default()) + t.Cleanup(func() { _ = state.Close() }) + + validateUserInfo(false) + + graham, err := state.GetUserByUsername("graham") + if err != nil { + t.Fatal(err) + } + for _, scope := range graham.BackendScopes { + if scope.Path == fixtureAccessSource { + t.Fatalf("graham gained access scope: %#v", graham.BackendScopes) + } + } + for _, link := range graham.SidebarLinks { + if link.Name == "access" { + t.Fatalf("graham has access sidebar link: %#v", graham.SidebarLinks) + } + } +} + +func TestGrahamNoAccessAfterSettingsMigrationStartup(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize(settingsMigrationConfigPath(t)) + settings.Env.IsPlaywright = true + alignSettingsSourcesForMigrationFixture(t) + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + settings.Config.Server.DatabaseV2.Path = dbPath + settings.Config.Server.DatabaseV2.MigrateFrom = settingsMigrationBoltPath(t) + if err := migrateFromBoltToSQLite(); err != nil { + t.Fatal(err) + } + + _, err := state.Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + app.MustWireServices(state.Default()) + t.Cleanup(func() { _ = state.Close() }) + + validateUserInfo(false) + + graham, err := state.GetUserByUsername("graham") + if err != nil { + t.Fatal(err) + } + for _, scope := range graham.BackendScopes { + if scope.Path == fixtureAccessSource { + t.Fatalf("graham gained access scope after validateUserInfo: %#v", graham.BackendScopes) + } + } + for _, link := range graham.SidebarLinks { + if link.Name == "access" { + t.Fatalf("graham has access sidebar link after validateUserInfo: %#v", graham.SidebarLinks) + } + } + if len(graham.SidebarLinks) == 0 { + t.Fatal("graham should have sidebar links after migration so frontend does not fall back to all sources") + } +} + +func assertSourceSidebarLinkCount(t *testing.T, user *users.User, want int) { + t.Helper() + count := 0 + for _, link := range user.SidebarLinks { + if strings.HasPrefix(link.Category, "source") { + count++ + } + } + if count != want { + t.Fatalf("user %q has %d source sidebar links, want %d: %v", + user.Username, count, want, user.SidebarLinks) + } +} diff --git a/backend/cmd/cli.go b/backend/cmd/cli.go index f8373a327a..ef281d5e08 100644 --- a/backend/cmd/cli.go +++ b/backend/cmd/cli.go @@ -2,7 +2,6 @@ package cmd import ( "bufio" - "flag" "fmt" "os" "path/filepath" @@ -10,11 +9,12 @@ import ( "strings" "github.com/goccy/go-yaml" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/version" - "github.com/gtsteffaniak/filebrowser/backend/database/storage" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "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" ) @@ -22,169 +22,44 @@ var ( configPath string ) -// return bool to indicate if the program should continue running -func runCLI() (bool, bool) { - - generateYaml() - - // Global flags - var help bool - // Override the default usage output to use generalUsage() - flag.Usage = generalUsage - flag.StringVar(&configPath, "c", "", "Path to the config file, default: config.yaml") - flag.BoolVar(&help, "h", false, "Get help about commands") - - if configPath == "" { - configPath = os.Getenv("FILEBROWSER_CONFIG") - // backwards compatibility in docker, prefer config.yaml if it exists - if configPath != "" { - _, err := os.Stat(configPath) - if err != nil { - logger.Fatalf("config file %v does not exist, please create it or set the FILEBROWSER_CONFIG environment variable to a valid config file path", configPath) - } - } else { - configPath = "config.yaml" - } - } - - // Parse global flags (before subcommands) - flag.Parse() // print generalUsage on error - - // Show help if requested - if help { - generalUsage() - return false, false - } - - // Create a new FlagSet for the 'set' subcommand - setCmd := flag.NewFlagSet("set", flag.ExitOnError) - var user, dbConfig string - var asAdmin bool - var sourceName, indexPath, ruleCategory, value string - var allow bool - - setCmd.StringVar(&user, "u", "", "Comma-separated username and password: \"set -u ,\"") - setCmd.BoolVar(&asAdmin, "a", false, "Create a user as admin user, used in combination with -u") - setCmd.StringVar(&dbConfig, "c", "config.yaml", "Path to the config file, default: config.yaml") - setCmd.StringVar(&sourceName, "s", "", "source name to apply the rule to") - setCmd.StringVar(&indexPath, "p", "", "Index path (e.g. /secret) for rule command") - setCmd.StringVar(&ruleCategory, "r", "", "Rule category: 'user', 'group', or 'all' (for deny only)") - setCmd.StringVar(&value, "v", "", "Value: username or groupname (not required if ruleCategory is 'all')") - setCmd.BoolVar(&allow, "allow", false, "Allow access (default: false, which means deny)") - - storeCfg := configPath - cliSubcmd := "" - var setKind string - - if len(os.Args) > 1 { - switch os.Args[1] { - case "version": - fmt.Printf(`FileBrowser Quantum - A modern web-based file manager - Version : %v - Commit : %v - Release Info : https://github.com/gtsteffaniak/filebrowser/releases/tag/%v -`, version.Version, version.CommitSHA, version.Version) - return false, false - case "setup": - cliSubcmd = "setup" - case "set": - cliSubcmd = "set" - if len(os.Args) < 3 { - fmt.Printf("error: missing subcommand for 'set'. Use 'set user' or 'set rule'\n") - os.Exit(1) - } - setKind = os.Args[2] - var err error - // Handle old syntax: "set -u user,pass -c config.yaml" - if setKind == "-u" { - err = setCmd.Parse(os.Args[2:]) - } else { - // New pattern: subcommand-based (e.g., "set user" or "set rule") - err = setCmd.Parse(os.Args[3:]) - } - if err != nil { - setCmd.PrintDefaults() - os.Exit(1) - } - storeCfg = dbConfig - } - } - - switch cliSubcmd { - case "setup": - createConfig(configPath) - return false, false - case "set": - if setKind == "-u" { - dbExists := getStore(storeCfg) - logger.Debugf("setUser called with args: %v, config: %v, admin: %v", os.Args, dbConfig, asAdmin) - err := setUser(dbConfig, asAdmin) - if err != nil { - fmt.Printf("error: %v\n", err) - os.Exit(1) - } - return false, dbExists - } - switch setKind { - case "rule": - dbExists := getStore(storeCfg) - sourceInfo, ok := settings.Config.Server.NameToSource[sourceName] // backend source is path - if !ok { - fmt.Printf("error: invalid source name: %s\n", sourceName) - os.Exit(1) - } - err := setRule(dbConfig, sourceInfo.Path, indexPath, ruleCategory, value, allow) - if err != nil { - fmt.Printf("error: %v\n", err) - os.Exit(1) - } - return false, dbExists - default: - fmt.Printf("error: unknown subcommand '%s' for 'set'. Use 'set user' or 'set rule'\n", setKind) - os.Exit(1) - } - return false, false - default: - dbExists := getStore(storeCfg) - return true, dbExists - } -} - -func setRule(dbConfig, fsPath, indexPath, ruleCategory, value string, allow bool) error { - // Validate required parameters - if fsPath == "" { - return fmt.Errorf("real filesystem path is required: use -f ") +func setRule(backendSourcePath, indexPath, ruleCategory, value string, allow bool) error { + if backendSourcePath == "" { + return fmt.Errorf("backend source path is missing; check --source / -s") } if indexPath == "" { - return fmt.Errorf("index path is required: use -p ") + return fmt.Errorf("--path / -p is required (index path within the source, e.g. /)") } if ruleCategory == "" { - return fmt.Errorf("ruleCategory is required: use -r ") + return fmt.Errorf("role is required: use --role / -r ") } if ruleCategory != "all" && value == "" { - return fmt.Errorf("value is required when ruleCategory is 'user' or 'group': use -v ") + return fmt.Errorf("value is required when role is 'user' or 'group': use --value / -v ") } - // Apply the rule based on allow flag and ruleCategory - var err error + + parsedPath, err := utils.ParseSanitizedIndexPath(indexPath, true) + if err != nil { + return err + } + if allow { switch ruleCategory { case "user": - err = store.Access.AllowUser(fsPath, indexPath, value) + err = state.AllowUser(backendSourcePath, parsedPath, value) case "group": - err = store.Access.AllowGroup(fsPath, indexPath, value) + err = state.AllowGroup(backendSourcePath, parsedPath, value) default: - return fmt.Errorf("invalid ruleCategory for allow: must be 'user' or 'group'") + return fmt.Errorf("invalid role for allow: must be 'user' or 'group'") } } else { switch ruleCategory { case "user": - err = store.Access.DenyUser(fsPath, indexPath, value) + err = state.DenyUser(backendSourcePath, parsedPath, value) case "group": - err = store.Access.DenyGroup(fsPath, indexPath, value) + err = state.DenyGroup(backendSourcePath, parsedPath, value) case "all": - err = store.Access.DenyAll(fsPath, indexPath) + err = state.DenyAll(backendSourcePath, parsedPath) default: - return fmt.Errorf("invalid ruleCategory: must be 'user', 'group', or 'all'") + return fmt.Errorf("invalid role: must be 'user', 'group', or 'all'") } } @@ -197,42 +72,31 @@ func setRule(dbConfig, fsPath, indexPath, ruleCategory, value string, allow bool action = "allow" } if ruleCategory == "all" { - fmt.Printf("successfully added %s rule for all users on index path '%s' in filesystem path '%s'\n", action, indexPath, fsPath) + fmt.Printf("successfully added %s rule for all users on index path '%s' in filesystem path '%s'\n", action, indexPath, backendSourcePath) } else { - fmt.Printf("successfully added %s rule for %s '%s' on index path '%s' in filesystem path '%s'\n", action, ruleCategory, value, indexPath, fsPath) + fmt.Printf("successfully added %s rule for %s '%s' on index path '%s' in filesystem path '%s'\n", action, ruleCategory, value, indexPath, backendSourcePath) } return nil } -func setUser(dbConfig string, asAdmin bool) error { - if len(os.Args) < 4 { - return fmt.Errorf("missing username and password for 'set user'. Use 'set -u username,password'") - } - userInfo := strings.Split(os.Args[3], ",") - if len(userInfo) < 2 { - return fmt.Errorf("not enough info to create user: \"set -u username,password\", only provided %v", userInfo) - } - username := userInfo[0] - password := userInfo[1] - user, err := store.Users.Get(username) +func setUser(username, password string, asAdmin bool) error { + user, err := state.GetUserByUsername(username) if err != nil { newUser := users.User{ - Username: username, - LoginMethod: users.LoginMethodPassword, - NonAdminEditable: users.NonAdminEditable{ - Password: password, + FrontendUser: users.FrontendUser{ + Username: username, + LoginMethod: users.LoginMethodPassword, }, } for _, source := range settings.Config.Server.SourceMap { if source.Config.DefaultEnabled { - newUser.Scopes = append(newUser.Scopes, users.SourceScope{ - Name: source.Path, + newUser.BackendScopes = append(newUser.BackendScopes, users.BackendScope{ + Path: source.Path, Scope: source.Config.DefaultUserScope, }) } } - // Create the user logic if asAdmin { logger.Infof("Creating user as admin: %s\n", username) } else { @@ -240,28 +104,29 @@ func setUser(dbConfig string, asAdmin bool) error { } newUser.Permissions = settings.ConvertPermissionsToUsers(settings.Config.UserDefaults.Account.Permissions) newUser.Permissions.Admin = asAdmin - err = storage.CreateUser(newUser, newUser.Permissions) + err = state.CreateUser(&newUser, password) if err != nil { return fmt.Errorf("could not create user: %v", err) } + if dirErr := files.MakeUserDirs(&newUser, true); dirErr != nil { + logger.Error(dirErr.Error()) + } fmt.Printf("successfully created user") return nil } if user.LoginMethod != users.LoginMethodPassword { return fmt.Errorf("user %s is not allowed to login with password authentication, cannot set password", username) } - user.Password = password - user.TOTPSecret = "" // reset TOTP secret if it exists - user.TOTPNonce = "" // reset TOTP nonce if it exists + user.TOTPSecret = "" + user.TOTPNonce = "" user.LoginMethod = users.LoginMethodPassword if asAdmin { user.Permissions.Admin = true } - // Ensure version is set for existing users being updated if user.Version == 0 { user.Version = users.CurrentUserMigrationVersion } - err = store.Users.Save(user, true, false) + err = state.UpdateUser(&user, password, "password", "totpSecret", "totpNonce", "loginMethod", "permissions", "version") if err != nil { return fmt.Errorf("could not update user: %v", err) } @@ -269,8 +134,27 @@ func setUser(dbConfig string, asAdmin bool) error { return nil } -// askQuestion displays a prompt and reads a line of input from the user. -// It returns the defaultValue if the user's input is empty. +func promoteUser(username string) error { + user, err := state.GetUserByUsername(username) + if err != nil { + return fmt.Errorf("user %s not found", username) + } + if user.Permissions.Admin { + fmt.Printf("user %s is already an admin\n", username) + return nil + } + user.Permissions.Admin = true + if user.Version == 0 { + user.Version = users.CurrentUserMigrationVersion + } + err = state.UpdateUser(&user, "", "permissions") + if err != nil { + return fmt.Errorf("could not promote user: %v", err) + } + fmt.Printf("successfully promoted user to admin: %s\n", username) + return nil +} + func askQuestion(reader *bufio.Reader, prompt string, defaultValue string) string { fmt.Printf("%s (default: %s): ", prompt, defaultValue) input, _ := reader.ReadString('\n') @@ -281,9 +165,6 @@ func askQuestion(reader *bufio.Reader, prompt string, defaultValue string) strin return input } -// askYesNoQuestion prompts the user with a yes/no question and returns a boolean. -// It retries until valid input ("yes", "y", "no", "n") is received. -// The defaultValue must be "yes" or "no". func askYesNoQuestion(reader *bufio.Reader, prompt string, defaultValue string) bool { for { answer := askQuestion(reader, prompt, defaultValue) @@ -298,43 +179,45 @@ func askYesNoQuestion(reader *bufio.Reader, prompt string, defaultValue string) } } -// createConfig orchestrates the configuration process by asking the user a series of questions. -func createConfig(configpath string) { +func createConfig(configpath string, noInput bool) error { + if noInput { + return fmt.Errorf("'setup' requires interactive input; rerun without --no-input") + } + reader := bufio.NewReader(os.Stdin) config := settings.SetDefaults(false) config.Server.Sources = []*settings.Source{{Path: "./"}} + if configpath == "" { + configpath = "config.yaml" + } + fmt.Println("--- Starting Configuration Setup ---") realPath := "" - // 1. Ask for the source filesystem path (with validation) for { config.Server.Sources[0].Path = askQuestion(reader, "What is the source filesystem path?", "./") - // Convert relative path to absolute path absolutePath, err := filepath.Abs(config.Server.Sources[0].Path) if err == nil { var isDir bool - // Resolve symlinks and get the real path realPath, isDir, _ = iteminfo.ResolveSymlinks(absolutePath) if realPath != "" && isDir { - break // Valid path found, exit loop + break } } fmt.Printf("Error: The path '%s' does not exist or isn't valid. Please try again.\n", config.Server.Sources[0].Path) } - // 2. Ask for the source name defaultSourceName := filepath.Base(realPath) sourceName := askQuestion(reader, "What should the first source name be?", defaultSourceName) if sourceName != defaultSourceName { config.Server.Sources[0].Name = sourceName } - // 3. Ask for server port (with validation) for { portStr := askQuestion(reader, "What port should the server listen on?", "80") port, err := strconv.Atoi(portStr) if err == nil && (port >= 1 && port <= 65535) { - config.Server.Port = port - break // Port is valid, exit loop + config.Http.Port = port + break } fmt.Printf("Error: '%s' is not a valid port. Please enter a number between 1 and 65535.\n", portStr) } @@ -355,53 +238,51 @@ func createConfig(configpath string) { } for { - config.Server.Database = askQuestion(reader, "What should the file name and path be for the database?", "./database.db") - if strings.HasSuffix(config.Server.Database, ".db") { - break // Valid path found, exit loop + config.Server.DatabaseV2.Path = askQuestion(reader, "What should the file name and path be for the database?", "./database.db") + if strings.HasSuffix(config.Server.DatabaseV2.Path, ".db") { + break } - fmt.Printf("Error: '%s' is not a valid path. Please enter a path to a file ending in .db", config.Server.Database) + fmt.Printf("Error: '%s' is not a valid path. Please enter a path to a file ending in .db", config.Server.DatabaseV2.Path) } - // 4. Ask for the application brand name config.Frontend.Name = askQuestion(reader, "What should the application brand name be?", "FileBrowser Quantum") - - // 5. Ask for admin username and password 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") - // 6. Ask boolean (Yes/No) questions using the helper - config.UserDefaults.Account.Permissions.Modify = askYesNoQuestion(reader, "Should a new user be able to modify content by default?", "no") + 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{ + View: true, + Download: true, + Modify: modifyDefault, + Create: modifyDefault, + Delete: modifyDefault, + }) config.UserDefaults.Account.Permissions.Share = askYesNoQuestion(reader, "Should a new user be able to create shares by default?", "no") fmt.Println("--- Configuration Complete ---") - // marshall yaml and write to file - // Marshal the struct to YAML bytes yamlData, err := yaml.Marshal(&config) if err != nil { - return + return fmt.Errorf("marshaling config: %w", err) } - // Write the YAML data to the file - err = os.WriteFile("config.yaml", yamlData, 0644) // 0644 provides read/write for owner, read for others + err = os.WriteFile(configpath, yamlData, 0600) if err != nil { - return + return fmt.Errorf("writing config file: %w", err) } - // cleanup database if it exists - if _, err := os.Stat(config.Server.Database); err == nil { + if _, err := os.Stat(config.Server.DatabaseV2.Path); err == nil { response := askYesNoQuestion(reader, "Database specified already exists. Move database file to backup to start fresh?", "no") if !response { - return + return nil } - // move database file to backup - backupPath := config.Server.Database + ".bak" - err = os.Rename(config.Server.Database, backupPath) + backupPath := config.Server.DatabaseV2.Path + ".bak" + err = os.Rename(config.Server.DatabaseV2.Path, backupPath) if err != nil { fmt.Printf("Error moving database file to backup: %v\n", err) } else { fmt.Printf("Database file moved to backup: %s\n", backupPath) } } - + return nil } func generateYaml() { @@ -414,7 +295,6 @@ func generateYaml() { if generateConfig { os.Exit(0) } - } func SplitByMultiple(str string) []string { diff --git a/backend/cmd/cli_test.go b/backend/cmd/cli_test.go new file mode 100644 index 0000000000..191a5adcfb --- /dev/null +++ b/backend/cmd/cli_test.go @@ -0,0 +1,185 @@ +package cmd + +import ( + "bytes" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/alecthomas/kong" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func freshCLI() cliRoot { + return cliRoot{} +} + +func newCLIParser(t *testing.T, cli *cliRoot) *kong.Kong { + t.Helper() + parser, err := kong.New(cli, kong.Name("filebrowser"), kong.Bind(&cli.Globals)) + require.NoError(t, err) + return parser +} + +func TestParseDefaultServerCommand(t *testing.T) { + cli := freshCLI() + parser := newCLIParser(t, &cli) + ctx, err := parser.Parse([]string{}) + require.NoError(t, err) + assert.Equal(t, "run", ctx.Command()) +} + +func TestParseVersionCommand(t *testing.T) { + cli := freshCLI() + parser := newCLIParser(t, &cli) + ctx, err := parser.Parse([]string{"version"}) + require.NoError(t, err) + assert.Equal(t, "version", ctx.Command()) +} + +func TestParseGlobalConfigFlag(t *testing.T) { + cli := freshCLI() + parser := newCLIParser(t, &cli) + _, err := parser.Parse([]string{"-c", "/tmp/custom.yaml", "version"}) + require.NoError(t, err) + assert.Equal(t, "/tmp/custom.yaml", cli.Config) +} + +func TestParseUserSetWithPasswordFlag(t *testing.T) { + cli := freshCLI() + parser := newCLIParser(t, &cli) + ctx, err := parser.Parse([]string{"user", "set", "alice", "--password", "secret", "--admin"}) + require.NoError(t, err) + assert.Equal(t, "user set ", ctx.Command()) + assert.Equal(t, "alice", cli.User.Set.Username) + assert.True(t, cli.User.Set.Password.Provided) + assert.Equal(t, "secret", cli.User.Set.Password.Inline) + assert.True(t, cli.User.Set.Admin) +} + +func TestParseUserSetConfigFlagOrder(t *testing.T) { + cli := freshCLI() + parser := newCLIParser(t, &cli) + _, err := parser.Parse([]string{"-c", "other.yaml", "user", "set", "bob", "--password", "x"}) + require.NoError(t, err) + assert.Equal(t, "other.yaml", cli.Config) +} + +func TestParseSetRuleFlags(t *testing.T) { + cli := freshCLI() + parser := newCLIParser(t, &cli) + ctx, err := parser.Parse([]string{ + "set", "rule", + "-s", "access", "-p", "/", "-r", "user", "-v", "admin", "--allow", + }) + require.NoError(t, err) + assert.Equal(t, "set rule", ctx.Command()) + assert.Equal(t, "access", cli.Set.Rule.Source) + assert.Equal(t, "/", cli.Set.Rule.Path) + assert.Equal(t, "user", cli.Set.Rule.Role) + assert.Equal(t, "admin", cli.Set.Rule.Value) + assert.True(t, cli.Set.Rule.Allow) +} + +func TestParseLegacySetUser(t *testing.T) { + cli := freshCLI() + parser := newCLIParser(t, &cli) + ctx, err := parser.Parse([]string{"set", "-u", "alice,secret", "-a"}) + require.NoError(t, err) + assert.Equal(t, "set", ctx.Command()) + assert.Equal(t, "alice,secret", cli.Set.User) + assert.True(t, cli.Set.Admin) +} + +func TestPasswordFlagResolveInline(t *testing.T) { + p := passwordFlag{Provided: true, Inline: "inline-pass"} + got, err := p.resolve(true) + require.NoError(t, err) + assert.Equal(t, "inline-pass", got) +} + +func TestPasswordFlagResolveStdin(t *testing.T) { + r, w, err := os.Pipe() + require.NoError(t, err) + oldStdin := os.Stdin + os.Stdin = r + t.Cleanup(func() { os.Stdin = oldStdin }) + + _, err = w.WriteString("piped-secret\n") + require.NoError(t, err) + require.NoError(t, w.Close()) + + p := passwordFlag{Provided: true} + got, err := p.resolve(false) + require.NoError(t, err) + assert.Equal(t, "piped-secret", got) +} + +func TestPasswordFlagMissing(t *testing.T) { + p := passwordFlag{} + _, err := p.resolve(false) + require.Error(t, err) + assert.Contains(t, err.Error(), "--password is required") +} + +func TestPasswordFlagNoInputRequiresInline(t *testing.T) { + p := passwordFlag{Provided: true} + _, err := p.resolve(true) + require.Error(t, err) + assert.Contains(t, err.Error(), "--no-input") +} + +func TestSplitByMultiple(t *testing.T) { + assert.Equal(t, []string{"info", "warning", "error"}, SplitByMultiple("info|warning|error")) +} + +func TestSetCmdRunSkipsWhenRuleSelected(t *testing.T) { + cli := freshCLI() + parser := newCLIParser(t, &cli) + ctx, err := parser.Parse([]string{"set", "rule", "-s", "x", "-p", "/", "-r", "all"}) + require.NoError(t, err) + cli.Set.User = "should-not-run" + err = cli.Set.Run(ctx) + require.NoError(t, err) +} + +func TestSetCmdRunLegacyUser(t *testing.T) { + cli := freshCLI() + parser := newCLIParser(t, &cli) + ctx, err := parser.Parse([]string{"set", "-u", "bad"}) + require.NoError(t, err) + err = cli.Set.Run(ctx) + require.Error(t, err) + assert.Contains(t, err.Error(), "not enough info") +} + +func TestPasswordReadAllFromReader(t *testing.T) { + var buf bytes.Buffer + buf.WriteString(" trimmed \n") + data, err := io.ReadAll(&buf) + require.NoError(t, err) + assert.Equal(t, "trimmed", strings.TrimSpace(string(data))) +} + +func TestResolveConfigPathEnvMissingFile(t *testing.T) { + missing := filepath.Join(t.TempDir(), "does-not-exist.yaml") + t.Setenv("FILEBROWSER_CONFIG", missing) + config := "" + resolveConfigPath(&config) + assert.Equal(t, missing, config) + _, err := os.Stat(config) + assert.Error(t, err) +} + +func TestSetupNoInputRejected(t *testing.T) { + cli := freshCLI() + parser := newCLIParser(t, &cli) + ctx, err := parser.Parse([]string{"setup", "--no-input"}) + require.NoError(t, err) + err = ctx.Run() + require.Error(t, err) + assert.Contains(t, err.Error(), "interactive input") +} diff --git a/backend/cmd/fixture_test.go b/backend/cmd/fixture_test.go new file mode 100644 index 0000000000..d8544b49f9 --- /dev/null +++ b/backend/cmd/fixture_test.go @@ -0,0 +1,83 @@ +package cmd + +import ( + "os" + "path/filepath" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +const settingsMigrationBoltMinSize = 1024 + +// Docker source paths stored in the committed database.db.old Bolt fixture. +const ( + fixturePlaywrightSource = "/app/frontend/tests/playwright-files" + fixtureDockerSource = "/app/backend" + fixtureAccessSource = "/tests/playwright-files" +) + +// settingsMigrationBoltPath returns the committed read-only BoltDB reference used by +// migration tests and the Playwright settings Docker image. Tests must never write to it. +func settingsMigrationBoltPath(t *testing.T) string { + t.Helper() + path, err := filepath.Abs(filepath.Join("..", "..", "_docker", "src", "settings", "backend", "database.db.old")) + if err != nil { + t.Fatal(err) + } + info, err := os.Stat(path) + if err != nil { + t.Fatalf( + "settings migration fixture not found at %s: %v (commit _docker/src/settings/backend/database.db.old)", + path, + err, + ) + } + if info.Size() < settingsMigrationBoltMinSize { + t.Fatalf("settings migration fixture at %s is empty or too small (%d bytes)", path, info.Size()) + } + return path +} + +func settingsMigrationConfigPath(t *testing.T) string { + t.Helper() + path, err := filepath.Abs(filepath.Join("..", "..", "_docker", "src", "settings", "backend", "config.yaml")) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path); err != nil { + t.Fatalf("settings migration config not found at %s: %v", path, err) + } + return path +} + +// alignSettingsSourcesForMigrationFixture maps config sources to the Docker paths +// stored in database.db.old so migration tests can run locally without modifying +// the committed Bolt fixture. +func alignSettingsSourcesForMigrationFixture(t *testing.T) { + t.Helper() + byName := map[string]string{ + "playwright + files": fixturePlaywrightSource, + "docker": fixtureDockerSource, + "access": fixtureAccessSource, + } + newSourceMap := make(map[string]*settings.Source, len(byName)) + for name, dockerPath := range byName { + source, ok := settings.Config.Server.NameToSource[name] + if !ok { + t.Fatalf("source %q not in config", name) + } + if source.Path != dockerPath { + delete(settings.Config.Server.SourceMap, source.Path) + source.Path = dockerPath + } + newSourceMap[dockerPath] = source + settings.Config.Server.NameToSource[name] = source + } + settings.Config.Server.SourceMap = newSourceMap + sources := make([]*settings.Source, 0, len(byName)) + for _, name := range []string{"playwright + files", "docker", "access"} { + sources = append(sources, settings.Config.Server.NameToSource[name]) + } + settings.Config.Server.Sources = sources +} diff --git a/backend/cmd/kong.go b/backend/cmd/kong.go new file mode 100644 index 0000000000..77b5bf891e --- /dev/null +++ b/backend/cmd/kong.go @@ -0,0 +1,227 @@ +package cmd + +import ( + "fmt" + "io" + "os" + "strings" + + "github.com/alecthomas/kong" + "github.com/gtsteffaniak/filebrowser/backend/internal/version" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/go-logger/logger" + "golang.org/x/term" +) + +// Globals holds flags shared across all commands (order-independent). +type Globals struct { + Config string `short:"c" name:"config" default:"config.yaml" env:"FILEBROWSER_CONFIG" help:"Path to config file"` + NoInput bool `name:"no-input" help:"Disable interactive prompts (fail if input required)"` +} + +type runCmd struct{} + +type versionCmd struct{} + +type setupCmd struct{} + +type SetCmd struct { + User string `short:"u" help:"Deprecated: comma-separated username,password. Use 'user set' instead."` + Admin bool `short:"a" help:"Create user as admin (used with -u)"` + Rule SetRuleCmd `cmd:"" name:"rule" help:"Add or update an access rule"` +} + +type SetRuleCmd struct { + Source string `short:"s" name:"source" aliases:"f,sourceName" required:"" help:"Source name from config"` + Path string `short:"p" name:"path" aliases:"sourcePath" required:"" help:"Index path within the source"` + Role string `short:"r" name:"role" enum:"user,group,all" required:"" help:"Rule target type"` + Value string `short:"v" name:"value" help:"Username or group name (required for user/group)"` + Allow bool `name:"allow" help:"Allow access (default: deny)"` +} + +type UserCmd struct { + Set UserSetCmd `cmd:"" name:"set" help:"Create or update a password-authenticated user"` + Promote UserPromoteCmd `cmd:"" name:"promote" help:"Grant admin permissions without changing password"` +} + +type UserPromoteCmd struct { + Username string `arg:"" help:"Username to promote"` +} + +type UserSetCmd struct { + Username string `arg:"" help:"Username"` + Password passwordFlag `name:"password" help:"Password; omit value to prompt (TTY) or read stdin (pipe)"` + Admin bool `short:"a" name:"admin" help:"Grant admin permissions"` +} + +// passwordFlag accepts --password VALUE (inline) or --password alone (prompt/pipe). +type passwordFlag struct { + Provided bool + Inline string +} + +func (p *passwordFlag) Decode(ctx *kong.DecodeContext) error { + p.Provided = true + if ctx.Scan.Peek().IsValue() { + return ctx.Scan.PopValueInto("password", &p.Inline) + } + return nil +} + +func (p passwordFlag) resolve(noInput bool) (string, error) { + if !p.Provided { + return "", fmt.Errorf("--password is required (inline value, interactive prompt, or piped stdin)") + } + if p.Inline != "" { + return p.Inline, nil + } + if noInput { + return "", fmt.Errorf("--password requires an inline value or piped stdin when --no-input is set") + } + if term.IsTerminal(int(os.Stdin.Fd())) { + return promptPassword() + } + data, err := io.ReadAll(os.Stdin) + if err != nil { + return "", fmt.Errorf("read password from stdin: %w", err) + } + password := strings.TrimSpace(string(data)) + if password == "" { + return "", fmt.Errorf("password must not be empty") + } + return password, nil +} + +func promptPassword() (string, error) { + if _, err := fmt.Fprint(os.Stderr, "Password: "); err != nil { + return "", err + } + bytePassword, err := term.ReadPassword(int(os.Stdin.Fd())) + fmt.Fprintln(os.Stderr) + if err != nil { + return "", fmt.Errorf("read password: %w", err) + } + password := string(bytePassword) + if password == "" { + return "", fmt.Errorf("password must not be empty") + } + return password, nil +} + +var rootCLI cliRoot + +type cliRoot struct { + Globals `embed:""` + + Run runCmd `cmd:"" default:"1" hidden:"" help:"Start the FileBrowser server"` + Version versionCmd `cmd:"" name:"version" help:"Print version information"` + Setup setupCmd `cmd:"" name:"setup" help:"Interactive configuration setup"` + Set SetCmd `cmd:"" name:"set" help:"Set configuration values (deprecated: use 'user set' for users)"` + User UserCmd `cmd:"" name:"user" help:"User management"` +} + +func (versionCmd) Run() error { + fmt.Printf(`FileBrowser Quantum - A modern web-based file manager + Version : %v + Commit : %v + Release Info : https://github.com/gtsteffaniak/filebrowser/releases/tag/%v +`, version.Version, version.CommitSHA, version.Version) + return nil +} + +func (setupCmd) Run(globals *Globals) error { + return createConfig(globals.Config, globals.NoInput) +} + +func (s *SetCmd) Run(ctx *kong.Context) error { + if strings.HasPrefix(ctx.Command(), "set rule") { + return nil + } + if s.User == "" { + return fmt.Errorf("missing subcommand for 'set'. Use 'set rule' or 'user set'") + } + fmt.Fprintln(os.Stderr, "warning: 'set -u' is deprecated; use 'user set' instead") + userInfo := strings.SplitN(s.User, ",", 2) + if len(userInfo) < 2 || userInfo[0] == "" || userInfo[1] == "" { + return fmt.Errorf("not enough info to create user: \"set -u username,password\", only provided %v", strings.Split(s.User, ",")) + } + return setUser(userInfo[0], userInfo[1], s.Admin) +} + +func (r *SetRuleCmd) Run() error { + sourceInfo, ok := settings.Config.Server.NameToSource[r.Source] + if !ok { + return fmt.Errorf("invalid source name: %s", r.Source) + } + return setRule(sourceInfo.Path, r.Path, r.Role, r.Value, r.Allow) +} + +func (u *UserSetCmd) Run(globals *Globals) error { + password, err := u.Password.resolve(globals.NoInput) + if err != nil { + return err + } + return setUser(u.Username, password, u.Admin) +} + +func (p *UserPromoteCmd) Run() error { + return promoteUser(p.Username) +} + +func resolveConfigPath(config *string) { + envConfig := os.Getenv("FILEBROWSER_CONFIG") + if *config == "" { + if envConfig != "" { + *config = envConfig + } else { + *config = "config.yaml" + } + } +} + +func requireExistingConfig(config string) { + envConfig := os.Getenv("FILEBROWSER_CONFIG") + if envConfig != "" && config == envConfig { + if _, err := os.Stat(config); err != nil { + logger.Fatalf("config file %v does not exist, please create it or set the FILEBROWSER_CONFIG environment variable to a valid config file path", config) + } + } +} + +func runCLI() (keepGoing bool, dbExists bool) { + generateYaml() + + parser, err := kong.New(&rootCLI, + kong.Name("filebrowser"), + kong.Description("FileBrowser Quantum - A modern web-based file manager"), + kong.Bind(&rootCLI.Globals), + ) + if err != nil { + logger.Fatalf("failed to configure CLI: %v", err) + } + + ctx, err := parser.Parse(os.Args[1:]) + parser.FatalIfErrorf(err) + + resolveConfigPath(&rootCLI.Config) + configPath = rootCLI.Config + + cmd := ctx.Command() + switch { + case cmd == "" || cmd == "run": + requireExistingConfig(configPath) + dbExists = initializeDatabase(configPath) + return true, dbExists + case cmd == "version" || cmd == "setup": + parser.FatalIfErrorf(ctx.Run(&rootCLI)) + return false, false + case cmd == "set rule" || cmd == "set" || strings.HasPrefix(cmd, "user set") || strings.HasPrefix(cmd, "user promote"): + requireExistingConfig(configPath) + dbExists = initializeDatabase(configPath) + parser.FatalIfErrorf(ctx.Run(&rootCLI)) + return false, dbExists + default: + parser.Fatalf("unexpected command: %q", cmd) + return false, false + } +} diff --git a/backend/cmd/migrate.go b/backend/cmd/migrate.go new file mode 100644 index 0000000000..a95e11c18c --- /dev/null +++ b/backend/cmd/migrate.go @@ -0,0 +1,483 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + + storm "github.com/asdine/storm/v3" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/access" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/dbindex" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/sqldb" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/internal/usersidebar" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/go-logger/logger" +) + +const migrationGuideURL = "https://filebrowserquantum.com/en/docs/getting-started/v2/migration" + +func migrationErrf(format string, args ...any) error { + return fmt.Errorf(format+" See the v2 migration guide: "+migrationGuideURL, args...) +} + +// checkMigrationNeeded is true when server.database.migrateFrom points at a BoltDB file to import and +// server.database.path (SQLite) does not exist yet or is empty. +func checkMigrationNeeded() bool { + boltPath := settings.Config.Server.DatabaseV2.MigrateFrom + if boltPath == "" { + return false + } + if sqliteDatabasePopulated(settings.Config.Server.DatabaseV2.Path) { + return false + } + return legacyBoltDatabasePopulated(boltPath) +} + +// validateDatabasePaths enforces database path rules before opening or creating SQLite: +// 1. On a fresh install, fail if server.database.path is database.db or an unrenamed +// legacy database file (database.db) is present in the working directory. +// 2. On a fresh install with server.database.migrateFrom set, fail if the legacy database file is missing +// or empty. +// 3. When SQLite already exists and server.database.migrateFrom is set, fail if the legacy database file +// is missing or empty. +// +// Otherwise the existing SQLite database is used, or a new one is created on first open. +func validateDatabasePaths() error { + sqlitePath := settings.Config.Server.DatabaseV2.Path + boltPath := settings.Config.Server.DatabaseV2.MigrateFrom + sqliteExists := sqliteDatabasePopulated(sqlitePath) + + if !sqliteExists { + if filepath.Base(sqlitePath) == "database.db" { + return migrationErrf( + `server.database.path cannot be "database.db": that name is reserved for the legacy database file. ` + + `Rename database.db to database.db.old, set server.database.path to a new SQLite filename ` + + `and set server.database.migrateFrom to "database.db.old".`, + ) + } + if _, err := os.Stat("database.db"); err == nil { + return migrationErrf( + `legacy database file found in the working directory. ` + + `Rename it to database.db.old, set server.database.migrateFrom to "database.db.old" ` + + `or use migrateFrom: "default".`, + ) + } + if boltPath != "" { + return legacyBoltDatabaseError(boltPath, sqlitePath, true) + } + return nil + } + + if boltPath != "" { + return legacyBoltDatabaseError(boltPath, sqlitePath, false) + } + return nil +} + +func legacyBoltDatabaseError(boltPath, sqlitePath string, freshInstall bool) error { + stat, err := os.Stat(boltPath) + if err != nil { + if os.IsNotExist(err) { + if freshInstall { + return migrationErrf( + `server.database.migrateFrom is %q but that file does not exist, and no SQLite database exists at server.database.path (%q). `+ + `Check the migrateFrom path or restore your renamed legacy database backup.`, + boltPath, sqlitePath, + ) + } + return migrationErrf( + `server.database.migrateFrom is %q but that file does not exist. `+ + `Migration appears complete — remove server.database.migrateFrom from your config.`, + boltPath, + ) + } + return migrationErrf( + `server.database.migrateFrom is %q but cannot be read: %v. `+ + `Check file permissions or restore your backed-up database file.`, + boltPath, err, + ) + } + if stat.Size() == 0 { + if freshInstall { + return migrationErrf( + `server.database.migrateFrom is %q but that file is empty, and no SQLite database exists at server.database.path (%q). `+ + `Restore your backed-up database file or fix the migrateFrom path.`, + boltPath, sqlitePath, + ) + } + return migrationErrf( + `server.database.migrateFrom is %q but that file is empty. `+ + `Remove server.database.migrateFrom from your config, or restore the legacy database backup if migration is not complete.`, + boltPath, + ) + } + return nil +} + +func sqliteDatabasePopulated(path string) bool { + stat, err := os.Stat(path) + return err == nil && stat.Size() > 0 +} + +func legacyBoltDatabasePopulated(path string) bool { + stat, err := os.Stat(path) + return err == nil && stat.Size() > 0 +} + +// migrateFromBoltToSQLite migrates essential data from BoltDB to SQLite +func migrateFromBoltToSQLite() error { + oldDBPath := settings.Config.Server.DatabaseV2.MigrateFrom + newDBPath := settings.Config.Server.DatabaseV2.Path + + logger.Info("========================================") + logger.Info("Starting migration from legacy database") + logger.Info("========================================") + // Open old BoltDB (read-only) + logger.Info("Opening old database...") + oldDB, err := storm.Open(oldDBPath) + if err != nil { + return fmt.Errorf("failed to open old database: %w", err) + } + logger.Info("✓ Old database opened") + + // Initialize new database + logger.Info("Initializing new database...") + sqlStore, _, err := sqldb.NewSQLStoreWithOptions(newDBPath, sqldb.NewSQLStoreOpts{SkipQuickSetup: true}) + if err != nil { + oldDB.Close() + return fmt.Errorf("failed to initialize new database: %w", err) + } + logger.Info("✓ New database initialized") + + // Ensure cleanup on error - remove incomplete database for retry + migrationSuccess := false + defer func() { + oldDB.Close() + sqlStore.Close() + + if !migrationSuccess { + // Migration failed - remove the new database so it can be retried + logger.Warning("Migration failed, cleaning up new database file for retry...") + if err := os.Remove(newDBPath); err != nil && !os.IsNotExist(err) { + logger.Errorf("Failed to remove incomplete database file: %v", err) + } else { + logger.Info("✓ Incomplete database file removed, migration can be retried on next startup") + } + } + }() + + // Migrate users (bolt User.ID is stored as SQLite users.user_id) + logger.Info("Migrating users...") + if err := migrateUsers(oldDB, sqlStore); err != nil { + return fmt.Errorf("failed to migrate users: %w", err) + } + if err := state.EnsureNoAuthAdminUserAfterMigration(sqlStore); err != nil { + return fmt.Errorf("failed to configure noauth admin user: %w", err) + } + + // Migrate shares + logger.Info("Migrating shares...") + if err := migrateShares(oldDB, sqlStore); err != nil { + return fmt.Errorf("failed to migrate shares: %w", err) + } + + // Migrate access rules and groups + logger.Info("Migrating access rules and groups...") + if err := migrateAccessRules(oldDB, sqlStore); err != nil { + return fmt.Errorf("failed to migrate access rules: %w", err) + } + + // Migrate index info + logger.Info("Migrating index info...") + if err := migrateIndexInfo(oldDB, sqlStore); err != nil { + return fmt.Errorf("failed to migrate index info: %w", err) + } + + // Mark migration as successful + migrationSuccess = true + + logger.Info("========================================") + logger.Info("Migration completed successfully!") + logger.Info("========================================") + logger.Infof("Your legacy database file is unchanged at: %s", oldDBPath) + logger.Infof("New SQLite database created at: %s", newDBPath) + + return nil +} + +// normalizeUserScopesBeforeSQLite copies scopes from FrontendScopes into BackendScopes when the Bolt +// record only had JSON key "scopes" (FrontendUser) and nothing under backendScopes — CreateUser +// persists only BackendScopes in SQLite user_data. +func normalizeUserScopesBeforeSQLite(user *users.User) error { + if len(user.BackendScopes) > 0 { + return nil + } + backendScopes, err := users.APIScopesToBackend(user.FrontendScopes) + if err != nil { + return fmt.Errorf("convert frontend scopes to backend: %w", err) + } + for i := range backendScopes { + backendScopes[i].Permissions = users.SourceFilePermissions{ + View: true, + Download: user.Permissions.Download, + Modify: user.Permissions.Modify, + Delete: user.Permissions.Delete, + Create: user.Permissions.Create, + } + } + user.FrontendScopes = nil + user.BackendScopes = backendScopes + return nil +} + +// migrateUsers migrates all users from BoltDB to SQLite. Each bolt user.ID is written as user_id +func migrateUsers(oldDB *storm.DB, sqlStore *sqldb.SQLStore) error { + var usersList []*users.User + err := oldDB.All(&usersList) + if err != nil { + if err.Error() == "not found" { + logger.Info(" No users to migrate") + return nil + } + return fmt.Errorf("failed to read users from old DB: %w", err) + } + + promoted := 0 + for _, user := range usersList { + oldScopesCount := len(user.FrontendScopes) + newScopesCount := len(user.BackendScopes) + if err := normalizeUserScopesBeforeSQLite(user); err != nil { + return fmt.Errorf("failed to normalize scopes for user %s: %w", user.Username, err) + } + if normalized, changed := usersidebar.NormalizeSidebarLinks(user.SidebarLinks); changed { + user.SidebarLinks = normalized + } + if merged, changed := usersidebar.EnsureSidebarLinksFromScopes(user.SidebarLinks, user.BackendScopes); changed { + user.SidebarLinks = merged + } + if normalized, changed := usersidebar.NormalizeSidebarLinks(user.SidebarLinks); changed { + user.SidebarLinks = normalized + } + prevVersion := user.Version + if len(user.BackendScopes) == 0 { + settings.ApplyUserDefaults(user) + } + if prevVersion < users.SourcePermissionsMigrationVersion { + // ApplyUserDefaults bumps Version; restore pre-defaults version so legacy global file ops migrate to scopes. + user.Version = prevVersion + users.MigrateToSourcePermissions(user) + } + normalizeUserTokensBeforeSQLite(user) + updateTokens(user) + user.Version = users.ProfileStorageVersion + if newScopesCount > oldScopesCount { + promoted++ + logger.Infof(" user %q: legacy database had %d scopes, SQLite now has %d", + user.Username, oldScopesCount, newScopesCount) + } + boltID := user.ID + if err := sqlStore.CreateUser(user); err != nil { + return fmt.Errorf("failed to save user %s (bolt id: %d): %w", user.Username, boltID, err) + } + } + + if promoted > 0 { + logger.Infof(" Promoted frontend-only Bolt scopes to backend for %d user(s) before SQLite insert", promoted) + } + logger.Infof(" ✓ Migrated %d users", len(usersList)) + return nil +} + +// normalizeUserTokensBeforeSQLite ensures Bolt name-keyed tokens have Name set so +// TokensForPersist retains them in SQLite user_data (Bolt often stores the name only as the map key). +func normalizeUserTokensBeforeSQLite(user *users.User) { + if len(user.Tokens) == 0 { + return + } + normalized := make(map[string]users.AuthToken) + for key, token := range user.Tokens { + name := token.Name + if name == "" { + if key == token.Token { + continue + } + name = key + } + if _, exists := normalized[name]; exists { + continue + } + token.Name = name + if token.Token == "" { + token.Token = token.Key + } + token.Permissions = users.SanitizeTokenPermissions(token.Permissions) + users.StoreToken(normalized, token) + } + user.Tokens = normalized +} + +// migrateShares migrates all shares from BoltDB to SQLite. +// +// Legacy Bolt "Link" / "Share" JSON (flat CommonShare + Link fields): +// - "source" → Share.SourcePath (backend source path; not the share item path) +// - "path" → Share.Path (index-relative path within that source) +// - "userID" → Share.UserID unchanged (same numeric id as migrated users in SQLite) +// - "password_hash" → Share.PasswordHash (username is never stored on the share row) +// +// New users created after migration get random uint64 ids (utils.RandomUint64ID); Bolt ids 1,2,3… +// remain valid. PrepForFrontend resolves Share.UserID to username for API responses only. +func migrateShares(oldDB *storm.DB, sqlStore *sqldb.SQLStore) error { + boltShareBuckets := []string{"Share", "Link"} + var sharesList []*share.LegacyShare + for _, bucket := range boltShareBuckets { + var batch []*share.LegacyShare + err := oldDB.Select().Bucket(bucket).Find(&batch) + if err != nil && err != storm.ErrNotFound { + return fmt.Errorf("failed to read shares from legacy DB bucket %q: %w", bucket, err) + } + if len(batch) > 0 { + sharesList = append(sharesList, batch...) + } + } + + if len(sharesList) == 0 { + logger.Info(" No shares to migrate") + return nil + } + + for _, legacy := range sharesList { + link := legacy.ToShare() + if link.UserID == 0 { + return fmt.Errorf("failed to save share %s: owner user id is missing", link.Hash) + } + // Legacy Bolt "source" → SourcePath; normalize when it was stored as a display name. + if link.SourcePath != "" { + if _, ok := settings.Config.Server.SourceMap[link.SourcePath]; !ok { + if src, ok := settings.Config.Server.NameToSource[link.SourcePath]; ok { + link.SourceName = src.Name + link.SourcePath = src.Path + } + } else if link.SourceName == "" { + link.SourceName = settings.Config.Server.SourceMap[link.SourcePath].Name + } + } + // Do not persist API-only fields; PrepForFrontend fills these on read. + link.ShareURL = "" + link.DownloadURL = "" + link.FrontendShareInfo.SourceURL = "" + link.CanEditShare = false + if err := sqlStore.SaveShare(&link); err != nil { + return fmt.Errorf("failed to save share %s: %w", link.Hash, err) + } + } + + logger.Infof(" ✓ Migrated %d shares", len(sharesList)) + return nil +} + +// migrateAccessRules migrates access control data from BoltDB to SQLite. +// Path rules (AllRules) and group definitions (Groups) are unchanged through migration +func migrateAccessRules(oldDB *storm.DB, sqlStore *sqldb.SQLStore) error { + // Read the access rules JSON blob from BoltDB + var data []byte + err := oldDB.Get("access_rules", "rules", &data) + if err != nil { + if err.Error() == "not found" { + logger.Info(" No access rules to migrate") + return nil + } + return fmt.Errorf("failed to read access rules: %w", err) + } + + // Unmarshal the data + type dbStorage struct { + AllRules access.SourceRuleMap `json:"all_rules"` + Groups access.GroupMap `json:"groups"` + RevokedTokens map[string]struct{} `json:"revoked_tokens"` + HashedTokens map[string]uint `json:"hashed_tokens"` + } + + var storage dbStorage + if err := json.Unmarshal(data, &storage); err != nil { + return fmt.Errorf("failed to unmarshal access rules: %w", err) + } + + // Migrate access rules + ruleCount := 0 + for source, rules := range storage.AllRules { + resolvedSource := source + if info, ok := users.ResolveSourceKey(source); ok { + resolvedSource = info.Path + } else if src, ok := settings.Config.Server.NameToSource[source]; ok { + resolvedSource = src.Path + } + for path, rule := range rules { + err := sqlStore.SaveAccessRule(resolvedSource, path, rule) + if err != nil { + return fmt.Errorf("failed to save access rule: %w", err) + } + ruleCount++ + } + } + logger.Infof(" ✓ Migrated %d access rules", ruleCount) + + // Migrate groups + for name, members := range storage.Groups { + err := sqlStore.SaveGroup(name, members) + if err != nil { + return fmt.Errorf("failed to save group %s: %w", name, err) + } + } + logger.Infof(" ✓ Migrated %d groups", len(storage.Groups)) + + // Migrate revoked tokens + for tokenHash := range storage.RevokedTokens { + err := sqlStore.SaveRevokedToken(tokenHash) + if err != nil { + return fmt.Errorf("failed to save revoked token: %w", err) + } + } + logger.Infof(" ✓ Migrated %d revoked tokens", len(storage.RevokedTokens)) + + // Migrate hashed tokens (bolt stored owner user id) + for tokenHash, userID := range storage.HashedTokens { + if userID == 0 { + logger.Warningf(" skipping hashed token: invalid user id 0") + continue + } + err := sqlStore.SaveHashedToken(tokenHash, uint64(userID)) + if err != nil { + return fmt.Errorf("failed to save hashed token: %w", err) + } + } + logger.Infof(" ✓ Migrated %d hashed tokens", len(storage.HashedTokens)) + + return nil +} + +// migrateIndexInfo migrates index info metadata from BoltDB to SQLite +func migrateIndexInfo(oldDB *storm.DB, sqlStore *sqldb.SQLStore) error { + var indexList []*dbindex.IndexInfo + err := oldDB.All(&indexList) + if err != nil { + if err.Error() == "not found" { + logger.Info(" No index info to migrate") + return nil + } + return fmt.Errorf("failed to read index info: %w", err) + } + + for _, info := range indexList { + err := sqlStore.SaveIndexInfo(info) + if err != nil { + return fmt.Errorf("failed to save index info for %s: %w", info.Path, err) + } + } + + logger.Infof(" ✓ Migrated %d index info entries", len(indexList)) + return nil +} diff --git a/backend/cmd/migrate_config_test.go b/backend/cmd/migrate_config_test.go new file mode 100644 index 0000000000..8a2c033dd8 --- /dev/null +++ b/backend/cmd/migrate_config_test.go @@ -0,0 +1,165 @@ +package cmd + +import ( + "os" + "path/filepath" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func TestValidateDatabasePaths_missingBoltOnFreshInstall(t *testing.T) { + dir := t.TempDir() + settings.Config.Server.DatabaseV2.MigrateFrom = filepath.Join(dir, "database.db.old") + settings.Config.Server.DatabaseV2.Path = filepath.Join(dir, "filebrowser.sqlite") + + err := validateDatabasePaths() + if err == nil { + t.Fatal("expected error when migrateFrom file is missing on fresh install") + } +} + +func TestValidateDatabasePaths_emptyBoltOnFreshInstall(t *testing.T) { + dir := t.TempDir() + boltPath := filepath.Join(dir, "database.db.old") + if err := os.WriteFile(boltPath, nil, 0o600); err != nil { + t.Fatal(err) + } + settings.Config.Server.DatabaseV2.MigrateFrom = boltPath + settings.Config.Server.DatabaseV2.Path = filepath.Join(dir, "filebrowser.sqlite") + + err := validateDatabasePaths() + if err == nil { + t.Fatal("expected error when migrateFrom file is empty on fresh install") + } +} + +func TestValidateDatabasePaths_missingBoltWhenSQLiteExists(t *testing.T) { + dir := t.TempDir() + settings.Config.Server.DatabaseV2.MigrateFrom = filepath.Join(dir, "missing.db.old") + sqlitePath := filepath.Join(dir, "filebrowser.sqlite") + if err := os.WriteFile(sqlitePath, []byte("sqlite"), 0o600); err != nil { + t.Fatal(err) + } + settings.Config.Server.DatabaseV2.Path = sqlitePath + + if err := validateDatabasePaths(); err == nil { + t.Fatal("expected error when migrateFrom is set but legacy file is missing after migration") + } +} + +func TestValidateDatabasePaths_okWhenSQLiteExistsWithoutMigrateFrom(t *testing.T) { + dir := t.TempDir() + settings.Config.Server.DatabaseV2.MigrateFrom = "" + sqlitePath := filepath.Join(dir, "filebrowser.sqlite") + if err := os.WriteFile(sqlitePath, []byte("sqlite"), 0o600); err != nil { + t.Fatal(err) + } + settings.Config.Server.DatabaseV2.Path = sqlitePath + + if err := validateDatabasePaths(); err != nil { + t.Fatalf("expected no error: %v", err) + } + if checkMigrationNeeded() { + t.Fatal("migration should not run when sqlite already exists") + } +} + +func TestValidateDatabasePaths_okWhenSQLiteAndBoltExist(t *testing.T) { + dir := t.TempDir() + boltPath := filepath.Join(dir, "database.db.old") + if err := os.WriteFile(boltPath, []byte("bolt"), 0o600); err != nil { + t.Fatal(err) + } + sqlitePath := filepath.Join(dir, "filebrowser.sqlite") + if err := os.WriteFile(sqlitePath, []byte("sqlite"), 0o600); err != nil { + t.Fatal(err) + } + settings.Config.Server.DatabaseV2.MigrateFrom = boltPath + settings.Config.Server.DatabaseV2.Path = sqlitePath + + if err := validateDatabasePaths(); err != nil { + t.Fatalf("expected no error when both databases exist: %v", err) + } + if checkMigrationNeeded() { + t.Fatal("migration should not run when sqlite already exists") + } +} + +func TestValidateDatabasePaths_rejectsDatabaseDBAsSQLitePath(t *testing.T) { + dir := t.TempDir() + settings.Config.Server.DatabaseV2.MigrateFrom = "" + settings.Config.Server.DatabaseV2.Path = filepath.Join(dir, "database.db") + + if err := validateDatabasePaths(); err == nil { + t.Fatal("expected error when sqlite path is database.db on fresh install") + } +} + +func TestValidateDatabasePaths_rejectsUnrenamedLegacyDatabaseDB(t *testing.T) { + dir := t.TempDir() + t.Chdir(dir) + + settings.Config.Server.DatabaseV2.MigrateFrom = "" + settings.Config.Server.DatabaseV2.Path = filepath.Join(dir, "filebrowser.sqlite") + if err := os.WriteFile("database.db", []byte("legacy-bolt"), 0o600); err != nil { + t.Fatal(err) + } + + if err := validateDatabasePaths(); err == nil { + t.Fatal("expected error when unrenamed database.db exists on fresh install") + } +} + +func TestValidateDatabasePaths_migrateFromDefaultResolvesFromEnv(t *testing.T) { + dir := t.TempDir() + boltPath := filepath.Join(dir, "database.db.old") + if err := os.WriteFile(boltPath, []byte("bolt"), 0o600); err != nil { + t.Fatal(err) + } + + t.Setenv("FILEBROWSER_DATABASE", boltPath) + + settings.Config.Server.DatabaseV2.MigrateFrom = settings.MigrateFromDefault + settings.Config.Server.DatabaseV2.Path = filepath.Join(dir, "filebrowser.sqlite") + + if err := settings.ResolveDatabasePaths(); err != nil { + t.Fatalf("ResolveDatabasePaths: %v", err) + } + if settings.Config.Server.DatabaseV2.MigrateFrom != boltPath { + t.Fatalf("migrateFrom = %q, want %q", settings.Config.Server.DatabaseV2.MigrateFrom, boltPath) + } + if err := validateDatabasePaths(); err != nil { + t.Fatalf("validateDatabasePaths: %v", err) + } + if !checkMigrationNeeded() { + t.Fatal("expected migration to be needed") + } +} + +func TestCheckMigrationNeeded_trueWhenBoltPresentAndSQLiteMissing(t *testing.T) { + dir := t.TempDir() + boltPath := filepath.Join(dir, "database.db.old") + if err := os.WriteFile(boltPath, []byte("bolt"), 0o600); err != nil { + t.Fatal(err) + } + settings.Config.Server.DatabaseV2.MigrateFrom = boltPath + settings.Config.Server.DatabaseV2.Path = filepath.Join(dir, "filebrowser.sqlite") + + if err := validateDatabasePaths(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !checkMigrationNeeded() { + t.Fatal("expected migration to be needed") + } +} + +func TestValidateDatabasePaths_okFreshInstallWithoutMigrateFrom(t *testing.T) { + dir := t.TempDir() + settings.Config.Server.DatabaseV2.MigrateFrom = "" + settings.Config.Server.DatabaseV2.Path = filepath.Join(dir, "filebrowser.sqlite") + + if err := validateDatabasePaths(); err != nil { + t.Fatalf("expected no error on fresh install without migrateFrom: %v", err) + } +} diff --git a/backend/cmd/migrate_tokens_test.go b/backend/cmd/migrate_tokens_test.go new file mode 100644 index 0000000000..9c9fc33892 --- /dev/null +++ b/backend/cmd/migrate_tokens_test.go @@ -0,0 +1,74 @@ +package cmd + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + storm "github.com/asdine/storm/v3" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/sqldb" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func TestMigrateAdminTokensRoundTripSQLite(t *testing.T) { + boltPath := settingsMigrationBoltPath(t) + sqlitePath := filepath.Join(t.TempDir(), "migrate-tokens.sqlite") + + oldDB, err := storm.Open(boltPath) + if err != nil { + t.Fatal(err) + } + defer oldDB.Close() + + sqlStore, _, err := sqldb.NewSQLStoreWithOptions(sqlitePath, sqldb.NewSQLStoreOpts{SkipQuickSetup: true}) + if err != nil { + t.Fatal(err) + } + defer sqlStore.Close() + + var list []*users.User + if err = oldDB.All(&list); err != nil { + t.Fatal(err) + } + var admin *users.User + for _, u := range list { + if u.Username == "admin" { + admin = u + break + } + } + if admin == nil { + t.Fatal("admin not found") + } + + normalizeUserTokensBeforeSQLite(admin) + if err = sqlStore.CreateUser(admin); err != nil { + t.Fatal(err) + } + + loaded, err := sqlStore.GetUserByUsername("admin") + if err != nil { + t.Fatal(err) + } + customized, ok := loaded.Tokens["customized"] + if !ok { + t.Fatalf("customized missing after reload: %#v", loaded.Tokens) + } + if !customized.Permissions.Admin { + t.Fatalf("customized admin permission missing after reload: %#v", customized.Permissions) + } + if customized.Permissions.Api || customized.Permissions.Share || customized.Permissions.Realtime { + t.Fatalf("customized should only retain admin global after reload: %#v", customized.Permissions) + } + if customized.Permissions.Modify || customized.Permissions.Create || customized.Permissions.Delete || customized.Permissions.Download { + t.Fatalf("customized legacy file ops should be stripped: %#v", customized.Permissions) + } + + out, _ := json.MarshalIndent(map[string]any{ + "customizedPermissions": customized.Permissions, + "tokenNames": len(loaded.Tokens), + }, "", " ") + os.Stdout.Write(out) + os.Stdout.Write([]byte("\n")) +} diff --git a/backend/cmd/migrate_users_defaults_test.go b/backend/cmd/migrate_users_defaults_test.go new file mode 100644 index 0000000000..26eed62df5 --- /dev/null +++ b/backend/cmd/migrate_users_defaults_test.go @@ -0,0 +1,89 @@ +package cmd + +import ( + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +// Simulates migrateUsers() steps for a Bolt user without backend scopes or source permissions. +func TestMigrateUsersFlow_appliesConfigDefaultsAndSourcePermissions(t *testing.T) { + loadMigrateTestConfig(t, "../../_docker/src/jwt/backend/config.yaml") + + user := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "legacy-bolt-user", + Permissions: users.Permissions{ + Download: true, + Modify: true, + Create: true, + Share: true, + }, + }, + Version: 2, + } + + prevVersion := user.Version + if len(user.BackendScopes) == 0 { + settings.ApplyUserDefaults(user) + } + if prevVersion < users.SourcePermissionsMigrationVersion { + user.Version = prevVersion + if !users.MigrateToSourcePermissions(user) { + t.Fatal("expected source permission migration") + } + } + user.Version = users.ProfileStorageVersion + + if !user.Permissions.Share { + t.Fatal("global share should remain after migration") + } + if user.Permissions.Modify || user.Permissions.Download { + t.Fatalf("legacy global file ops should be cleared: %+v", user.Permissions) + } + if len(user.BackendScopes) == 0 { + t.Fatal("ApplyUserDefaults should assign default-enabled sources") + } + perms := user.BackendScopes[0].Permissions + if !perms.View || !perms.Modify || !perms.Create || !perms.Download { + t.Fatalf("scope permissions after migration: %+v", perms) + } + if user.BackendScopes[0].Scope != "/legacy-bolt-user" { + t.Fatalf("createUserDir scope=%q", user.BackendScopes[0].Scope) + } +} + +func TestMigrateUsersFlow_existingScopeGetsLegacyGlobalFileOps(t *testing.T) { + loadMigrateTestConfig(t, "../../_docker/src/proxy/backend/config.yaml") + + user := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "scoped", + Permissions: users.Permissions{ + Download: true, + Modify: false, + Create: false, + Share: true, + }, + }, + BackendScopes: []users.BackendScope{ + {Path: settings.Config.Server.Sources[0].Path, Scope: "/"}, + }, + Version: 2, + } + + users.MigrateToSourcePermissions(user) + perms := user.BackendScopes[0].Permissions + if !perms.Download || perms.Modify || perms.Create { + t.Fatalf("expected legacy global copied to scope: %+v", perms) + } +} + +func loadMigrateTestConfig(t *testing.T, path string) { + t.Helper() + settings.Config = settings.SetDefaults(true) + if err := settings.LoadConfigWithDefaultsForTest(path); err != nil { + t.Fatal(err) + } +} diff --git a/backend/cmd/migration_fixture_test.go b/backend/cmd/migration_fixture_test.go new file mode 100644 index 0000000000..9c5efb5871 --- /dev/null +++ b/backend/cmd/migration_fixture_test.go @@ -0,0 +1,142 @@ +package cmd + +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/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func TestMigrationFixturePostState(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize(settingsMigrationConfigPath(t)) + settings.Env.IsPlaywright = true + alignSettingsSourcesForMigrationFixture(t) + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + settings.Config.Server.DatabaseV2.Path = dbPath + settings.Config.Server.DatabaseV2.MigrateFrom = settingsMigrationBoltPath(t) + + if err := migrateFromBoltToSQLite(); err != nil { + t.Fatal(err) + } + + sqlStore, _, err := sqldb.NewSQLStoreWithOptions(dbPath, sqldb.NewSQLStoreOpts{SkipQuickSetup: true}) + if err != nil { + t.Fatal(err) + } + defer sqlStore.Close() + + playwrightPath := fixturePlaywrightSource + dockerPath := fixtureDockerSource + accessPath := fixtureAccessSource + + admin, err := sqlStore.GetUserByUsername("admin") + if err != nil { + t.Fatal(err) + } + if !admin.Permissions.Admin || !admin.Permissions.Api || !admin.Permissions.Share { + t.Fatalf("admin globals=%+v", admin.Permissions) + } + if admin.Permissions.Realtime { + t.Fatal("admin realtime should be false") + } + + fullPerms := users.SourceFilePermissions{ + View: true, Download: true, Modify: true, Create: true, Delete: true, + } + for _, sourcePath := range []string{playwrightPath, dockerPath, accessPath} { + assertSourceFilePerms(t, admin, sourcePath, fullPerms) + } + + customized, ok := admin.Tokens["customized"] + if !ok { + t.Fatal("customized token missing") + } + if !customized.Permissions.Admin { + t.Fatalf("customized token globals=%+v", customized.Permissions) + } + if customized.Permissions.Api || customized.Permissions.Share || customized.Permissions.Realtime { + t.Fatalf("customized token should only have admin global: %+v", customized.Permissions) + } + if customized.Permissions.Modify || customized.Permissions.Create || customized.Permissions.Delete || customized.Permissions.Download { + t.Fatalf("customized token legacy file ops should be stripped: %+v", customized.Permissions) + } + + basic, err := sqlStore.GetUserByUsername("basic") + if err != nil { + t.Fatal(err) + } + if !basic.Permissions.Share || basic.Permissions.Admin || basic.Permissions.Api { + t.Fatalf("basic globals=%+v", basic.Permissions) + } + viewOnly := users.SourceFilePermissions{View: true} + for _, sourcePath := range []string{playwrightPath, dockerPath, accessPath} { + assertSourceFilePerms(t, basic, sourcePath, viewOnly) + } + + graham, err := sqlStore.GetUserByUsername("graham") + if err != nil { + t.Fatal(err) + } + grahamPerms := users.SourceFilePermissions{ + View: true, Download: true, Modify: true, Create: true, Delete: false, + } + assertSourceFilePerms(t, graham, playwrightPath, grahamPerms) + assertSourceFilePerms(t, graham, dockerPath, grahamPerms) + + allRules, err := sqlStore.GetAllAccessRules() + if err != nil { + t.Fatal(err) + } + playwrightRules := allRules[playwrightPath] + if rule, ok := playwrightRules["/text-files/bash.sh/"]; !ok || len(rule.Deny.Users) != 1 { + t.Fatalf("playwright access rule=%+v ok=%v", rule, ok) + } else if _, denied := rule.Deny.Users["admin"]; !denied { + t.Fatalf("playwright access rule deny=%+v", rule.Deny.Users) + } + + accessRules := allRules[accessPath] + if len(accessRules) != 1 { + t.Fatalf("access source rule count=%d", len(accessRules)) + } + if rule, ok := accessRules["/"]; !ok || len(rule.Deny.Users) != 1 { + t.Fatalf("access source rule=%+v ok=%v", rule, ok) + } else if _, denied := rule.Deny.Users["basic"]; !denied { + t.Fatalf("access source rule deny=%+v", rule.Deny.Users) + } + + shares, err := sqlStore.GetSharesByUserID(admin.ID) + if err != nil { + t.Fatal(err) + } + if len(shares) != 2 { + t.Fatalf("share count=%d", len(shares)) + } + shareByHash := make(map[string]*share.Share, len(shares)) + for _, s := range shares { + shareByHash[s.Hash] = s + } + if link, ok := shareByHash["lMhwHkF-hqCN92-QIJJZow"]; !ok || link.Path != "/myfolder/" || + !link.AllowModify || !link.AllowCreate || !link.AllowDelete { + t.Fatalf("myfolder share=%+v", link) + } + if link, ok := shareByHash["dGhQi4AcMhva2Ne-7x7fvw"]; !ok || link.Path != "/test & test.txt/" || + link.AllowModify || link.AllowCreate || link.AllowDelete { + t.Fatalf("test share=%+v", link) + } +} + +func assertSourceFilePerms(t *testing.T, user *users.User, sourcePath string, want users.SourceFilePermissions) { + t.Helper() + got, ok := user.BackendSourcePermissions[sourcePath] + if !ok { + t.Fatalf("user %q missing source permissions for %q", user.Username, sourcePath) + } + if got != want { + t.Fatalf("user %q source %q perms=%+v want=%+v", user.Username, sourcePath, got, want) + } +} diff --git a/backend/cmd/migration_sidebar_test.go b/backend/cmd/migration_sidebar_test.go new file mode 100644 index 0000000000..a8e0c11eec --- /dev/null +++ b/backend/cmd/migration_sidebar_test.go @@ -0,0 +1,124 @@ +package cmd + +import ( + "path/filepath" + "testing" + + storm "github.com/asdine/storm/v3" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/sqldb" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/usersidebar" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func writeSidebarMigrationBolt(t *testing.T, path string) { + t.Helper() + db, err := storm.Open(path) + if err != nil { + t.Fatal(err) + } + defer db.Close() + + user := &users.User{ + ID: 1, + FrontendUser: users.FrontendUser{ + NonAdminEditable: users.NonAdminEditable{ + Password: "$2a$10$IYCsziHjzH0mPc.bZwRuXefQKPVXfFqjdyfVmNcL.XZJsgyfxljDy", + SidebarLinks: []users.SidebarLink{ + { + Name: "My Files", + Category: string(users.SidebarLinkSourceMinimal), + Icon: "folder", + SourceName: fixturePlaywrightSource, + Target: "/", + }, + { + Name: "External Docs", + Category: string(users.SidebarLinkCustom), + Target: "https://example.com/docs", + Icon: "link", + }, + }, + }, + Username: "sidebaruser", + LoginMethod: users.LoginMethodPassword, + FrontendScopes: []users.FrontendScope{ + {Name: fixturePlaywrightSource, Scope: "/"}, + {Name: fixtureDockerSource, Scope: "/"}, + }, + Permissions: users.Permissions{ + Download: true, + }, + }, + Version: 3, + } + if err := db.Save(user); err != nil { + t.Fatal(err) + } +} + +func TestMigrationSidebarLinks_customMinimalPartialScopesAndCustomURL(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize(settingsMigrationConfigPath(t)) + settings.Env.IsPlaywright = true + alignSettingsSourcesForMigrationFixture(t) + + boltPath := filepath.Join(t.TempDir(), "sidebar-migration.db.old") + writeSidebarMigrationBolt(t, boltPath) + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + settings.Config.Server.DatabaseV2.Path = dbPath + settings.Config.Server.DatabaseV2.MigrateFrom = boltPath + + if err := migrateFromBoltToSQLite(); err != nil { + t.Fatal(err) + } + + sqlStore, _, err := sqldb.NewSQLStoreWithOptions(dbPath, sqldb.NewSQLStoreOpts{SkipQuickSetup: true}) + if err != nil { + t.Fatal(err) + } + defer sqlStore.Close() + + sidebarUser, err := sqlStore.GetUserByUsername("sidebaruser") + if err != nil { + t.Fatal(err) + } + + links := sidebarUser.SidebarLinks + if len(links) < 3 { + t.Fatalf("sidebaruser links=%#v, want at least 3 after scope merge", links) + } + + var minimalLink *users.SidebarLink + var customLink *users.SidebarLink + var dockerLink *users.SidebarLink + for i := range links { + link := links[i] + switch { + case link.Category == string(users.SidebarLinkSourceMinimal): + minimalLink = &links[i] + case link.Category == string(users.SidebarLinkCustom): + customLink = &links[i] + case link.SourceName == fixtureDockerSource || link.Name == "docker": + dockerLink = &links[i] + } + } + if minimalLink == nil { + t.Fatalf("missing source-minimal link in %#v", links) + } + if minimalLink.Name != "My Files" || minimalLink.Icon != "folder" { + t.Fatalf("custom minimal link not preserved: %#v", *minimalLink) + } + if customLink == nil || customLink.Name != "External Docs" || customLink.Target != "https://example.com/docs" { + t.Fatalf("custom link not preserved: %#v", customLink) + } + if dockerLink == nil { + t.Fatalf("docker scope link missing after merge: %#v", links) + } + + frontendLinks := usersidebar.FrontendLinks(links, true) + if len(frontendLinks) < 3 { + t.Fatalf("frontend links=%#v", frontendLinks) + } +} diff --git a/backend/cmd/office.go b/backend/cmd/office.go index 91f6fa0db9..d18e55084d 100644 --- a/backend/cmd/office.go +++ b/backend/cmd/office.go @@ -3,7 +3,7 @@ package cmd import ( "net/http" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" "github.com/gtsteffaniak/go-logger/logger" ) diff --git a/backend/cmd/root.go b/backend/cmd/root.go index eaac50ef88..9b03abe540 100644 --- a/backend/cmd/root.go +++ b/backend/cmd/root.go @@ -11,47 +11,48 @@ import ( _ "net/http/pprof" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/auth" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/common/version" - "github.com/gtsteffaniak/filebrowser/backend/database/storage" - "github.com/gtsteffaniak/filebrowser/backend/database/storage/bolt" - "github.com/gtsteffaniak/filebrowser/backend/ffmpeg" - fbhttp "github.com/gtsteffaniak/filebrowser/backend/http" - "github.com/gtsteffaniak/filebrowser/backend/icons" - "github.com/gtsteffaniak/filebrowser/backend/indexing" - "github.com/gtsteffaniak/filebrowser/backend/preview" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + "github.com/gtsteffaniak/filebrowser/backend/internal/analytics" + "github.com/gtsteffaniak/filebrowser/backend/internal/app" + "github.com/gtsteffaniak/filebrowser/backend/internal/icons" + "github.com/gtsteffaniak/filebrowser/backend/internal/preview" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/version" + "github.com/gtsteffaniak/filebrowser/backend/internal/web" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" "github.com/gtsteffaniak/filebrowser/backend/swagger/docs" "github.com/gtsteffaniak/go-logger/logger" "github.com/swaggo/swag" ) -var store *bolt.BoltStore +var runtimeApp *app.App -func getStore(configFile string) bool { - // Use the config file (global flag) +func initializeDatabase(configFile string) bool { settings.Initialize(configFile) - s, hasDB, err := storage.InitializeDb(settings.Config.Server.Database) - if err != nil { - logger.Fatalf("could not load db info: %v", err) - } - store = s - return hasDB -} -func generalUsage() { - fmt.Printf(`usage: ./filebrowser [options] -commands: - -h Print help - -c Print the default config file - version Print version information - set -u Username and password for the new user - set -a Create user as admin - set -s Specify a user scope - set -h Print this help message -`) + if err := validateDatabasePaths(); err != nil { + logger.Fatalf("%v", err) + } + + if checkMigrationNeeded() { + logger.Info("Old database detected, starting migration...") + err := migrateFromBoltToSQLite() + if err != nil { + logger.Fatalf("Migration failed: %v", err) + } + } + + store, existingDb, err := state.Open(settings.Config.Server.DatabaseV2.Path) + if err != nil { + logger.Fatalf("could not initialize state: %v", err) + } + runtimeApp, err = app.WireServices(store) + if err != nil { + logger.Fatalf("could not wire services: %v", err) + } + return existingDb } func StartFilebrowser() { @@ -59,9 +60,9 @@ func StartFilebrowser() { if !keepGoing { return } - database := fmt.Sprintf("Using existing database : %v", settings.Config.Server.Database) + database := fmt.Sprintf("Using existing database : %v", settings.Config.Server.DatabaseV2.Path) if !dbExists { - database = fmt.Sprintf("Creating new database : %v", settings.Config.Server.Database) + database = fmt.Sprintf("Creating new database : %v", settings.Config.Server.DatabaseV2.Path) } if !settings.Config.Server.DisableUpdateCheck { info, _ := utils.CheckForUpdates() @@ -83,8 +84,8 @@ func StartFilebrowser() { shutdownComplete := make(chan struct{}) // Signals shutdown process is complete // Dev mode enables development features like template hot-reloading - _, err := os.Stat("http/dist") - // In dev mode, always use filesystem assets. Otherwise, check if http/dist exists + _, err := os.Stat("internal/web/dist") + // In dev mode, always use filesystem assets. Otherwise, check if internal/web/dist exists if !settings.Env.IsDevMode { settings.Env.EmbeddedFs = os.IsNotExist(err) } @@ -115,7 +116,7 @@ func StartFilebrowser() { } serverConfig := settings.Config.Server swagInfo := docs.SwaggerInfo - swagInfo.BasePath = serverConfig.BaseURL + swagInfo.BasePath = settings.Config.Http.BaseURL swag.Register(docs.SwaggerInfo.InstanceName(), swagInfo) // initialize indexing and schedule indexing ever n minutes (default 5) if len(settings.Config.Server.SourceMap) == 0 { @@ -128,26 +129,24 @@ func StartFilebrowser() { logger.Fatalf("Failed to initialize index database: %v", err) } - // Set indexing storage for persistence - if store != nil && store.Indexing != nil { - indexing.SetIndexingStorage(store.Indexing) - if isNewDb { - if err := store.Indexing.ResetAllComplexities(); err != nil { - logger.Errorf("Failed to reset index complexities: %v", err) - } + // Index metadata persistence is wired from app.WireServices during initializeDatabase. + if isNewDb { + if err := state.ResetAllIndexComplexities(); err != nil { + logger.Errorf("Failed to reset index complexities: %v", err) } } for _, source := range settings.Config.Server.SourceMap { go indexing.Initialize(source, false, isNewDb) } + analytics.StartReporter() validateUserInfo(!dbExists) validateOfficeIntegration() validateAccessRules() validateShareInfo() // Start the rootCMD in a goroutine go func() { - if err := rootCMD(ctx, store, &serverConfig, shutdownComplete); err != nil { + if err := rootCMD(ctx, &serverConfig, runtimeApp, shutdownComplete); err != nil { logger.Fatalf("Error starting filebrowser: %v", err) } close(done) // Signal that the server has stopped @@ -183,17 +182,16 @@ func StartFilebrowser() { logger.Info("Shutdown complete.") } -func rootCMD(ctx context.Context, store *bolt.BoltStore, serverConfig *settings.Server, shutdownComplete chan struct{}) error { +func rootCMD(ctx context.Context, serverConfig *settings.Server, a *app.App, shutdownComplete chan struct{}) error { if serverConfig.NumImageProcessors < 1 { logger.Fatal("Image resize workers count could not be < 1") } cacheDir := settings.Config.Server.CacheDir numWorkers := settings.Config.Server.NumImageProcessors - ffmpeg.SetFFmpegPaths() // Initialize asset filesystem before starting services if settings.Env.EmbeddedFs { - embeddedAssets := fbhttp.GetEmbeddedAssets() + embeddedAssets := web.GetEmbeddedAssets() subAssets, err := fs.Sub(embeddedAssets, "embed") if err != nil { logger.Fatalf("Failed to create sub filesystem: %v", err) @@ -209,8 +207,6 @@ func rootCMD(ctx context.Context, store *bolt.BoltStore, serverConfig *settings. logger.Fatalf("Error starting preview service: %v", err) } logger.Debugf("MuPDF Enabled : %v", settings.Env.MuPdfAvailable) - logger.Debugf("Media Enabled : %v", settings.MediaEnabled()) - logger.Debugf("Exiftool Enabled : %v", settings.Config.Integrations.Media.ExiftoolPath != "") // Generate PWA icons after preview service is initialized if err := icons.GeneratePWAIcons(); err != nil { @@ -220,11 +216,10 @@ func rootCMD(ctx context.Context, store *bolt.BoltStore, serverConfig *settings. // Initialize PWA manifest after icons are generated icons.InitializePWAManifest() - // Initialize WebAuthn/Passkey service if enabled - if err := auth.InitWebAuthn(); err != nil { - logger.Fatalf("Failed to initialize WebAuthn: %v", err) - } - - fbhttp.StartHttp(ctx, store, shutdownComplete) + web.StartHttp(ctx, web.Deps{ + Store: a.Store, + Files: a.Files, + Auth: a.Auth, + }, shutdownComplete) return nil } diff --git a/backend/cmd/share.go b/backend/cmd/share.go index 5e27531e6b..3b67aab05e 100644 --- a/backend/cmd/share.go +++ b/backend/cmd/share.go @@ -1,18 +1,15 @@ package cmd import ( - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" "github.com/gtsteffaniak/go-logger/logger" ) // validateShareInfo migrates share links to add default sidebar links func validateShareInfo() { - if store.Share == nil { - return - } - - // Get all shares - shares, err := store.Share.All() + shares, err := state.GetAllShares() if err != nil { logger.Debugf("No shares found or error getting shares: %v", err) return @@ -22,27 +19,28 @@ func validateShareInfo() { for _, link := range shares { // Check if this share needs migration (version not set or 0) if link.Version == 0 { - // Add default sidebar links - link.SidebarLinks = []users.SidebarLink{ - { - Name: "Share QR Code and Info", - Category: "shareInfo", - Target: "#", - Icon: "qr_code", - }, - { - Name: "Download", - Category: "download", - Target: "#", - Icon: "download", - }, - } - - // Set version to 1 to indicate migration is complete - link.Version = 1 - + hash := link.Hash // Save the updated share - if err := store.Share.Save(link); err != nil { + if err := state.UpdateShare(hash, func(existingShare *share.Share) error { + // Set version to 1 to indicate migration is complete + existingShare.Version = 1 + // Add default sidebar links + existingShare.SidebarLinks = []users.SidebarLink{ + { + Name: "Share QR Code and Info", + Category: "shareInfo", + Target: "#", + Icon: "qr_code", + }, + { + Name: "Download", + Category: "download", + Target: "#", + Icon: "download", + }, + } + return nil + }); err != nil { logger.Errorf("Failed to migrate share %s: %v", link.Hash, err) continue } diff --git a/backend/cmd/user.go b/backend/cmd/user.go index e2fa5a78d9..aa0b3da384 100644 --- a/backend/cmd/user.go +++ b/backend/cmd/user.go @@ -6,9 +6,11 @@ import ( "reflect" "strings" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/internal/usersidebar" "github.com/gtsteffaniak/go-logger/logger" ) @@ -16,77 +18,123 @@ var createBackup = false func validateUserInfo(newDB bool) { // update source info for users if names/sources/paths might have changed - usersList, err := store.Users.Gets() + usersList, err := state.GetAllUsers() if err != nil { logger.Fatalf("could not load users: %v", err) } - for _, user := range usersList { + for i := range usersList { + user := &usersList[i] + changedFields := make([]string, 0, 8) changePass := false - updateUser := false + if updateUserScopes(user) { - updateUser = true + changedFields = append(changedFields, "backendScopes") } if updatePermissions(user) { - updateUser = true + changedFields = append(changedFields, "permissions", "perm", "version") + } + if updateSourcePermissions(user) { + changedFields = append(changedFields, "backendScopes", "backendSourcePermissions", "version") } if updatePreviewSettings(user) { - updateUser = true + changedFields = append(changedFields, "preview") } if updateLoginType(user) { - updateUser = true + changedFields = append(changedFields, "loginMethod") } if updateShowFirstLogin(user) { - updateUser = true + changedFields = append(changedFields, "showFirstLogin") } if updateSidebarLinks(user) { - updateUser = true + changedFields = append(changedFields, "sidebarLinks") } if updateTokens(user) { - updateUser = true + changedFields = append(changedFields, "tokens", "version") } - if updateShowToolsInSidebar(user) { - updateUser = true + if normalizeApiTokenPermissions(user) { + changedFields = append(changedFields, "tokens") + } + if state.ApplyEnforcedSyncToUser(user) { + changedFields = append(changedFields, settings.UserJSONFieldsForEnforcedSync()...) + } + if state.ApplyEnforcedSourcePermissionsSyncToUser(user) { + changedFields = append(changedFields, "backendScopes", "backendSourcePermissions") + } + if user.Version < users.ProfileStorageVersion { + user.Version = users.ProfileStorageVersion + changedFields = append(changedFields, "version") } adminUser := settings.Config.Auth.AdminUsername - adminPass := settings.Config.Auth.AdminPassword - if user.Username == adminUser && adminPass != "" && user.LoginMethod == users.LoginMethodPassword { + if adminUser == "" { + adminUser = "admin" + } + if user.Username == adminUser && user.Permissions.Admin { + adminPerms := settings.AdminPerms() + if user.Permissions.Share != adminPerms.Share || user.Permissions.Api != adminPerms.Api { + user.Permissions.Share = adminPerms.Share + user.Permissions.Api = adminPerms.Api + user.Permissions.Admin = true + changedFields = append(changedFields, "permissions") + } + } + if user.Username == adminUser && settings.Config.Auth.AdminPassword != "" && user.LoginMethod == users.LoginMethodPassword { logger.Info("Resetting admin user to default username and password.") - user.Permissions.Admin = true + user.Permissions = settings.AdminPerms() user.Password = settings.Config.Auth.AdminPassword - updateUser = true + changedFields = append(changedFields, "permissions", "password") changePass = true } - if updateUser { - skipCreateBackup := os.Getenv("FILEBROWSER_DISABLE_AUTOMATIC_BACKUP") == "true" || newDB - if createBackup && !skipCreateBackup { - logger.Warning("Incompatible user settings detected, creating backup of database before converting.") - err = fileutils.CopyFile(settings.Config.Server.Database, fmt.Sprintf("%s.bak", settings.Config.Server.Database)) - if err != nil { - logger.Fatalf("Unable to create automatic backup of database due to error: %v", err) - } - } - fields := []string{"Scopes", "SidebarLinks", "Tokens", "Permissions", "Preview", "ShowFirstLogin", "LoginMethod", "Version", "ShowToolsInSidebar"} - if changePass { - fields = append(fields, "Password") - } - err := store.Users.Update(user, true, fields...) + + changedFields = dedupeFields(changedFields) + if len(changedFields) == 0 { + continue + } + + skipCreateBackup := os.Getenv("FILEBROWSER_DISABLE_AUTOMATIC_BACKUP") == "true" || newDB + if createBackup && !skipCreateBackup { + logger.Warning("Incompatible user settings detected, creating backup of database before converting.") + err = fileutils.CopyFile(settings.Config.Server.DatabaseV2.Path, fmt.Sprintf("%s.bak", settings.Config.Server.DatabaseV2.Path)) if err != nil { - logger.Errorf("could not update user: %v", err) + logger.Fatalf("Unable to create automatic backup of database due to error: %v", err) } } + plainPass := "" + if changePass { + plainPass = user.Password + } + if err := state.UpdateUser(user, plainPass, changedFields...); err != nil { + logger.Errorf("could not update user: %v", err) + } } } -func updateUserScopes(user *users.User) bool { - newScopes := []users.SourceScope{} - seen := make(map[string]struct{}) - - // Build map of existing scopes keyed by canonical source path (DB may use path or display name). - existing := make(map[string]users.SourceScope) - for _, s := range user.Scopes { - if info, ok := users.ResolveSourceKey(s.Name); ok { - existing[info.Path] = s +func dedupeFields(fields []string) []string { + seen := make(map[string]struct{}, len(fields)) + out := make([]string, 0, len(fields)) + for _, field := range fields { + field = strings.TrimSpace(field) + if field == "" { + continue } + key := strings.ToLower(field) + if _, ok := seen[key]; ok { + continue + } + seen[key] = struct{}{} + out = append(out, field) + } + return out +} + +func updateUserScopes(user *users.User) bool { + newScopes := []users.BackendScope{} + seen := make(map[string]struct{}) + hadScopes := len(user.BackendScopes) > 0 + + // Build map for existing scopes by Name + existing := make(map[string]users.BackendScope) + for _, s := range user.BackendScopes { + existing[s.Path] = s } // Preserve order by using Config.Server.Sources @@ -98,39 +146,50 @@ func updateUserScopes(user *users.User) bool { existingScope.Scope = src.Config.DefaultUserScope } } else if src.Config.DefaultEnabled { + // Only seed default-enabled sources for users with no scopes yet. + // Partial-scope users (e.g. migrated graham) must not gain extra sources on startup. + if hadScopes { + continue + } existingScope.Scope = src.Config.DefaultUserScope } else { continue } - newScopes = append(newScopes, users.SourceScope{ - Name: src.Path, - Scope: existingScope.Scope, + newScopes = append(newScopes, users.BackendScope{ + Path: src.Path, + Scope: existingScope.Scope, + Permissions: existingScope.Permissions, }) seen[src.Path] = struct{}{} } - // Preserve explicit or legacy scopes not already merged (e.g. non-defaultEnabled sources, removed sources). - for _, s := range user.Scopes { - if info, ok := users.ResolveSourceKey(s.Name); ok { - if _, already := seen[info.Path]; already { - continue - } + // Preserve user-defined scopes not matching current sources, append to end + for _, s := range user.BackendScopes { + if _, ok := seen[s.Path]; !ok { + newScopes = append(newScopes, s) } - newScopes = append(newScopes, s) } - changed := !reflect.DeepEqual(user.Scopes, newScopes) - user.Scopes = newScopes + changed := !reflect.DeepEqual(user.BackendScopes, newScopes) + user.BackendScopes = newScopes + return changed } -// updateShowToolsInSidebar one-time defaults for legacy users (Version < CurrentUserMigrationVersion) from configured userDefaults. -func updateShowToolsInSidebar(user *users.User) bool { - if user.Version >= 3 { - return false +func updateSourcePermissions(user *users.User) bool { + changed := false + if user.Version < users.SourcePermissionsMigrationVersion { + if users.MigrateToSourcePermissions(user) { + changed = true + } } - user.ShowToolsInSidebar = true - user.Version = users.CurrentUserMigrationVersion - return true + if users.EnsureSourcePermissionsForScopes( + user, + settings.DefaultSourceFilePermissions(), + settings.AdminSourceFilePermissions(), + ) { + changed = true + } + return changed } func updateShowFirstLogin(user *users.User) bool { @@ -147,6 +206,7 @@ func updatePermissions(user *users.User) bool { return false } updateUser := true + user.Permissions.Download = true // if any keys are true, set the permissions to true if user.Perm.Api { user.Permissions.Api = true @@ -188,7 +248,7 @@ func updatePermissions(user *users.User) bool { user.Permissions.Delete = true updateUser = true } - user.Version = users.CurrentUserMigrationVersion + user.Version = 2 if updateUser { createBackup = true } @@ -213,58 +273,37 @@ func updatePreviewSettings(user *users.User) bool { return false } -// updateSidebarLinks checks if user has stale source links and rebuilds them if needed +// updateSidebarLinks normalizes sidebar links and ensures scoped sources have sidebar entries. func updateSidebarLinks(user *users.User) bool { - // Count source links and check if any are still valid - sourceLinksCount := 0 - validSourceLinksCount := 0 + updated := false - for _, link := range user.SidebarLinks { - if strings.HasPrefix(link.Category, "source") { - sourceLinksCount++ - if link.SourceName == "" { - continue - } - if _, ok := users.ResolveSourceKey(link.SourceName); ok { - validSourceLinksCount++ - } - } + if normalized, changed := usersidebar.NormalizeSidebarLinks(user.SidebarLinks); changed { + user.SidebarLinks = normalized + updated = true } - // If user has no source links, don't update anything - if sourceLinksCount == 0 { - return false + if !usersidebar.NeedsSidebarLinksFromScopes(user.SidebarLinks, user.BackendScopes) { + return updated } - // If user has source links but NONE are valid, rebuild from their scopes - if validSourceLinksCount == 0 { - // Remove all existing source links - newLinks := []users.SidebarLink{} - for _, link := range user.SidebarLinks { - if !strings.HasPrefix(link.Category, "source") { - newLinks = append(newLinks, link) - } - } - - for _, scope := range user.Scopes { - info, ok := users.ResolveSourceKey(scope.Name) - if !ok { - continue - } - newLinks = append(newLinks, users.SidebarLink{ - Name: info.Name, - Category: "source", - Target: "/", - Icon: "", - SourceName: info.Path, - }) - } - - user.SidebarLinks = newLinks - return true + if usersidebar.ValidSourceSidebarLinkCount(user.SidebarLinks) == 0 && len(user.SidebarLinks) > 0 { + logger.Infof("User %s has stale source sidebar links, merging missing links from scopes", user.Username) + } else if usersidebar.ValidSourceSidebarLinkCount(user.SidebarLinks) == 0 { + logger.Infof("User %s has no source sidebar links, building from scopes", user.Username) + } else { + logger.Infof("User %s is missing sidebar links for some scoped sources, merging from scopes", user.Username) } - return false + merged, changed := usersidebar.EnsureSidebarLinksFromScopes(user.SidebarLinks, user.BackendScopes) + if changed { + user.SidebarLinks = merged + updated = true + } + if normalized, changed := usersidebar.NormalizeSidebarLinks(user.SidebarLinks); changed { + user.SidebarLinks = normalized + updated = true + } + return updated } func updateTokens(user *users.User) bool { @@ -275,9 +314,29 @@ func updateTokens(user *users.User) bool { user.Tokens = make(map[string]users.AuthToken) for name, token := range user.ApiKeys { token.Token = token.Key - user.Tokens[name] = token + token.Name = name + users.StoreToken(user.Tokens, token) } } - user.Version = users.CurrentUserMigrationVersion + user.Version = 2 return true } + +func normalizeApiTokenPermissions(user *users.User) bool { + if user == nil || len(user.Tokens) == 0 { + return false + } + changed := false + for name, token := range user.Tokens { + if token.Name == "" || name != token.Name { + continue + } + sanitized := users.SanitizeTokenPermissions(token.Permissions) + if sanitized != token.Permissions { + token.Permissions = sanitized + user.Tokens[name] = token + changed = true + } + } + return changed +} diff --git a/backend/cmd/user_scopes_test.go b/backend/cmd/user_scopes_test.go new file mode 100644 index 0000000000..75404b5a7b --- /dev/null +++ b/backend/cmd/user_scopes_test.go @@ -0,0 +1,107 @@ +package cmd + +import ( + "path/filepath" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/sqldb" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/usersidebar" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func TestUpdateUserScopes_preservesPartialScopes(t *testing.T) { + settings.Initialize(settingsMigrationConfigPath(t)) + alignSettingsSourcesForMigrationFixture(t) + + user := &users.User{ + FrontendUser: users.FrontendUser{Username: "graham"}, + BackendScopes: []users.BackendScope{ + {Path: fixturePlaywrightSource, Scope: "/myfolder"}, + {Path: fixtureDockerSource, Scope: "/"}, + }, + } + + updateUserScopes(user) + if len(user.BackendScopes) != 2 { + t.Fatalf("scopes=%#v want 2 partial scopes", user.BackendScopes) + } + for _, scope := range user.BackendScopes { + if scope.Path == fixtureAccessSource { + t.Fatalf("access source should not be added to partial-scope user: %#v", user.BackendScopes) + } + } +} + +func TestMigrationGraham_noAccessScopeOrSidebarLink(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize(settingsMigrationConfigPath(t)) + settings.Env.IsPlaywright = true + alignSettingsSourcesForMigrationFixture(t) + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + settings.Config.Server.DatabaseV2.Path = dbPath + settings.Config.Server.DatabaseV2.MigrateFrom = settingsMigrationBoltPath(t) + if err := migrateFromBoltToSQLite(); err != nil { + t.Fatal(err) + } + + sqlStore, _, err := sqldb.NewSQLStoreWithOptions(dbPath, sqldb.NewSQLStoreOpts{SkipQuickSetup: true}) + if err != nil { + t.Fatal(err) + } + defer sqlStore.Close() + + graham, err := sqlStore.GetUserByUsername("graham") + if err != nil { + t.Fatal(err) + } + if graham.BackendSourcePermissions == nil { + t.Fatal("expected backend source permissions after migration") + } + if _, ok := graham.BackendSourcePermissions[fixtureAccessSource]; ok { + t.Fatalf("graham should not have access permissions after migration: %#v", graham.BackendSourcePermissions) + } + + for _, link := range usersidebar.FrontendLinks(graham.SidebarLinks, true) { + if link.Name == "access" { + t.Fatalf("graham should not have access sidebar link after migration: %#v", graham.SidebarLinks) + } + } + + updateUserScopes(graham) + updateSourcePermissions(graham) + updateSidebarLinks(graham) + + for _, scope := range graham.BackendScopes { + if scope.Path == fixtureAccessSource { + t.Fatalf("graham should not gain access scope: %#v", graham.BackendScopes) + } + } + if _, ok := graham.BackendSourcePermissions[fixtureAccessSource]; ok { + t.Fatalf("graham should not have access source permissions: %#v", graham.BackendSourcePermissions) + } + + frontendLinks := usersidebar.FrontendLinks(graham.SidebarLinks, true) + for _, link := range frontendLinks { + if link.Name == "access" { + t.Fatalf("graham should not have access sidebar link: %#v", frontendLinks) + } + } +} + +func TestUpdateUserScopes_seedsDefaultEnabledWhenEmpty(t *testing.T) { + settings.Initialize(settingsMigrationConfigPath(t)) + alignSettingsSourcesForMigrationFixture(t) + + user := &users.User{ + FrontendUser: users.FrontendUser{Username: "newuser"}, + } + + if !updateUserScopes(user) { + t.Fatal("expected default-enabled scopes to be seeded") + } + if len(user.BackendScopes) != 3 { + t.Fatalf("scopes=%#v want all default-enabled sources", user.BackendScopes) + } +} diff --git a/backend/cmd/user_sidebar_test.go b/backend/cmd/user_sidebar_test.go new file mode 100644 index 0000000000..50a6963142 --- /dev/null +++ b/backend/cmd/user_sidebar_test.go @@ -0,0 +1,79 @@ +package cmd + +import ( + "strings" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func TestUpdateSidebarLinks_dedupesDuplicateMigratedLinks(t *testing.T) { + settingsConfig := "../../_docker/src/settings/backend/config.yaml" + settings.Initialize(settingsConfig) + + user := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "admin", + NonAdminEditable: users.NonAdminEditable{ + SidebarLinks: []users.SidebarLink{ + {Name: "playwright + files", Category: "source", SourceName: "/app/frontend/tests/playwright-files", Target: "/"}, + {Name: "docker", Category: "source", SourceName: "/app/backend", Target: "/"}, + {Name: "access", Category: "source", SourceName: "/tests/playwright-files", Target: "/"}, + {Name: "playwright + files", Category: "source", SourceName: "../frontend/tests/playwright-files", Target: "/"}, + {Name: "docker", Category: "source", SourceName: ".", Target: "/"}, + {Name: "access", Category: "source", SourceName: "/tests/playwright-files", Target: "/"}, + }, + }, + }, + BackendScopes: []users.BackendScope{ + {Path: "../frontend/tests/playwright-files", Scope: "/"}, + {Path: ".", Scope: "/"}, + {Path: "/tests/playwright-files", Scope: "/"}, + }, + } + + if !updateSidebarLinks(user) { + t.Fatal("expected updateSidebarLinks to return true") + } + + count := 0 + for _, link := range user.SidebarLinks { + if strings.HasPrefix(link.Category, "source") { + count++ + } + } + if count != 3 { + t.Fatalf("got %d source links, want 3: %v", count, user.SidebarLinks) + } +} + +func TestUpdateSidebarLinks_buildsFromScopesWhenNoSourceLinks(t *testing.T) { + settings.Initialize(settingsMigrationConfigPath(t)) + alignSettingsSourcesForMigrationFixture(t) + + user := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "admin", + }, + BackendScopes: []users.BackendScope{ + {Path: fixturePlaywrightSource, Scope: "/"}, + {Path: fixtureDockerSource, Scope: "/"}, + {Path: fixtureAccessSource, Scope: "/"}, + }, + } + + if !updateSidebarLinks(user) { + t.Fatal("expected updateSidebarLinks to return true") + } + + count := 0 + for _, link := range user.SidebarLinks { + if strings.HasPrefix(link.Category, "source") { + count++ + } + } + if count != 3 { + t.Fatalf("got %d source links, want 3: %v", count, user.SidebarLinks) + } +} diff --git a/backend/cmd/user_test.go b/backend/cmd/user_test.go index d79a2d6643..40c9fb5341 100644 --- a/backend/cmd/user_test.go +++ b/backend/cmd/user_test.go @@ -4,8 +4,8 @@ import ( "reflect" "testing" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" "github.com/stretchr/testify/assert" ) @@ -33,108 +33,104 @@ func TestUpdateUserScopes_Phases(t *testing.T) { testCases := []struct { name string user *users.User - expectedPhase1 []users.SourceScope - expectedPhase2 []users.SourceScope + expectedPhase1 []users.BackendScope + expectedPhase2 []users.BackendScope }{ { name: "Single valid scope", user: &users.User{ - Scopes: []users.SourceScope{ - {Scope: "/home", Name: "/pathA"}, + BackendScopes: []users.BackendScope{ + {Scope: "/home", Path: "/pathA"}, }, }, - expectedPhase1: []users.SourceScope{ - {Scope: "/home", Name: "/pathA"}, - {Scope: "/defaultB", Name: "/pathB"}, + expectedPhase1: []users.BackendScope{ + {Scope: "/home", Path: "/pathA"}, }, - expectedPhase2: []users.SourceScope{ - {Scope: "/home", Name: "/pathA"}, - {Scope: "/defaultB", Name: "/pathB"}, + expectedPhase2: []users.BackendScope{ + {Scope: "/home", Path: "/pathA"}, }, }, { name: "Single empty scope path", user: &users.User{ - Scopes: []users.SourceScope{ - {Scope: "", Name: "/pathB"}, + BackendScopes: []users.BackendScope{ + {Scope: "", Path: "/pathB"}, }, }, - expectedPhase1: []users.SourceScope{ - {Scope: "/defaultB", Name: "/pathB"}, + expectedPhase1: []users.BackendScope{ + {Scope: "/defaultB", Path: "/pathB"}, }, - expectedPhase2: []users.SourceScope{ - {Scope: "/defaultA", Name: "/pathA"}, - {Scope: "/defaultB", Name: "/pathB"}, + expectedPhase2: []users.BackendScope{ + {Scope: "/defaultB", Path: "/pathB"}, }, }, { name: "Two scopes, one includes username in path", user: &users.User{ - Username: "user123", - Scopes: []users.SourceScope{ - {Scope: "/home/user123", Name: "/pathA"}, - {Scope: "/data", Name: "/pathB"}, + FrontendUser: users.FrontendUser{Username: "user123"}, + BackendScopes: []users.BackendScope{ + {Scope: "/home/user123", Path: "/pathA"}, + {Scope: "/data", Path: "/pathB"}, }, }, - expectedPhase1: []users.SourceScope{ - {Scope: "/home/user123", Name: "/pathA"}, - {Scope: "/data", Name: "/pathB"}, + expectedPhase1: []users.BackendScope{ + {Scope: "/home/user123", Path: "/pathA"}, + {Scope: "/data", Path: "/pathB"}, }, - expectedPhase2: []users.SourceScope{ - {Scope: "/home/user123", Name: "/pathA"}, - {Scope: "/data", Name: "/pathB"}, + expectedPhase2: []users.BackendScope{ + {Scope: "/home/user123", Path: "/pathA"}, + {Scope: "/data", Path: "/pathB"}, }, }, { name: "Two scopes, one with empty name", user: &users.User{ - Scopes: []users.SourceScope{ - {Scope: "/home", Name: "/pathB"}, - {Scope: "/data", Name: "/somethingElse"}, + BackendScopes: []users.BackendScope{ + {Scope: "/home", Path: "/pathB"}, + {Scope: "/data", Path: "/somethingElse"}, }, }, - expectedPhase1: []users.SourceScope{ - {Scope: "/home", Name: "/pathB"}, - {Scope: "/data", Name: "/somethingElse"}, + expectedPhase1: []users.BackendScope{ + {Scope: "/home", Path: "/pathB"}, + {Scope: "/data", Path: "/somethingElse"}, }, - expectedPhase2: []users.SourceScope{ - {Scope: "/defaultA", Name: "/pathA"}, - {Scope: "/home", Name: "/pathB"}, - {Scope: "/data", Name: "/somethingElse"}, + expectedPhase2: []users.BackendScope{ + {Scope: "/home", Path: "/pathB"}, + {Scope: "/data", Path: "/somethingElse"}, }, }, { name: "No scopes at all", user: &users.User{ - Scopes: []users.SourceScope{}, + BackendScopes: []users.BackendScope{}, }, - expectedPhase1: []users.SourceScope{ - {Scope: "/defaultB", Name: "/pathB"}, + expectedPhase1: []users.BackendScope{ + {Scope: "/defaultB", Path: "/pathB"}, }, - expectedPhase2: []users.SourceScope{ - {Scope: "/defaultA", Name: "/pathA"}, - {Scope: "/defaultB", Name: "/pathB"}, + expectedPhase2: []users.BackendScope{ + {Scope: "/defaultB", Path: "/pathB"}, }, }, { name: "All user Scope and source change", user: &users.User{ - Username: "user123", - Scopes: []users.SourceScope{ - {Scope: "/defaultC/user123", Name: "/pathC"}, - {Scope: "/defaultA/user123", Name: "/pathA"}, - {Scope: "/defaultB/user123", Name: "/pathB"}, + FrontendUser: users.FrontendUser{Username: "user123"}, + BackendScopes: []users.BackendScope{ + {Scope: "/defaultC/user123", Path: "/pathC"}, + {Scope: "/defaultA/user123", Path: "/pathA"}, + {Scope: "/defaultB/user123", Path: "/pathB"}, }, }, - expectedPhase1: []users.SourceScope{ - {Scope: "/defaultA/user123", Name: "/pathA"}, - {Scope: "/defaultB/user123", Name: "/pathB"}, - {Scope: "/defaultC/user123", Name: "/pathC"}, + // updateUserScopes emits configured sources first (Sources order), then unknown paths. + expectedPhase1: []users.BackendScope{ + {Scope: "/defaultA/user123", Path: "/pathA"}, + {Scope: "/defaultB/user123", Path: "/pathB"}, + {Scope: "/defaultC/user123", Path: "/pathC"}, }, - expectedPhase2: []users.SourceScope{ - {Scope: "/defaultA/user123", Name: "/pathA"}, - {Scope: "/defaultB/user123", Name: "/pathB"}, - {Scope: "/defaultC/user123", Name: "/pathC"}, + expectedPhase2: []users.BackendScope{ + {Scope: "/defaultA/user123", Path: "/pathA"}, + {Scope: "/defaultB/user123", Path: "/pathB"}, + {Scope: "/defaultC/user123", Path: "/pathC"}, }, }, } @@ -144,10 +140,10 @@ func TestUpdateUserScopes_Phases(t *testing.T) { // --------------------- for _, tc := range testCases { t.Run(tc.name+"_Phase1", func(t *testing.T) { - originalScopes := tc.user.Scopes + originalScopes := tc.user.BackendScopes updated := updateUserScopes(tc.user) - assert.Equal(t, tc.expectedPhase1, tc.user.Scopes, "Phase1 scope mismatch for test case: %s", tc.name) - assert.Equal(t, updated, !reflect.DeepEqual(originalScopes, tc.user.Scopes), "Phase2 scope change detection failed:\t %s vs expected:\t %s", tc.user.Scopes, tc.expectedPhase1) + assert.Equal(t, tc.expectedPhase1, tc.user.BackendScopes, "Phase1 scope mismatch for test case: %s", tc.name) + assert.Equal(t, updated, !reflect.DeepEqual(originalScopes, tc.user.BackendScopes), "Phase2 scope change detection failed:\t %s vs expected:\t %s", tc.user.BackendScopes, tc.expectedPhase1) }) } @@ -172,10 +168,10 @@ func TestUpdateUserScopes_Phases(t *testing.T) { // Run again without resetting user objects to test idempotency + renaming for _, tc := range testCases { t.Run(tc.name+"_Phase2", func(t *testing.T) { - originalScopes := tc.user.Scopes + originalScopes := tc.user.BackendScopes updated := updateUserScopes(tc.user) - assert.Equal(t, tc.expectedPhase2, tc.user.Scopes, "Phase2 scope mismatch for test case: %s", tc.name) - assert.Equal(t, updated, !reflect.DeepEqual(originalScopes, tc.user.Scopes), "Phase2 scope change detection failed:\t %s vs expected:\t %s", tc.user.Scopes, tc.expectedPhase1) + assert.Equal(t, tc.expectedPhase2, tc.user.BackendScopes, "Phase2 scope mismatch for test case: %s", tc.name) + assert.Equal(t, updated, !reflect.DeepEqual(originalScopes, tc.user.BackendScopes), "Phase2 scope change detection failed:\t %s vs expected:\t %s", tc.user.BackendScopes, tc.expectedPhase1) }) } diff --git a/backend/common/settings/generator_simple_test.go b/backend/common/settings/generator_simple_test.go deleted file mode 100644 index ce34fb9349..0000000000 --- a/backend/common/settings/generator_simple_test.go +++ /dev/null @@ -1,236 +0,0 @@ -package settings - -import ( - "regexp" - "strings" - "testing" -) - -func TestGenerateConfigYaml_Basic(t *testing.T) { - reNumber := regexp.MustCompile(`^-?\d+(\.\d+)?$`) - // Test using the actual source directory structure - trueVal := true - config := &Settings{ - UserDefaults: UserDefaults{ - Locale: "es", // Non-default value - DarkMode: &trueVal, // Default value - DisableOfficePreviewExt: ".docx .xlsx", // This field is deprecated - }, - Auth: Auth{ - Key: "secret123", // This is a secret field - AdminUsername: "testadmin", // This is a secret field - AdminPassword: "testpassword", // This is a secret field - }, - } - - // Test different combinations - testCases := []struct { - name string - showComments bool - showFull bool - filterDeprecated bool - expectSecrets bool - expectDeprecated bool - }{ - { - name: "API_mode_all_fields", - showComments: false, - showFull: true, - filterDeprecated: false, - expectSecrets: true, // Secrets should be hidden - expectDeprecated: true, // Deprecated should be shown - }, - { - name: "Static_config_filter_deprecated", - showComments: true, - showFull: true, - filterDeprecated: true, - expectSecrets: true, // Secrets should be hidden - expectDeprecated: false, // Deprecated should be filtered - }, - { - name: "Filtered_non_defaults", - showComments: false, - showFull: false, - filterDeprecated: false, - expectSecrets: true, // Secrets should be hidden - expectDeprecated: false, // Might not appear if matches default - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - // Use the current directory structure for real testing - yamlOutput, err := GenerateConfigYaml(config, tc.showComments, tc.showFull, tc.filterDeprecated) - if err != nil { - t.Fatalf("GenerateConfigYaml failed: %v", err) - } - - // Basic validation - should produce some output - if len(yamlOutput) == 0 { - t.Fatal("Generated empty YAML") - } - - // Test string quoting - string values should be quoted, numbers and booleans should not - lines := strings.Split(yamlOutput, "\n") - for _, line := range lines { - if strings.Contains(line, ":") && !strings.HasSuffix(strings.TrimSpace(line), ":") { - // This is a key-value line, skip comment portion - parts := strings.SplitN(line, ":", 2) - if len(parts) == 2 { - value := strings.TrimSpace(parts[1]) - // Remove comments - if commentIdx := strings.Index(value, "#"); commentIdx >= 0 { - value = strings.TrimSpace(value[:commentIdx]) - } - - // Skip empty values, arrays, and objects - if value == "" || strings.HasPrefix(value, "[") || strings.HasPrefix(value, "{") { - continue - } - - // Check if it's a number (should NOT be quoted) - if reNumber.MatchString(value) { - if strings.HasPrefix(value, "\"") { - t.Errorf("Numeric value should not be quoted in line: %s (value: '%s')", line, value) - } - continue - } - - // Check if it's a boolean (should NOT be quoted) - if value == "true" || value == "false" { - if strings.HasPrefix(value, "\"") { - t.Errorf("Boolean value should not be quoted in line: %s (value: '%s')", line, value) - } - continue - } - - // Check if it's null (should NOT be quoted - it's a YAML literal for nil) - if value == "null" { - continue - } - - // Everything else should be a quoted string - if !strings.HasPrefix(value, "\"") || !strings.HasSuffix(value, "\"") { - // Add debug info to see what's wrong - t.Logf("DEBUG: Checking value '%s' from line '%s'", value, strings.TrimSpace(line)) - t.Errorf("String value should be quoted in line: %s (value: %s)", strings.TrimSpace(line), value) - } - } - } - } - - // Test secret hiding - if tc.expectSecrets { - if !strings.Contains(yamlOutput, "**hidden**") { - t.Error("Expected secrets to be hidden with **hidden**") - } - if strings.Contains(yamlOutput, "secret123") || strings.Contains(yamlOutput, "testadmin") || strings.Contains(yamlOutput, "testpassword") { - t.Error("Secret values should not appear in output") - } - } - - // Test deprecated field filtering - hasDeprecated := strings.Contains(yamlOutput, "disableOfficePreviewExt") - if tc.expectDeprecated && !hasDeprecated { - t.Error("Expected deprecated field to be present") - } - if !tc.expectDeprecated && hasDeprecated && tc.filterDeprecated { - t.Error("Expected deprecated field to be filtered out when filterDeprecated=true") - } - - // Test comments - hasComments := strings.Contains(yamlOutput, "#") - if tc.showComments && !hasComments { - t.Error("Expected comments to be present when showComments=true") - } - - t.Logf("Test case: %s\nGenerated YAML:\n%s\n", tc.name, yamlOutput) - }) - } -} - -func TestCollectCommentsAndSecrets_Basic(t *testing.T) { - // Test the comment and secret collection directly - comments, secrets, deprecated, err := CollectCommentsAndSecrets(".") - if err != nil { - t.Fatalf("CollectCommentsAndSecrets failed: %v", err) - } - - // Should find some secrets in the actual source files - foundSecrets := false - for typeName, typeSecrets := range secrets { - for fieldName := range typeSecrets { - t.Logf("Found secret: %s.%s", typeName, fieldName) - foundSecrets = true - } - } - if !foundSecrets { - t.Error("Expected to find some secret fields in the actual source code") - } - - // Should find some deprecated fields - foundDeprecated := false - for typeName, typeDeprecated := range deprecated { - for fieldName := range typeDeprecated { - t.Logf("Found deprecated: %s.%s", typeName, fieldName) - foundDeprecated = true - } - } - if !foundDeprecated { - t.Error("Expected to find some deprecated fields in the actual source code") - } - - t.Logf("Comments: %d types", len(comments)) - t.Logf("Secrets: %d types", len(secrets)) - t.Logf("Deprecated: %d types", len(deprecated)) -} - -func TestGenerateYaml_StaticGeneration(t *testing.T) { - // Test the static generation function that's used by FILEBROWSER_GENERATE_CONFIG=true - - // Create a temporary config for testing - config := &Settings{ - UserDefaults: UserDefaults{ - Locale: "en", - DisableOfficePreviewExt: ".docx .xlsx", // This should be filtered out - }, - Auth: Auth{ - Key: "test-secret", // This should be redacted - }, - } - - // Test static generation with comments and deprecated filtering - yamlOutput, err := GenerateConfigYamlWithSource(config, true, true, true, ".") - if err != nil { - t.Fatalf("Static generation failed: %v", err) - } - - // Verify comments are included - if !strings.Contains(yamlOutput, "#") { - t.Error("Static generation should include comments") - } - - // Verify deprecated field is filtered out - if strings.Contains(yamlOutput, "disableOfficePreviewExt") { - t.Error("Static generation should filter out deprecated field disableOfficePreviewExt") - } - - // Verify secrets are redacted - if !strings.Contains(yamlOutput, "**hidden**") { - t.Error("Static generation should redact secrets") - } - if strings.Contains(yamlOutput, "test-secret") { - t.Error("Static generation should not contain actual secret values") - } - - // Verify it has proper structure - if !strings.Contains(yamlOutput, "userDefaults:") { - t.Error("Static generation should contain userDefaults section") - } - if !strings.Contains(yamlOutput, "auth:") { - t.Error("Static generation should contain auth section") - } - - t.Logf("Static generation successful with comments and proper filtering") -} diff --git a/backend/common/settings/migration_test.go b/backend/common/settings/migration_test.go deleted file mode 100644 index d048a6ac30..0000000000 --- a/backend/common/settings/migration_test.go +++ /dev/null @@ -1,221 +0,0 @@ -package settings - -import ( - "testing" - - "github.com/gtsteffaniak/filebrowser/backend/database/users" -) - -// TestMigrateUserDefaults_OldToNew verifies that deprecated fields are correctly migrated to new fields -func TestMigrateUserDefaults_OldToNew(t *testing.T) { - // Setup: Create UserDefaults with old fields set - Config.UserDefaults = UserDefaults{ - // Old deprecated fields - DarkMode: boolPtr(true), - DisableQuickToggles: true, - HideSidebarFileActions: true, - StickySidebar: true, - SingleClick: true, - HideFilesInTree: true, - ShowToolsInSidebar: boolPtr(false), - DeleteWithoutConfirming: true, - DateFormat: true, - ShowHidden: true, - QuickDownload: true, - ShowSelectMultiple: true, - HideFileExt: ".tmp", - ShowCopyPath: true, - DeleteAfterArchive: true, - DisablePreviewExt: ".exe", - EditorQuickSave: true, - DisableViewingExt: ".bin", - DisableOnlyOfficeExt: ".md", - PreferEditorForMarkdown: true, - DebugOffice: true, - DisableSearchOptions: true, - ThemeColor: "var(--red)", - CustomTheme: "dark", - Locale: "de", - LockPassword: true, - DisableSettings: true, - LoginMethod: "oidc", - DisableUpdateNotifications: true, - Permissions: UserDefaultsPermissions{ - Api: true, - Admin: true, - Modify: true, - Share: true, - Realtime: true, - Delete: true, - Create: true, - Download: boolPtr(false), - }, - Preview: UserDefaultsPreview{ - Image: boolPtr(true), - Video: boolPtr(true), - Audio: boolPtr(true), - MotionVideoPreview: boolPtr(true), - Office: boolPtr(true), - PopUp: boolPtr(true), - HighQuality: boolPtr(true), - Folder: boolPtr(true), - Models: boolPtr(true), - // Deprecated fields that should be migrated - DisableHideSidebar: true, - AutoplayMedia: true, - DefaultMediaPlayer: true, - }, - FileLoading: users.FileLoading{ - MaxConcurrent: 5, - UploadChunkSize: 20, - }, - } - - // Execute: Run migration - migrateUserDefaults() - - // Verify: Check that new fields are populated from old fields - ud := &Config.UserDefaults - - // Sidebar fields - if !ud.Sidebar.DisableQuickToggles { - t.Error("sidebar.disableQuickToggles should be true") - } - if !ud.Sidebar.HideFileActions { - t.Error("sidebar.hideFileActions should be true") - } - if !ud.Sidebar.Sticky { - t.Error("sidebar.sticky should be true") - } - if !ud.Sidebar.HideFiles { - t.Error("sidebar.hideFiles should be true") - } - if ud.Sidebar.ShowTools == nil || *ud.Sidebar.ShowTools != false { - t.Error("sidebar.showTools should be false") - } - if !ud.Sidebar.DisableHideOnPreview { - t.Error("sidebar.disableHideOnPreview should be true") - } - - // Listing fields - if !ud.Listing.DeleteWithoutConfirming { - t.Error("listing.deleteWithoutConfirming should be true") - } - if !ud.Listing.DateFormat { - t.Error("listing.dateFormat should be true") - } - if !ud.Listing.ShowHidden { - t.Error("listing.showHidden should be true") - } - if !ud.Listing.QuickDownload { - t.Error("listing.quickDownload should be true") - } - if !ud.Listing.ShowSelectMultiple { - t.Error("listing.showSelectMultiple should be true") - } - if !ud.Listing.SingleClick { - t.Error("listing.singleClick should be true") - } - if ud.Listing.HideFileExt != ".tmp" { - t.Errorf("listing.hideFileExt should be '.tmp', got '%s'", ud.Listing.HideFileExt) - } - if !ud.Listing.ShowCopyPath { - t.Error("listing.showCopyPath should be true") - } - if !ud.Listing.DeleteAfterArchive { - t.Error("listing.deleteAfterArchive should be true") - } - - // Preview fields - if ud.Preview.Image == nil || *ud.Preview.Image != true { - t.Error("preview.image should be true") - } - if ud.Preview.Video == nil || *ud.Preview.Video != true { - t.Error("preview.video should be true") - } - if ud.Preview.Audio == nil || *ud.Preview.Audio != true { - t.Error("preview.audio should be true") - } - if ud.Preview.DisablePreviewExt != ".exe" { - t.Errorf("preview.disablePreviewExt should be '.exe', got '%s'", ud.Preview.DisablePreviewExt) - } - - // FileViewer fields - if !ud.FileViewer.EditorQuickSave { - t.Error("fileViewer.editorQuickSave should be true") - } - if ud.FileViewer.AutoplayMedia == nil || *ud.FileViewer.AutoplayMedia != true { - t.Error("fileViewer.autoplayMedia should be true") - } - if ud.FileViewer.DisableViewingExt != ".bin" { - t.Errorf("fileViewer.disableViewingExt should be '.bin', got '%s'", ud.FileViewer.DisableViewingExt) - } - if ud.FileViewer.DisableOnlyOfficeExt != ".md" { - t.Errorf("fileViewer.disableOnlyOfficeExt should be '.md', got '%s'", ud.FileViewer.DisableOnlyOfficeExt) - } - if !ud.FileViewer.PreferEditorForMarkdown { - t.Error("fileViewer.preferEditorForMarkdown should be true") - } - if !ud.FileViewer.DebugOffice { - t.Error("fileViewer.debugOffice should be true") - } - - // Search fields - if !ud.Search.DisableOptions { - t.Error("search.disableOptions should be true") - } - - // UI fields - if ud.UI.DarkMode == nil || *ud.UI.DarkMode != true { - t.Error("ui.darkMode should be true") - } - if ud.UI.ThemeColor != "var(--red)" { - t.Errorf("ui.themeColor should be 'var(--red)', got '%s'", ud.UI.ThemeColor) - } - if ud.UI.CustomTheme != "dark" { - t.Errorf("ui.customTheme should be 'dark', got '%s'", ud.UI.CustomTheme) - } - if ud.UI.Locale != "de" { - t.Errorf("ui.locale should be 'de', got '%s'", ud.UI.Locale) - } - - // Account fields - if !ud.Account.LockPassword { - t.Error("account.lockPassword should be true") - } - if !ud.Account.DisableSettings { - t.Error("account.disableSettings should be true") - } - if ud.Account.LoginMethod != "oidc" { - t.Errorf("account.loginMethod should be 'oidc', got '%s'", ud.Account.LoginMethod) - } - if !ud.Account.DisableUpdateNotifications { - t.Error("account.disableUpdateNotifications should be true") - } - - // Account Permissions - if !ud.Account.Permissions.Api { - t.Error("account.permissions.api should be true") - } - if !ud.Account.Permissions.Admin { - t.Error("account.permissions.admin should be true") - } - if !ud.Account.Permissions.Modify { - t.Error("account.permissions.modify should be true") - } - if !ud.Account.Permissions.Share { - t.Error("account.permissions.share should be true") - } - if !ud.Account.Permissions.Realtime { - t.Error("account.permissions.realtime should be true") - } - if !ud.Account.Permissions.Delete { - t.Error("account.permissions.delete should be true") - } - if !ud.Account.Permissions.Create { - t.Error("account.permissions.create should be true") - } - if ud.Account.Permissions.Download == nil || *ud.Account.Permissions.Download != false { - t.Error("account.permissions.download should be false") - } -} diff --git a/backend/common/settings/settings.go b/backend/common/settings/settings.go deleted file mode 100644 index e8ed9b3f16..0000000000 --- a/backend/common/settings/settings.go +++ /dev/null @@ -1,173 +0,0 @@ -//go:generate go run ./tools/yaml.go -input=common/settings/settings.go -output=config.generated.yaml -package settings - -import ( - "crypto/rand" - - "github.com/gtsteffaniak/filebrowser/backend/database/users" -) - -// boolPtr returns a pointer to a bool value -func boolPtr(b bool) *bool { - return &b -} - -// boolValueOrDefault returns the value of a bool pointer, or the default if nil -func boolValueOrDefault(ptr *bool, defaultValue bool) bool { - if ptr != nil { - return *ptr - } - return defaultValue -} - -// ConvertPermissionsToUsers converts UserDefaultsPermissions to users.Permissions -func ConvertPermissionsToUsers(p UserDefaultsAccountPermissions) users.Permissions { - return users.Permissions{ - Api: p.Api, - Admin: p.Admin, - Modify: p.Modify, - Share: p.Share, - Realtime: p.Realtime, - Delete: p.Delete, - Create: p.Create, - Download: boolValueOrDefault(p.Download, true), - } -} - -const DefaultUsersHomeBasePath = "/users" - -// AuthMethod describes an authentication method. -type AuthMethod string - -// GenerateKey generates a key of 512 bits. -func GenerateKey() ([]byte, error) { - b := make([]byte, 64) - _, err := rand.Read(b) - // Note that err == nil only if we read len(b) bytes. - if err != nil { - return nil, err - } - - return b, nil -} - -func GetSettingsConfig(nameType string, Value string) string { - return nameType + Value -} - -func AdminPerms() users.Permissions { - return users.Permissions{ - Modify: true, - Share: true, - Admin: true, - Api: true, - Download: true, - Delete: true, - Create: true, - Realtime: false, - } -} - -// Apply applies the default options to a user. -// Keep this in sync with [UserDefaults]: every user-facing field there should be copied -// here (except DefaultScopes, which is wired through source config rather than this helper). -func ApplyUserDefaults(u *users.User) { - d := Config.UserDefaults - - // Account settings - u.DisableSettings = d.Account.DisableSettings - u.LockPassword = d.Account.LockPassword - u.DisableUpdateNotifications = d.Account.DisableUpdateNotifications - - // Sidebar settings - u.DisableQuickToggles = d.Sidebar.DisableQuickToggles - u.HideSidebarFileActions = d.Sidebar.HideFileActions - u.StickySidebar = d.Sidebar.Sticky - u.HideFilesInTree = d.Sidebar.HideFiles - u.ShowToolsInSidebar = boolValueOrDefault(d.Sidebar.ShowTools, true) - - // Listing settings - u.DeleteWithoutConfirming = d.Listing.DeleteWithoutConfirming - u.DateFormat = d.Listing.DateFormat - u.ShowHidden = d.Listing.ShowHidden - u.QuickDownload = d.Listing.QuickDownload - u.ShowSelectMultiple = d.Listing.ShowSelectMultiple - u.SingleClick = d.Listing.SingleClick - u.HideFileExt = d.Listing.HideFileExt - u.ShowCopyPath = d.Listing.ShowCopyPath - u.DeleteAfterArchive = d.Listing.DeleteAfterArchive - u.ViewMode = d.Listing.ViewMode - u.GallerySize = d.Listing.GallerySize - - // Preview settings - u.Preview.DisableHideSidebar = d.Sidebar.DisableHideOnPreview - u.Preview.Image = boolValueOrDefault(d.Preview.Image, true) - u.Preview.Video = boolValueOrDefault(d.Preview.Video, true) - u.Preview.Audio = boolValueOrDefault(d.Preview.Audio, true) - u.Preview.MotionVideoPreview = boolValueOrDefault(d.Preview.MotionVideoPreview, true) - u.Preview.Office = boolValueOrDefault(d.Preview.Office, true) - u.Preview.PopUp = boolValueOrDefault(d.Preview.PopUp, true) - u.Preview.Folder = boolValueOrDefault(d.Preview.Folder, true) - u.Preview.Models = boolValueOrDefault(d.Preview.Models, true) - u.DisablePreviewExt = d.Preview.DisablePreviewExt - - // FileViewer settings - u.EditorQuickSave = d.FileViewer.EditorQuickSave - u.Preview.AutoplayMedia = boolValueOrDefault(d.FileViewer.AutoplayMedia, true) - u.Preview.DefaultMediaPlayer = d.FileViewer.DefaultMediaPlayer - u.DisableViewingExt = d.FileViewer.DisableViewingExt - u.DisableOnlyOfficeExt = d.FileViewer.DisableOnlyOfficeExt - u.DisableOfficePreviewExt = d.FileViewer.DisableOnlyOfficeExt // deprecated field, map to same source - u.PreferEditorForMarkdown = d.FileViewer.PreferEditorForMarkdown - u.DebugOffice = d.FileViewer.DebugOffice - - // Search settings - u.DisableSearchOptions = d.Search.DisableOptions - - // UI settings - u.DarkMode = boolValueOrDefault(d.UI.DarkMode, true) - u.ThemeColor = d.UI.ThemeColor - u.CustomTheme = d.UI.CustomTheme - u.Locale = d.UI.Locale - - // FileLoading settings - u.FileLoading = d.FileLoading - - if u.Username == "anonymous" { - return - } - - // Permissions - u.Permissions.Api = d.Account.Permissions.Api - u.Permissions.Admin = d.Account.Permissions.Admin - u.Permissions.Modify = d.Account.Permissions.Modify - u.Permissions.Share = d.Account.Permissions.Share - u.Permissions.Realtime = d.Account.Permissions.Realtime - u.Permissions.Delete = d.Account.Permissions.Delete - u.Permissions.Create = d.Account.Permissions.Create - u.Permissions.Download = boolValueOrDefault(d.Account.Permissions.Download, true) - - if u.LoginMethod == "" && d.Account.LoginMethod != "" { - u.LoginMethod = users.LoginMethod(d.Account.LoginMethod) - } - - if len(u.Scopes) == 0 { - for _, source := range Config.Server.Sources { - if source.Config.DefaultEnabled { - u.Scopes = append(u.Scopes, users.SourceScope{ - Name: source.Path, // backend name is path - Scope: source.Config.DefaultUserScope, - }) - u.SidebarLinks = append(u.SidebarLinks, users.SidebarLink{ - Name: source.Name, - Category: "source", - Target: "/", - Icon: "", - SourceName: source.Path, - }) - } - } - } - - u.Version = users.CurrentUserMigrationVersion -} diff --git a/backend/common/settings/validConfig.yaml b/backend/common/settings/validConfig.yaml deleted file mode 100644 index c48a8fd7f3..0000000000 --- a/backend/common/settings/validConfig.yaml +++ /dev/null @@ -1,35 +0,0 @@ -server: - numImageProcessors: 4 - socket: "" - tlsKey: "" - tlsCert: "" - disablePreviews: false - disablePreviewResize: false - port: 80 - baseURL: "/" - database: "mydb.db" - sources: - - path: "." -integrations: - office: - url: "http://localhost:9052" - secret: 6H1H7GzUk2alRkNxAPav0W02g8JS5oUd -auth: - methods: - password: - enabled: true -frontend: - name: "" - disableUsedPercentage: true -userDefaults: - locale: "" - viewMode: "" - darkMode: true - disableSettings: false - singleClick: true - permissions: - admin: true - modify: true - share: true - api: true - dateFormat: false diff --git a/backend/config.playwright.yaml b/backend/config.playwright.yaml index 1f396503d3..31bfdb6049 100644 --- a/backend/config.playwright.yaml +++ b/backend/config.playwright.yaml @@ -1,6 +1,7 @@ -server: +http: port: 8080 baseURL: "/" +server: database: "playwright-files.db" logging: - levels: "info|warning|debug|error" @@ -8,48 +9,56 @@ server: - path: "../frontend/playwright-files" config: defaultEnabled: true + defaultPermissions: + view: true + download: true + modify: false + create: false + delete: false + userDefaults: - editorQuickSave: false # show quick save button in editor - hideSidebarFileActions: false # hide the file actions in the sidebar - disableQuickToggles: false # disable the quick toggles in the sidebar - disableSearchOptions: false # disable the search options in the search bar - stickySidebar: true # keep sidebar open when navigating - darkMode: true # should dark mode be enabled - viewMode: "normal" # view mode to use: eg. normal, list, grid, or compact - singleClick: false # open directory on single click, also enables middle click to open in new tab - showHidden: false # show hidden files in the UI. On windows this includes files starting with a dot and windows hidden files - dateFormat: false # when false, the date is relative, when true, the date is an exact timestamp - gallerySize: 3 # 0-9 - the size of the gallery thumbnails - themeColor: "var(--blue)" # theme color to use: eg. #ff0000, or var(--red), var(--purple), etc - quickDownload: false # show icon to download in one click - disablePreviewExt: "" # space separated list of file extensions to disable preview for - disableViewingExt: "" # space separated list of file extensions to disable viewing for - lockPassword: false # disable the user from changing their password - disableSettings: false # disable the user from viewing the settings page + fileViewer: + editorQuickSave: false + disableOnlyOfficeExt: ".md .txt .pdf" + disableViewingExt: "" + sidebar: + hideFileActions: false + disableQuickToggles: false + sticky: true + disableHideOnPreview: true + search: + disableOptions: false + ui: + darkMode: true + themeColor: "var(--blue)" + locale: "" + listing: + singleClick: false + showHidden: false + dateFormat: false + viewMode: "normal" + gallerySize: 3 + quickDownload: false + showSelectMultiple: false + deleteWithoutConfirming: false preview: - disableHideSidebar: true # disable the hide sidebar preview for previews and editors - image: true # show thumbnail preview image for image files - video: true # show thumbnail preview image for video files - motionVideoPreview: true # show multiple frames for videos in thumbnail preview when hovering - office: true # show thumbnail preview image for office files - popup: true # show larger popup preview when hovering over thumbnail - autoplayMedia: true # autoplay media files in preview - defaultMediaPlayer: true # disable html5 media player and use the default media player - folder: true # show thumbnail preview image for folder files - permissions: - api: false # allow api access - admin: false # allow admin access - modify: false # allow modifying files - share: false # allow sharing files - realtime: false # allow realtime updates - delete: false # allow deleting files - create: false # allow creating or uploading files - download: true # allow downloading files - disableUpdateNotifications: false # disable update notifications banner for admin users - deleteWithoutConfirming: false # delete files without confirmation - disableOnlyOfficeExt: ".md .txt .pdf" # list of file extensions to disable onlyoffice editor for - showSelectMultiple: false # show select multiple files on desktop + image: true + video: true + motionVideoPreview: true + office: true + popup: true + folder: true + disablePreviewExt: "" + account: + lockPassword: false + disableSettings: false + disableUpdateNotifications: false + permissions: + api: false + admin: false + share: false + realtime: false #office: # url: "http://localhost:9052" -# secret: "6H1H7GzUk2alRkNxAPav0W02g8JS5oUd" \ No newline at end of file +# secret: "6H1H7GzUk2alRkNxAPav0W02g8JS5oUd" diff --git a/backend/config.yaml b/backend/config.yaml index 15358d264c..cd70864acd 100644 --- a/backend/config.yaml +++ b/backend/config.yaml @@ -1,8 +1,10 @@ -server: +http: port: 80 baseURL: "/" +server: logging: - - levels: "info|warning|error" + - levels: "info|error|warning|debug" + apiFilter: 'disabled' sources: - path: "/srv" auth: @@ -13,74 +15,3 @@ auth: signup: false passkey: enabled: false -userDefaults: - sidebar: - disableQuickToggles: false # disable the quick toggles in the sidebar - hideFileActions: false # hide the file actions in the sidebar - disableHideOnPreview: false # keep sidebar open when previewing files - sticky: true # keep sidebar open when navigating - hideFiles: false # hide files in the sidebar tree navigation, when true, will show only directories - showTools: true # show sidebar links of category "tool"; when false they stay in the list but are hidden in the UI - - listing: - deleteWithoutConfirming: false # delete files without confirmation - dateFormat: false # when false, the date is relative, when true, the date is an exact timestamp - showHidden: false # show hidden files in the UI. On windows this includes files starting with a dot and windows hidden files - quickDownload: false # show icon to download in one click - showSelectMultiple: false # show select multiple files on desktop - singleClick: false # open directory on single click, also enables middle click to open in new tab - hideFileExt: "" # space separated list of file extensions to hide in UI - showCopyPath: false # show copy path button in the context menu - deleteAfterArchive: true # delete source files after successful creation/extraction of archives - viewMode: "normal" # view mode to use: eg. normal, list, grid, or compact - gallerySize: 3 # 0-9 - the size of the gallery thumbnails - - preview: - image: true # show thumbnail preview image for image files (defaults to true if not set) - video: true # show thumbnail preview image for video files (defaults to true if not set) - audio: true # show thumbnail preview image for audio files (defaults to true if not set) - motionVideoPreview: true # show multiple frames for videos in thumbnail preview when hovering (defaults to true if not set) - office: true # show thumbnail preview image for office files (defaults to true if not set) - popup: true # show larger popup preview when hovering over thumbnail (defaults to true if not set) - disablePreviewExt: "" # space separated list of file extensions to disable preview for - highQuality: true # high quality preview thumbnails - folder: true # show thumbnail preview image for folder files (defaults to true if not set) - models: true # show live thumbnail preview for 3D Models files (defaults to true if not set) - - fileViewer: - editorQuickSave: false # show quick save button in editor - autoplayMedia: true # autoplay media files in preview (defaults to true if not set) - disableViewingExt: "" # space separated list of file extensions to disable viewing for - disableOnlyOfficeExt: ".md .txt .pdf .html .xml" # list of file extensions to disable onlyoffice editor for - preferEditorForMarkdown: false # prefer editor first for markdown files instead of the Markdown Viewer - debugOffice: false # debug onlyoffice editor - defaultMediaPlayer: false # disable html5 media player and use the default media player - - search: - disableOptions: false # disable the search options in the search bar - - ui: - darkMode: true # should dark mode be enabled (defaults to true if not set) - themeColor: "var(--blue)" # theme color to use: eg. #ff0000, or var(--red), var(--purple), etc - customTheme: "" # Name of theme to use chosen from custom themes config - locale: "en" # language to use: eg. de, en, or fr - - fileLoading: - maxConcurrentUpload: 10 # maximum number of concurrent uploads - uploadChunkSizeMb: 10 # upload chunk size in MB - downloadChunkSizeMb: 0 # download chunk size in MB (0 = no chunking) - - account: - permissions: - api: false # allow api access - admin: false # allow admin access - modify: false # allow modifying files - share: false # allow sharing files - realtime: false # allow realtime updates - delete: false # allow deleting files - create: false # allow creating or uploading files - download: true # allow downloading files (defaults to true if not set) - lockPassword: false # disable the user from changing their password - disableSettings: false # disable the user from viewing the settings page - loginMethod: "password" # login method to use: eg. password, proxy, oidc - disableUpdateNotifications: false # disable update notifications banner for admin users diff --git a/backend/database/share/share.go b/backend/database/share/share.go deleted file mode 100644 index 765fdb5b45..0000000000 --- a/backend/database/share/share.go +++ /dev/null @@ -1,77 +0,0 @@ -package share - -import ( - "sync" - - "github.com/gtsteffaniak/filebrowser/backend/database/users" -) - -type CommonShare struct { - DownloadsLimit int `json:"downloadsLimit,omitempty"` - ShareTheme string `json:"shareTheme,omitempty"` - DisableAnonymous bool `json:"disableAnonymous,omitempty"` - MaxBandwidth int `json:"maxBandwidth,omitempty"` - DisableThumbnails bool `json:"disableThumbnails,omitempty"` - KeepAfterExpiration bool `json:"keepAfterExpiration,omitempty"` - AllowedUsernames []string `json:"allowedUsernames,omitempty"` - ThemeColor string `json:"themeColor,omitempty"` - Banner string `json:"banner,omitempty"` - Title string `json:"title,omitempty"` - Description string `json:"description,omitempty"` - Favicon string `json:"favicon,omitempty"` - QuickDownload bool `json:"quickDownload,omitempty"` - HideNavButtons bool `json:"hideNavButtons,omitempty"` - DisableSidebar bool `json:"disableSidebar"` - Source string `json:"source,omitempty"` // backend source is path to maintain between name changes - Path string `json:"path,omitempty"` - DownloadURL string `json:"downloadURL,omitempty"` - ShareURL string `json:"shareURL,omitempty"` - FaviconUrl string `json:"faviconUrl,omitempty"` - BannerUrl string `json:"bannerUrl,omitempty"` - DisableShareCard bool `json:"disableShareCard,omitempty"` - EnforceDarkLightMode string `json:"enforceDarkLightMode,omitempty"` // "dark" or "light" - ViewMode string `json:"viewMode,omitempty"` // default view mode for anonymous users: "list", "compact", "normal", "gallery" - EnableOnlyOffice bool `json:"enableOnlyOffice,omitempty"` - ShareType string `json:"shareType"` // type of share: normal, upload, max - PerUserDownloadLimit bool `json:"perUserDownloadLimit,omitempty"` - ExtractEmbeddedSubtitles bool `json:"extractEmbeddedSubtitles,omitempty"` // can be io intensive for large files and take 10-30 seconds. - AllowDelete bool `json:"allowDelete,omitempty"` - AllowCreate bool `json:"allowCreate,omitempty"` // allow creating files - AllowModify bool `json:"allowModify,omitempty"` // allow modifying files - DisableFileViewer bool `json:"disableFileViewer,omitempty"` // don't allow viewing files - DisableDownload bool `json:"disableDownload,omitempty"` // don't allow downloading files - AllowReplacements bool `json:"allowReplacements,omitempty"` // allow replacements of files - SidebarLinks []users.SidebarLink `json:"sidebarLinks"` // customizable sidebar links - HasPassword bool `json:"hasPassword,omitempty"` - ShowHidden bool `json:"showHidden,omitempty"` // show hidden files in share (true = show, false = hide) - HideFileExt string `json:"hideFileExt,omitempty"` // show hidden files based on extensions in shares - DisableLoginOption bool `json:"disableLoginOption"` // disable login option in share (true = hide, false = show) - SourceURL string `json:"sourceURL,omitempty"` - CanEditShare bool `json:"canEditShare,omitempty"` -} -type CreateBody struct { - CommonShare - Hash string `json:"hash,omitempty"` - Password string `json:"password"` - Expires string `json:"expires"` - Unit string `json:"unit"` -} - -// Link is the information needed to build a shareable link. -type Link struct { - CommonShare - Downloads int `json:"downloads"` - Hash string `json:"hash" storm:"id,index"` - UserID uint `json:"userID"` - Expire int64 `json:"expire"` - PasswordHash string `json:"password_hash,omitempty"` - PinnedItems PinnedItems `json:"pinnedItems,omitempty"` - // Token is a random value that will only be set when PasswordHash is set. It is - // URL-Safe and is used to download links in password-protected shares via a - // query arg. - Token string `json:"token,omitempty"` - - Mu sync.Mutex `json:"-"` - UserDownloads map[string]int `json:"userDownloads,omitempty"` // Track downloads per username - Version int `json:"version,omitempty"` -} diff --git a/backend/database/share/storage.go b/backend/database/share/storage.go deleted file mode 100644 index 928d2cc7a3..0000000000 --- a/backend/database/share/storage.go +++ /dev/null @@ -1,409 +0,0 @@ -package share - -import ( - "strings" - "sync" - "time" - - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/crud" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/go-logger/logger" -) - -// StorageBackend is the interface to implement for a share storage. -type StorageBackend interface { - All() ([]*Link, error) - FindByUserID(id uint) ([]*Link, error) - GetByHash(hash string) (*Link, error) - GetCommonShareByHash(hash string) (*CommonShare, error) - GetPermanent(path, source string, id uint) (*Link, error) - GetBySourcePath(path, source string) ([]*Link, error) - Gets(path, source string, id uint) ([]*Link, error) - Save(s *Link) error - Delete(hash string) error -} - -// crudBackend implements crud.CrudBackend[Link] for share storage. -type crudBackend struct { - back StorageBackend -} - -func (c *crudBackend) GetByID(id any) (*Link, error) { - hash, ok := id.(string) - if !ok { - return nil, errors.ErrInvalidDataType - } - return c.back.GetByHash(hash) -} - -func (c *crudBackend) GetAll() ([]*Link, error) { - return c.back.All() -} - -func (c *crudBackend) Save(obj *Link) error { - return c.back.Save(obj) -} - -func (c *crudBackend) DeleteByID(id any) error { - hash, ok := id.(string) - if !ok { - return errors.ErrInvalidDataType - } - return c.back.Delete(hash) -} - -// Storage is a share storage using generics. -type Storage struct { - Generic *crud.Storage[Link] - back StorageBackend - shareByHash map[string]*Link // key: link hash - shareByPath map[string]map[string]string // key: pathKey(Source, Path), value: set of hashes (hash -> "") - mu sync.RWMutex - users *users.Storage -} - -// pathKey returns the cache key for shareByPath (source + path). -func pathKey(source, path string) string { - return source + ":" + path -} - -// setCacheLocked updates both shareByHash and shareByPath for the given link. -// Caller must hold s.mu. -func (s *Storage) setCacheLocked(link *Link) { - if link == nil { - return - } - adjustedPath := utils.AddTrailingSlashIfNotExists(link.Path) - adjustedSource := utils.AddTrailingSlashIfNotExists(link.Source) - s.shareByHash[link.Hash] = link - key := pathKey(adjustedSource, adjustedPath) - if s.shareByPath[key] == nil { - s.shareByPath[key] = make(map[string]string) - } - s.shareByPath[key][link.Hash] = "" -} - -// setCache updates both caches for the given link. It acquires s.mu. -func (s *Storage) setCache(link *Link) { - s.mu.Lock() - s.setCacheLocked(link) - s.mu.Unlock() -} - -// deleteFromCacheLocked removes the link (by hash) from both caches. -// Caller must hold s.mu. -func (s *Storage) deleteFromCacheLocked(hash string) { - link, ok := s.shareByHash[hash] - if !ok { - return - } - adjustedPath := utils.AddTrailingSlashIfNotExists(link.Path) - adjustedSource := utils.AddTrailingSlashIfNotExists(link.Source) - key := pathKey(adjustedSource, adjustedPath) - if inner, ok := s.shareByPath[key]; ok { - delete(inner, hash) - if len(inner) == 0 { - delete(s.shareByPath, key) - } - } - delete(s.shareByHash, hash) -} - -// deleteFromCache removes the link (by hash) from both caches. It acquires s.mu. -func (s *Storage) deleteFromCache(hash string) { - s.mu.Lock() - s.deleteFromCacheLocked(hash) - s.mu.Unlock() -} - -// setCacheAfterMove updates both caches when a link's Source or Path changed. It acquires s.mu. -func (s *Storage) setCacheAfterMove(link *Link, oldSource, oldPath string) { - s.mu.Lock() - if link == nil { - return - } - adjustedOldPath := utils.AddTrailingSlashIfNotExists(oldPath) - adjustedOldSource := utils.AddTrailingSlashIfNotExists(oldSource) - oldKey := pathKey(adjustedOldSource, adjustedOldPath) - if inner, ok := s.shareByPath[oldKey]; ok { - delete(inner, link.Hash) - if len(inner) == 0 { - delete(s.shareByPath, oldKey) - } - } - s.setCacheLocked(link) - s.mu.Unlock() -} - -// NewStorage creates a share links storage from a backend and populates the -// in-memory cache from the database so all reads can be served from cache. -func NewStorage(back StorageBackend, usersStore *users.Storage) *Storage { - s := &Storage{ - Generic: crud.NewStorage[Link](&crudBackend{back: back}), - back: back, - shareByHash: make(map[string]*Link), - shareByPath: make(map[string]map[string]string), - users: usersStore, - } - s.loadShareCache() - return s -} - -// loadShareCache fills shareByHash and shareByPath from the backend and removes expired links from the DB. -// Call once at startup so all reads can be served from cache. -func (s *Storage) loadShareCache() { - links, err := s.back.All() - if err != nil && err != errors.ErrNotExist { - return - } - if links == nil { - links = []*Link{} - } - s.mu.Lock() - for _, link := range links { - if link == nil { - continue - } - if link.Expire != 0 && link.Expire <= time.Now().Unix() && !link.KeepAfterExpiration { - _ = s.back.Delete(link.Hash) - continue - } - link.InitUserDownloads() - s.setCacheLocked(link) - } - s.mu.Unlock() -} - -// LoadShareCacheFromDB repopulates the in-memory cache from the database. -// Call at startup (e.g. from InitializeDb) to ensure shares are loaded after the store is ready. -func (s *Storage) LoadShareCacheFromDB() { - s.loadShareCache() -} - -// All returns all non-expired shares from the cache (populated at startup and by writes). -func (s *Storage) All() ([]*Link, error) { - s.mu.Lock() - result := make([]*Link, 0, len(s.shareByHash)) - for _, l := range s.shareByHash { - if l == nil { - continue - } - if l.Expire != 0 && l.Expire <= time.Now().Unix() && !l.KeepAfterExpiration { - _ = s.back.Delete(l.Hash) - s.deleteFromCacheLocked(l.Hash) - continue - } - result = append(result, l) - } - s.mu.Unlock() - return result, nil -} - -// FindByUserID returns non-expired shares for the user from the cache. -func (s *Storage) FindByUserID(id uint) ([]*Link, error) { - s.mu.Lock() - result := make([]*Link, 0) - for _, l := range s.shareByHash { - if l == nil || l.UserID != id { - continue - } - if l.Expire != 0 && l.Expire <= time.Now().Unix() && !l.KeepAfterExpiration { - _ = s.back.Delete(l.Hash) - s.deleteFromCacheLocked(l.Hash) - continue - } - result = append(result, l) - } - s.mu.Unlock() - return result, nil -} - -// GetByHash wraps StorageBackend.GetByHash and handles expiry. -func (s *Storage) GetByHash(hash string) (*Link, error) { - // return stable in-memory pointer if available - s.mu.RLock() - if link, ok := s.shareByHash[hash]; ok && link != nil { - s.mu.RUnlock() - if link.Expire != 0 && link.Expire <= time.Now().Unix() { - _ = s.back.Delete(hash) - s.deleteFromCache(hash) - return nil, errors.ErrNotExist - } - return link, nil - } - s.mu.RUnlock() - - link, err := s.back.GetByHash(hash) - if err != nil { - return nil, err - } - if link.Expire != 0 && link.Expire <= time.Now().Unix() { - _ = s.back.Delete(hash) - return nil, errors.ErrNotExist - } - - // Initialize UserDownloads map - link.InitUserDownloads() - - s.setCache(link) - return link, nil -} - -// GetPermanent wraps StorageBackend.GetPermanent -func (s *Storage) GetPermanent(path, source string, id uint) (*Link, error) { - l, err := s.back.GetPermanent(path, source, id) - if err == nil && l != nil { - s.setCache(l) - } - return l, err -} - -// Gets returns shares for the given path, source, and user from the cache. -func (s *Storage) Gets(sourcePath, source string, id uint) ([]*Link, error) { - s.mu.Lock() - adjustedPath := utils.AddTrailingSlashIfNotExists(sourcePath) - adjustedSource := utils.AddTrailingSlashIfNotExists(source) - key := pathKey(adjustedSource, adjustedPath) - hashes := s.shareByPath[key] - result := make([]*Link, 0, len(hashes)) - for h := range hashes { - l := s.shareByHash[h] - if l == nil || l.UserID != id { - continue - } - if l.Expire != 0 && l.Expire <= time.Now().Unix() && !l.KeepAfterExpiration { - _ = s.back.Delete(l.Hash) - s.deleteFromCacheLocked(l.Hash) - continue - } - result = append(result, l) - } - s.mu.Unlock() - return result, nil -} - -// GetBySourcePath returns shares for the given path and source from the cache. -func (s *Storage) GetBySourcePath(path, source string) ([]*Link, error) { - s.mu.Lock() - adjustedPath := utils.AddTrailingSlashIfNotExists(path) - adjustedSource := utils.AddTrailingSlashIfNotExists(source) - key := pathKey(adjustedSource, adjustedPath) - hashes := s.shareByPath[key] - result := make([]*Link, 0, len(hashes)) - for h := range hashes { - l := s.shareByHash[h] - if l == nil { - continue - } - if l.Expire != 0 && l.Expire <= time.Now().Unix() && !l.KeepAfterExpiration { - _ = s.back.Delete(l.Hash) - s.deleteFromCacheLocked(l.Hash) - continue - } - result = append(result, l) - } - s.mu.Unlock() - return result, nil -} - -// IsShared returns whether the given path and source have any shares in the cache. -func (s *Storage) IsShared(path, source string, id uint) bool { - links, _ := s.GetBySourcePath(path, source) - for _, l := range links { - if l.UserID == id { - return true - } - } - return len(links) > 0 -} - -// UpdateShares updates all shares that match oldSource and oldPath to point to newSource and newPath. -// Handles both exact matches and subdirectories, regardless of trailing slashes. -func (s *Storage) UpdateShares(oldSource, oldPath, newSource, newPath string) (int, error) { - links, err := s.All() - if err != nil && err != errors.ErrNotExist { - logger.Error("failed to list shares", "error", err) - return 0, err - } - - // Normalize paths for comparison (remove trailing slashes) - oldPath = utils.AddTrailingSlashIfNotExists(oldPath) - newPath = utils.AddTrailingSlashIfNotExists(newPath) - - updated := 0 - for _, l := range links { - if l == nil || l.Source != oldSource { - continue - } - l.Path = utils.AddTrailingSlashIfNotExists(l.Path) - - pos := strings.Index(l.Path, oldPath) - if pos < 0 { - continue - } - - l.Source = newSource - l.Path = newPath - - if err := s.back.Save(l); err != nil { - logger.Error("failed to save updated share", "hash", l.Hash, "error", err) - return updated, err - } - - s.setCacheAfterMove(l, oldSource, oldPath) - updated++ - } - return updated, nil -} - -// UpdateSharePath updates the path for a specific share identified by hash -func (s *Storage) UpdateSharePath(hash, newPath string) error { - link, err := s.GetByHash(hash) - if err != nil { - return err - } - - oldPath := link.Path - link.Path = newPath - - if err := s.back.Save(link); err != nil { - logger.Error("failed to save updated share", "hash", hash, "error", err) - return err - } - - s.setCacheAfterMove(link, link.Source, oldPath) - - logger.Debug("share path updated", "hash", hash, "fromPath", oldPath, "toPath", newPath) - return nil -} - -// Save wraps StorageBackend.Save -func (s *Storage) Save(l *Link) error { - if err := s.back.Save(l); err != nil { - return err - } - s.setCache(l) - return nil -} - -// Delete wraps StorageBackend.Delete -func (s *Storage) Delete(hash string) error { - if err := s.back.Delete(hash); err != nil { - return err - } - s.deleteFromCache(hash) - return nil -} - -// Flush is a no-op: every share write (Save, Delete, UpdateShares, UpdateSharePath) already -// updates the database, so the cache and DB stay in sync without flushing. -func (s *Storage) Flush() error { - return nil -} - -// GetCommonShareByHash retrieves only the CommonShare attributes for a given hash -func (s *Storage) GetCommonShareByHash(hash string) (*CommonShare, error) { - return s.back.GetCommonShareByHash(hash) -} diff --git a/backend/database/storage/bolt/auth.go b/backend/database/storage/bolt/auth.go deleted file mode 100644 index c3e3e31fa5..0000000000 --- a/backend/database/storage/bolt/auth.go +++ /dev/null @@ -1,30 +0,0 @@ -package bolt - -import ( - storm "github.com/asdine/storm/v3" - "github.com/gtsteffaniak/filebrowser/backend/auth" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" -) - -type authBackend struct { - db *storm.DB -} - -func (s authBackend) Get(t string) (auth.Auther, error) { - var auther auth.Auther - switch t { - case "password": - auther = &auth.JSONAuth{} - case "proxy": - auther = &auth.ProxyAuth{} - case "noauth": - auther = &auth.NoAuth{} - default: - return nil, errors.ErrInvalidAuthMethod - } - return auther, get(s.db, "auther", auther) -} - -func (s authBackend) Save(a auth.Auther) error { - return Save(s.db, "auther", a) -} diff --git a/backend/database/storage/bolt/bolt.go b/backend/database/storage/bolt/bolt.go deleted file mode 100644 index 937466b56a..0000000000 --- a/backend/database/storage/bolt/bolt.go +++ /dev/null @@ -1,40 +0,0 @@ -package bolt - -import ( - storm "github.com/asdine/storm/v3" - - "github.com/gtsteffaniak/filebrowser/backend/auth" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/database/access" - "github.com/gtsteffaniak/filebrowser/backend/database/dbindex" - "github.com/gtsteffaniak/filebrowser/backend/database/share" - "github.com/gtsteffaniak/filebrowser/backend/database/users" -) - -// Storage is a storage powered by a Backend which makes the necessary -// verifications when fetching and saving data to ensure consistency. -type BoltStore struct { - Users *users.Storage - Share *share.Storage - Auth *auth.Storage - Settings *settings.Storage - Access *access.Storage - Indexing *dbindex.Storage -} - -// NewStorage creates a storage.Storage based on Bolt DB. -func NewStorage(db *storm.DB) (*BoltStore, error) { - userStore := users.NewStorage(usersBackend{db: db}) - authStore, err := auth.NewStorage(authBackend{db: db}, userStore) - if err != nil { - return nil, err - } - return &BoltStore{ - Users: userStore, - Share: share.NewStorage(shareBackend{db: db}, userStore), - Auth: authStore, - Settings: settings.NewStorage(settingsBackend{db: db}), - Access: access.NewStorage(db, userStore), - Indexing: dbindex.NewStorage(indexingBackend{db: db}), - }, nil -} diff --git a/backend/database/storage/bolt/config.go b/backend/database/storage/bolt/config.go deleted file mode 100644 index 075bb832c9..0000000000 --- a/backend/database/storage/bolt/config.go +++ /dev/null @@ -1,31 +0,0 @@ -package bolt - -import ( - storm "github.com/asdine/storm/v3" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" -) - -type settingsBackend struct { - db *storm.DB -} - -func (s settingsBackend) Get() (*settings.Settings, error) { - set := &settings.Settings{} - return set, get(s.db, "settings", set) -} - -func (s settingsBackend) Save(set *settings.Settings) error { - return Save(s.db, "settings", set) -} - -func (s settingsBackend) GetServer() (*settings.Server, error) { - server := &settings.Server{ - Port: 80, - NumImageProcessors: 4, - } - return server, get(s.db, "server", server) -} - -func (s settingsBackend) SaveServer(server *settings.Server) error { - return Save(s.db, "server", server) -} diff --git a/backend/database/storage/bolt/indexing.go b/backend/database/storage/bolt/indexing.go deleted file mode 100644 index e087b4bbcb..0000000000 --- a/backend/database/storage/bolt/indexing.go +++ /dev/null @@ -1,55 +0,0 @@ -package bolt - -import ( - storm "github.com/asdine/storm/v3" - "github.com/asdine/storm/v3/q" - - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/database/dbindex" -) - -type indexingBackend struct { - db *storm.DB -} - -func (s indexingBackend) All() ([]*dbindex.IndexInfo, error) { - var v []*dbindex.IndexInfo - err := s.db.All(&v) - if err == storm.ErrNotFound { - return v, errors.ErrNotExist - } - - return v, err -} - -func (s indexingBackend) GetByPath(path string) (*dbindex.IndexInfo, error) { - var v dbindex.IndexInfo - err := s.db.One("Path", path, &v) - if err == storm.ErrNotFound { - return nil, errors.ErrNotExist - } - - return &v, err -} - -func (s indexingBackend) GetBySource(source string) ([]*dbindex.IndexInfo, error) { - var v []*dbindex.IndexInfo - err := s.db.Select(q.Eq("Source", source)).Find(&v) - if err == storm.ErrNotFound { - return nil, errors.ErrNotExist - } - return v, err -} - -func (s indexingBackend) Save(info *dbindex.IndexInfo) error { - return s.db.Save(info) -} - -func (s indexingBackend) Delete(path string) error { - err := s.db.DeleteStruct(&dbindex.IndexInfo{Path: path}) - if err == storm.ErrNotFound { - return nil - } - return err -} - diff --git a/backend/database/storage/bolt/share.go b/backend/database/storage/bolt/share.go deleted file mode 100644 index d564985ed6..0000000000 --- a/backend/database/storage/bolt/share.go +++ /dev/null @@ -1,111 +0,0 @@ -package bolt - -import ( - "time" - - storm "github.com/asdine/storm/v3" - "github.com/asdine/storm/v3/q" - - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/database/share" - "github.com/gtsteffaniak/go-logger/logger" -) - -type shareBackend struct { - db *storm.DB -} - -func (s shareBackend) All() ([]*share.Link, error) { - var v []*share.Link - err := s.db.All(&v) - if err == storm.ErrNotFound { - return v, errors.ErrNotExist - } - - return v, err -} - -func (s shareBackend) FindByUserID(id uint) ([]*share.Link, error) { - var v []*share.Link - err := s.db.Select(q.Eq("UserID", id)).Find(&v) - if err == storm.ErrNotFound { - return v, errors.ErrNotExist - } - - return v, err -} - -func (s shareBackend) GetByHash(hash string) (*share.Link, error) { - var v share.Link - err := s.db.One("Hash", hash, &v) - if err == storm.ErrNotFound { - return nil, errors.ErrNotExist - } - - return &v, err -} - -func (s shareBackend) GetCommonShareByHash(hash string) (*share.CommonShare, error) { - var v share.Link - err := s.db.One("Hash", hash, &v) - if err == storm.ErrNotFound { - return nil, errors.ErrNotExist - } - if err != nil { - return nil, err - } - v.Source = "" - v.Path = "" - v.AllowedUsernames = nil - v.DownloadsLimit = 0 - v.CommonShare.HasPassword = v.HasPassword() - return &v.CommonShare, nil -} - -func (s shareBackend) GetPermanent(path, source string, id uint) (*share.Link, error) { - var v share.Link - // TODO remove legacy and return notfound errors - _ = s.db.Select(q.Eq("Path", path), q.Eq("Source", source), q.Eq("Expire", 0), q.Eq("UserID", id)).First(&v) - return &v, nil -} - -// GetBySourcePath returns all shares that exactly match Path and Source across users. -func (s shareBackend) GetBySourcePath(path, source string) ([]*share.Link, error) { - var v []*share.Link - err := s.db.Select(q.Eq("Path", path), q.Eq("Source", source)).Find(&v) - if err == storm.ErrNotFound { - return nil, errors.ErrNotExist - } - return v, err -} - -func (s shareBackend) Gets(path, sourcePath string, id uint) ([]*share.Link, error) { - var v []*share.Link - _ = s.db.Select(q.Eq("Path", path), q.Eq("Source", sourcePath), q.Eq("UserID", id)).Find(&v) - filteredList := []*share.Link{} - var err error - // through and filter out expired share - for i := range v { - if v[i].Expire < time.Now().Unix() && v[i].Expire != 0 { - err = s.Delete(v[i].Hash) - if err != nil { - logger.Errorf("expired share could not be deleted: %v", err.Error()) - } - } else { - filteredList = append(filteredList, v[i]) - } - } - return filteredList, err -} - -func (s shareBackend) Save(l *share.Link) error { - return s.db.Save(l) -} - -func (s shareBackend) Delete(hash string) error { - err := s.db.DeleteStruct(&share.Link{Hash: hash}) - if err == storm.ErrNotFound { - return nil - } - return err -} diff --git a/backend/database/storage/bolt/users.go b/backend/database/storage/bolt/users.go deleted file mode 100644 index 3409f1b5ab..0000000000 --- a/backend/database/storage/bolt/users.go +++ /dev/null @@ -1,327 +0,0 @@ -package bolt - -import ( - "fmt" - "reflect" - "slices" - "strings" - - storm "github.com/asdine/storm/v3" - - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/go-logger/logger" -) - -type usersBackend struct { - db *storm.DB -} - -// NewUsersBackend returns a users.StorageBackend backed by storm DB. -func NewUsersBackend(db *storm.DB) users.StorageBackend { - return &usersBackend{db: db} -} - -func (st usersBackend) GetBy(i interface{}) (user *users.User, err error) { - user = &users.User{} - - var arg string - var val interface{} - switch i := i.(type) { - case uint: - val = i - arg = "ID" - case int: - val = uint(i) - arg = "ID" - case string: - arg = "Username" - val = i - default: - return nil, errors.ErrInvalidDataType - } - - err = st.db.One(arg, val, user) - - if err != nil { - if err == storm.ErrNotFound { - return nil, errors.ErrNotExist - } - return nil, err - } - - return -} - -func (st usersBackend) Gets() ([]*users.User, error) { - var allUsers []*users.User - err := st.db.All(&allUsers) - if err == storm.ErrNotFound { - return nil, errors.ErrNotExist - } - if err != nil { - return allUsers, err - } - return allUsers, err -} - -func (st usersBackend) Update(user *users.User, actorIsAdmin bool, fields ...string) error { - existingUser, err := st.GetBy(user.ID) - if err != nil { - return err - } - - if user.LoginMethod == "" { - user.LoginMethod = existingUser.LoginMethod - } - fields, err = parseFields(user, fields, actorIsAdmin) - if err != nil { - return err - } - enforcedOtp := settings.Config.Auth.Methods.PasswordAuth.EnforcedOtp - if user.LoginMethod == "" { - user.LoginMethod = existingUser.LoginMethod - } - if user.TOTPNonce == "" { - user.TOTPNonce = existingUser.TOTPNonce - } - if user.TOTPSecret == "" { - user.TOTPSecret = existingUser.TOTPSecret - } - if user.LoginMethod == users.LoginMethodPassword && enforcedOtp && !user.OtpEnabled { - if slices.Contains(fields, "OtpEnabled") { - return errors.ErrNoTotpConfigured - } - } - if !slices.Contains(fields, "Password") { - user.Password = existingUser.Password - } else { - if existingUser.LockPassword && !actorIsAdmin { - return fmt.Errorf("password cannot be changed when lock password is enabled") - } - } - - if !actorIsAdmin { - fields = filterRestrictedFields(fields) - } - - if len(fields) == 0 { - return fmt.Errorf("no fields to update") - } - - // converting scopes to map of paths intead of names (names can change) - if slices.Contains(fields, "Scopes") { - adjustedScopes, err := user.GetBackendScopes() - if err != nil { - return err - } - for _, scope := range adjustedScopes { - // ensure full path exists - if scope.Scope == "" { - return fmt.Errorf("scope name is required") - } - } - user.Scopes = adjustedScopes - err = files.MakeUserDirs(user, false) - if err != nil { - return err - } - } - // converting scopes to map of paths intead of names (names can change) - if slices.Contains(fields, "SidebarLinks") { - adjustedLinks, err := user.GetBackendSidebarLinks() - if err != nil { - return err - } - user.SidebarLinks = adjustedLinks - } - // Use reflection to access struct fields - userFields := reflect.ValueOf(user).Elem() // Get struct value - for _, field := range fields { - // Get the corresponding field using reflection - fieldValue := userFields.FieldByName(field) - if !fieldValue.IsValid() { - return fmt.Errorf("invalid field: %s", field) - } - - // Ensure the field is settable - if !fieldValue.CanSet() { - return fmt.Errorf("cannot set value of field: %s", field) - } - - // Get the value to be stored - val := fieldValue.Interface() - if field == "OtpEnabled" { - otpEnabled, _ := val.(bool) - if !otpEnabled { - field = "TOTPSecret" // if otp is disabled, we also want to clear the TOTPSecret - val = "" // clear the TOTPSecret - } - // If otpEnabled is true, continue with normal field update - } - // Update the database - if err := st.db.UpdateField(existingUser, field, val); err != nil { - return fmt.Errorf("failed to update user field: %s, error: %v", field, err) - } - } - - return nil -} - -func (st usersBackend) Save(user *users.User, changePass, disableScopeChange bool) error { - if user.LoginMethod == "" { - user.LoginMethod = users.LoginMethodPassword - } - if user.Username == "anonymous" { - return fmt.Errorf("username cannot be 'anonymous'") - } - logger.Debugf("Saving user [%s] changepass: %v", user.Username, changePass) - if user.LoginMethod == users.LoginMethodPassword && changePass { - err := checkPassword(user.Password) - if err != nil { - return err - } - pass, err := utils.HashPwd(user.Password) - if err != nil { - return err - } - user.Password = pass - } - - // converting scopes to map of paths intead of names (names can change) - adjustedScopes, err := user.GetBackendScopes() - if err != nil { - return err - } - user.Scopes = adjustedScopes - err = files.MakeUserDirs(user, true) - if err != nil { - logger.Error(err.Error()) - } - err = st.db.Save(user) - if err == storm.ErrAlreadyExists { - return fmt.Errorf("user with provided username already exists") - } - return err -} - -func (st usersBackend) DeleteByID(id uint) error { - return st.db.DeleteStruct(&users.User{ID: id}) -} - -func (st usersBackend) DeleteByUsername(username string) error { - user, err := st.GetBy(username) - if err != nil { - return err - } - - return st.db.DeleteStruct(user) -} - -// Define a function to filter out restricted fields for non-admin users -func filterRestrictedFields(fields []string) []string { - // Get a list of allowed fields from NonAdminEditable - allowed := getNonAdminEditableFieldNames() - var filteredFields []string - - for _, field := range fields { - if slices.Contains(allowed, field) { - filteredFields = append(filteredFields, field) - } - } - - return filteredFields -} - -// Helper to return list of field names from NonAdminEditable struct -func getNonAdminEditableFieldNames() []string { - var names []string - t := reflect.TypeOf(users.NonAdminEditable{}) - for i := 0; i < t.NumField(); i++ { - names = append(names, t.Field(i).Name) - } - return names -} - -func parseFields(user *users.User, fields []string, actorIsAdmin bool) ([]string, error) { - // If `Which` is not specified, default to updating all fields - if len(fields) == 0 || fields[0] == "all" { - fields = []string{} - v := reflect.ValueOf(user) - if v.Kind() == reflect.Pointer { - v = v.Elem() - } - t := v.Type() - - // Dynamically populate fields to update - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - // which=all can't update password - switch strings.ToLower(field.Name) { - case "id", "username", "password", "tokens", "totpsecret", "totpnonce": - // Skip these fields - continue - } - - // Handle embedded structs (like NonAdminEditable) - if field.Anonymous { - // Get the embedded struct type - embeddedType := field.Type - if embeddedType.Kind() == reflect.Pointer { - embeddedType = embeddedType.Elem() - } - - // Add all fields from the embedded struct - for j := 0; j < embeddedType.NumField(); j++ { - embeddedField := embeddedType.Field(j) - fields = append(fields, embeddedField.Name) - } - } else { - fields = append(fields, field.Name) - } - } - } - newfields := []string{} - for _, field := range fields { - capitalField := utils.CapitalizeFirst(field) - if capitalField == "Scopes" { - if !actorIsAdmin { - continue - } - } - if capitalField == "Password" { - // Only process password if it's actually being updated (not empty) - if user.Password != "" { - logger.Debugf("Updating password for user [%s] loginMethod: %s", user.Username, user.LoginMethod) - if user.LoginMethod != users.LoginMethodPassword { - return nil, fmt.Errorf("password cannot be changed when login method is not password") - } - err := checkPassword(user.Password) - if err != nil { - return nil, fmt.Errorf("password does not meet complexity requirements") - } - value, err := utils.HashPwd(user.Password) - if err != nil { - logger.Error(err.Error()) - } - user.Password = value - } else { - // Skip password field if it's empty - continue - } - } - newfields = append(newfields, capitalField) - } - - return newfields, nil -} - -func checkPassword(password string) error { - if len(password) < settings.Config.Auth.Methods.PasswordAuth.MinLength { - return fmt.Errorf("password must be at least %d characters long", settings.Config.Auth.Methods.PasswordAuth.MinLength) - } - return nil -} diff --git a/backend/database/storage/bolt/users_test.go b/backend/database/storage/bolt/users_test.go deleted file mode 100644 index 22a5034a1f..0000000000 --- a/backend/database/storage/bolt/users_test.go +++ /dev/null @@ -1,530 +0,0 @@ -package bolt - -import ( - "path/filepath" - "testing" - - "github.com/asdine/storm/v3" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/users" -) - -func init() { - utils.BcryptCost = 4 // bcrypt.MinCost for faster tests - - // Initialize test source configuration - settings.Config.Server.SourceMap = map[string]*settings.Source{ - "/tmp/test": { - Path: "/tmp/test", - Name: "test", - Config: settings.SourceConfig{ - DefaultUserScope: "/", - }, - }, - } - settings.Config.Server.NameToSource = map[string]*settings.Source{ - "test": settings.Config.Server.SourceMap["/tmp/test"], - } - settings.Config.Server.Sources = []*settings.Source{ - settings.Config.Server.SourceMap["/tmp/test"], - } - // Don't set default scopes for tests - let tests explicitly set scopes when needed - settings.Config.UserDefaults.DefaultScopes = []users.SourceScope{} - // Initialize user package resolvers - settings.InitializeUserResolvers() -} - -func createTestUsersBackend(t *testing.T) users.StorageBackend { - dir := t.TempDir() - dbPath := filepath.Join(dir, "test.db") - db, err := storm.Open(dbPath) - if err != nil { - t.Fatalf("failed to open storm db: %v", err) - } - return NewUsersBackend(db) -} - -func createTestUser(t *testing.T, backend users.StorageBackend, username string, isAdmin bool) *users.User { - user := &users.User{ - Username: username, - NonAdminEditable: users.NonAdminEditable{ - Password: "testpass123", - DarkMode: false, - OtpEnabled: true, - Locale: "en", - ViewMode: "normal", - SingleClick: false, - }, - Permissions: users.Permissions{ - Admin: isAdmin, - }, - LoginMethod: users.LoginMethodPassword, - } - - err := backend.Save(user, true, false) - if err != nil { - t.Fatalf("failed to create user %s: %v", username, err) - } - return user -} - -func TestUpdate_AdminModifyOtherUser(t *testing.T) { - backend := createTestUsersBackend(t) - - // Create admin user - _ = createTestUser(t, backend, "admin", true) - - // Create regular user - regularUser := createTestUser(t, backend, "regular", false) - - // Admin modifies regular user - updateData := &users.User{ - ID: regularUser.ID, - Username: regularUser.Username, - NonAdminEditable: users.NonAdminEditable{ - DarkMode: true, - OtpEnabled: false, - Locale: "fr", - }, - Permissions: users.Permissions{ - Admin: false, // Admin can modify permissions - }, - } - - // Test with which=all - err := backend.Update(updateData, true, "all") - if err != nil { - t.Errorf("Admin should be able to modify other user with which=all: %v", err) - } - - // Verify changes were applied - updatedUser, err := backend.GetBy(regularUser.ID) - if err != nil { - t.Fatalf("Failed to get updated user: %v", err) - } - - if !updatedUser.DarkMode { - t.Error("DarkMode should have been updated to true") - } - if updatedUser.OtpEnabled { - t.Error("OtpEnabled should have been updated to false") - } - if updatedUser.Locale != "fr" { - t.Errorf("Locale should have been updated to 'fr', got '%s'", updatedUser.Locale) - } - - // Test with specific fields - updateData2 := &users.User{ - ID: regularUser.ID, - Username: regularUser.Username, - NonAdminEditable: users.NonAdminEditable{ - ViewMode: "list", - }, - } - - err = backend.Update(updateData2, true, "ViewMode") - if err != nil { - t.Errorf("Admin should be able to modify specific field: %v", err) - } - - updatedUser2, err := backend.GetBy(regularUser.ID) - if err != nil { - t.Fatalf("Failed to get updated user: %v", err) - } - - if updatedUser2.ViewMode != "list" { - t.Errorf("ViewMode should have been updated to 'list', got '%s'", updatedUser2.ViewMode) - } -} - -func TestUpdate_AdminModifySelf(t *testing.T) { - backend := createTestUsersBackend(t) - - // Create admin user - admin := createTestUser(t, backend, "admin", true) - - // Admin modifies themselves - updateData := &users.User{ - ID: admin.ID, - Username: admin.Username, - NonAdminEditable: users.NonAdminEditable{ - DarkMode: true, - OtpEnabled: false, - Locale: "de", - }, - } - - // Test with which=all - err := backend.Update(updateData, true, "all") - if err != nil { - t.Errorf("Admin should be able to modify themselves with which=all: %v", err) - } - - // Verify changes were applied - updatedUser, err := backend.GetBy(admin.ID) - if err != nil { - t.Fatalf("Failed to get updated user: %v", err) - } - - if !updatedUser.DarkMode { - t.Error("DarkMode should have been updated to true") - } - if updatedUser.OtpEnabled { - t.Error("OtpEnabled should have been updated to false") - } - if updatedUser.Locale != "de" { - t.Errorf("Locale should have been updated to 'de', got '%s'", updatedUser.Locale) - } -} - -func TestUpdate_NonAdminModifySelf(t *testing.T) { - backend := createTestUsersBackend(t) - - // Create regular user - regularUser := createTestUser(t, backend, "regular", false) - - // Non-admin modifies themselves - updateData := &users.User{ - ID: regularUser.ID, - Username: regularUser.Username, - NonAdminEditable: users.NonAdminEditable{ - DarkMode: true, - OtpEnabled: false, // This should be allowed now - Locale: "es", - ViewMode: "grid", - }, - } - - // Test with which=all - err := backend.Update(updateData, false, "all") - if err != nil { - t.Errorf("Non-admin should be able to modify themselves with which=all: %v", err) - } - - // Verify changes were applied - updatedUser, err := backend.GetBy(regularUser.ID) - if err != nil { - t.Fatalf("Failed to get updated user: %v", err) - } - - if !updatedUser.DarkMode { - t.Error("DarkMode should have been updated to true") - } - if updatedUser.OtpEnabled { - t.Error("OtpEnabled should have been updated to false") - } - if updatedUser.Locale != "es" { - t.Errorf("Locale should have been updated to 'es', got '%s'", updatedUser.Locale) - } - if updatedUser.ViewMode != "grid" { - t.Errorf("ViewMode should have been updated to 'grid', got '%s'", updatedUser.ViewMode) - } - - // Test with specific fields - updateData2 := &users.User{ - ID: regularUser.ID, - Username: regularUser.Username, - NonAdminEditable: users.NonAdminEditable{ - SingleClick: true, - }, - } - - err = backend.Update(updateData2, false, "SingleClick") - if err != nil { - t.Errorf("Non-admin should be able to modify specific allowed field: %v", err) - } - - updatedUser2, err := backend.GetBy(regularUser.ID) - if err != nil { - t.Fatalf("Failed to get updated user: %v", err) - } - - if !updatedUser2.SingleClick { - t.Error("SingleClick should have been updated to true") - } -} - -func TestUpdate_NonAdminModifySelfRestrictedFields(t *testing.T) { - backend := createTestUsersBackend(t) - - // Create regular user - regularUser := createTestUser(t, backend, "regular", false) - - // Non-admin tries to modify restricted fields (should be filtered out, not error) - updateData := &users.User{ - ID: regularUser.ID, - Username: regularUser.Username, - NonAdminEditable: users.NonAdminEditable{ - DarkMode: true, // This should be allowed - }, - Permissions: users.Permissions{ - Admin: true, // This should be filtered out - }, - Scopes: []users.SourceScope{ // This should be filtered out - {Name: "test", Scope: "/test"}, - }, - } - - // Test with which=all - should not error, but should filter out restricted fields - err := backend.Update(updateData, false, "all") - if err != nil { - t.Errorf("Non-admin should not error when trying to modify restricted fields (should be filtered): %v", err) - } - - // Verify only allowed fields were updated - updatedUser, err := backend.GetBy(regularUser.ID) - if err != nil { - t.Fatalf("Failed to get updated user: %v", err) - } - - // Allowed field should be updated - if !updatedUser.DarkMode { - t.Error("DarkMode should have been updated to true") - } - - // Restricted fields should NOT be updated - if updatedUser.Permissions.Admin { - t.Error("Permissions.Admin should not have been updated (restricted field)") - } - if len(updatedUser.Scopes) != 0 { - t.Error("Scopes should not have been updated (restricted field)") - } - - // Test with specific restricted fields - should be filtered out - updateData2 := &users.User{ - ID: regularUser.ID, - Username: regularUser.Username, - Permissions: users.Permissions{ - Admin: true, - }, - } - - err = backend.Update(updateData2, false, "Permissions") - if err == nil { - t.Error("Non-admin should get error when trying to modify only restricted fields (all fields filtered out)") - } - if err.Error() != "no fields to update" { - t.Errorf("Expected 'no fields to update' error, got: %v", err) - } - - // Verify restricted field was not updated - updatedUser2, err := backend.GetBy(regularUser.ID) - if err != nil { - t.Fatalf("Failed to get updated user: %v", err) - } - - if updatedUser2.Permissions.Admin { - t.Error("Permissions.Admin should not have been updated (restricted field)") - } -} - -func TestUpdate_NonAdminModifyOtherUser(t *testing.T) { - backend := createTestUsersBackend(t) - - // Create two regular users - _ = createTestUser(t, backend, "user1", false) - user2 := createTestUser(t, backend, "user2", false) - - // Non-admin tries to modify another user (this should be handled at a higher level) - // But if it gets to the backend, it should work the same as modifying self - updateData := &users.User{ - ID: user2.ID, - Username: user2.Username, - NonAdminEditable: users.NonAdminEditable{ - DarkMode: true, - }, - } - - // This should work (filtering restricted fields) but the higher-level auth should prevent this - err := backend.Update(updateData, false, "DarkMode") - if err != nil { - t.Errorf("Backend should handle non-admin modifying other user (filtering restricted fields): %v", err) - } - - // Verify the change was applied - updatedUser, err := backend.GetBy(user2.ID) - if err != nil { - t.Fatalf("Failed to get updated user: %v", err) - } - - if !updatedUser.DarkMode { - t.Error("DarkMode should have been updated to true") - } -} - -func TestUpdate_NonAdminModifyOtherUserOtp(t *testing.T) { - backend := createTestUsersBackend(t) - - // Create two regular users - _ = createTestUser(t, backend, "user1", false) - user2 := createTestUser(t, backend, "user2", false) - - // Non-admin tries to modify another user's OTP - updateData := &users.User{ - ID: user2.ID, - Username: user2.Username, - NonAdminEditable: users.NonAdminEditable{ - OtpEnabled: false, - }, - } - - // This should work (OtpEnabled is now in NonAdminEditable) - err := backend.Update(updateData, false, "OtpEnabled") - if err != nil { - t.Errorf("Non-admin should be able to modify OTP field: %v", err) - } - - // Verify the change was applied - updatedUser, err := backend.GetBy(user2.ID) - if err != nil { - t.Fatalf("Failed to get updated user: %v", err) - } - - if updatedUser.OtpEnabled { - t.Error("OtpEnabled should have been updated to false") - } -} - -func TestUpdate_WhichAllVsSpecific(t *testing.T) { - backend := createTestUsersBackend(t) - - // Create regular user - regularUser := createTestUser(t, backend, "regular", false) - - // Test which=all - updateDataAll := &users.User{ - ID: regularUser.ID, - Username: regularUser.Username, - NonAdminEditable: users.NonAdminEditable{ - DarkMode: true, - OtpEnabled: false, - Locale: "fr", - ViewMode: "list", - }, - } - - err := backend.Update(updateDataAll, false, "all") - if err != nil { - t.Errorf("which=all should work: %v", err) - } - - // Verify changes - updatedUser, err := backend.GetBy(regularUser.ID) - if err != nil { - t.Fatalf("Failed to get updated user: %v", err) - } - - if !updatedUser.DarkMode || updatedUser.OtpEnabled || updatedUser.Locale != "fr" || updatedUser.ViewMode != "list" { - t.Error("which=all should update all allowed fields") - } - - // Reset user - regularUser = createTestUser(t, backend, "regular2", false) - - // Test specific fields - updateDataSpecific := &users.User{ - ID: regularUser.ID, - Username: regularUser.Username, - NonAdminEditable: users.NonAdminEditable{ - DarkMode: true, - Locale: "de", - }, - } - - err = backend.Update(updateDataSpecific, false, "DarkMode", "Locale") - if err != nil { - t.Errorf("specific fields should work: %v", err) - } - - // Verify only specified fields were updated - updatedUser2, err := backend.GetBy(regularUser.ID) - if err != nil { - t.Fatalf("Failed to get updated user: %v", err) - } - - if !updatedUser2.DarkMode { - t.Error("DarkMode should have been updated") - } - if updatedUser2.Locale != "de" { - t.Error("Locale should have been updated") - } - if updatedUser2.ViewMode != "normal" { // Should remain default - t.Error("ViewMode should not have been updated") - } -} - -func TestUpdate_EmptyFieldsAfterFiltering(t *testing.T) { - backend := createTestUsersBackend(t) - - // Create regular user - regularUser := createTestUser(t, backend, "regular", false) - - // Non-admin tries to update only restricted fields - updateData := &users.User{ - ID: regularUser.ID, - Username: regularUser.Username, - Permissions: users.Permissions{ - Admin: true, // This will be filtered out - }, - Scopes: []users.SourceScope{ // This will be filtered out - {Name: "test", Scope: "/test"}, - }, - } - - // This should result in "no fields to update" error - err := backend.Update(updateData, false, "Permissions", "Scopes") - if err == nil { - t.Error("Should get error when all fields are filtered out") - } - - if err.Error() != "no fields to update" { - t.Errorf("Expected 'no fields to update' error, got: %v", err) - } -} - -func TestFilterRestrictedFields(t *testing.T) { - // Test the filterRestrictedFields function directly - testCases := []struct { - name string - fields []string - expected []string - }{ - { - name: "all allowed fields", - fields: []string{"DarkMode", "OtpEnabled", "Locale", "ViewMode", "PinnedItems"}, - expected: []string{"DarkMode", "OtpEnabled", "Locale", "ViewMode", "PinnedItems"}, - }, - { - name: "mixed allowed and restricted", - fields: []string{"DarkMode", "Permissions", "Scopes", "OtpEnabled", "PinnedItems"}, - expected: []string{"DarkMode", "OtpEnabled", "PinnedItems"}, - }, - { - name: "all restricted fields", - fields: []string{"Permissions", "Scopes", "Username", "ID"}, - expected: []string{}, - }, - { - name: "empty fields", - fields: []string{}, - expected: []string{}, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - result := filterRestrictedFields(tc.fields) - - if len(result) != len(tc.expected) { - t.Errorf("Expected %d fields, got %d", len(tc.expected), len(result)) - } - - for i, field := range result { - if field != tc.expected[i] { - t.Errorf("Expected field %s at position %d, got %s", tc.expected[i], i, field) - } - } - }) - } -} diff --git a/backend/database/storage/bolt/utils.go b/backend/database/storage/bolt/utils.go deleted file mode 100644 index 70f88fe435..0000000000 --- a/backend/database/storage/bolt/utils.go +++ /dev/null @@ -1,33 +0,0 @@ -package bolt - -import ( - storm "github.com/asdine/storm/v3" - - "github.com/gtsteffaniak/filebrowser/backend/common/errors" -) - -func get(db *storm.DB, name string, to interface{}) error { - err := db.Get("config", name, to) - if err == storm.ErrNotFound { - return errors.ErrNotExist - } - - return err -} - -func Save(db *storm.DB, name string, from interface{}) error { - return db.Set("config", name, from) -} - -func SaveAccessRules(db *storm.DB, name string, from interface{}) error { - return db.Set("access_rules", name, from) -} - -func GetAccessRules(db *storm.DB, name string, to interface{}) error { - err := db.Get("access_rules", name, to) - if err == storm.ErrNotFound { - return errors.ErrNotExist - } - - return err -} diff --git a/backend/database/storage/storage.go b/backend/database/storage/storage.go deleted file mode 100644 index 589ed40613..0000000000 --- a/backend/database/storage/storage.go +++ /dev/null @@ -1,135 +0,0 @@ -package storage - -import ( - "fmt" - "os" - "path/filepath" - "strings" - - storm "github.com/asdine/storm/v3" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/storage/bolt" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/go-logger/logger" -) - -var userStore *users.Storage - -func InitializeDb(path string) (*bolt.BoltStore, bool, error) { - logger.Debugf("Initializing database: %v", path) - exists, err := dbExists(path) - if err != nil { - panic(err) - } - db, err := storm.Open(path) - if err != nil { - if strings.Contains(err.Error(), "timeout") { - logger.Fatal("the database is locked, please close all other instances of filebrowser before starting.") - } - logger.Fatalf("could not open database: %v", err) - } - store, err := bolt.NewStorage(db) - if err != nil { - return nil, exists, err - } - // Load access rules from DB on startup - // ignoring errors because - _ = store.Access.LoadFromDB() - // Load share cache from DB so shareByHash/shareByPath are populated at startup - store.Share.LoadShareCacheFromDB() - userStore = store.Users - err = bolt.Save(db, "version", 2) - if err != nil { - return nil, exists, err - } - if !exists { - if settings.Env.IsPlaywright || settings.Env.IsDevMode { - settings.Env.IsFirstLoad = false - } else { - settings.Env.IsFirstLoad = true - } - quickSetup(store) - } - - return store, exists, err -} - -func dbExists(path string) (bool, error) { - stat, err := os.Stat(path) - if err == nil { - return stat.Size() != 0, nil - } - - if os.IsNotExist(err) { - d := filepath.Dir(path) - _, err = os.Stat(d) - if os.IsNotExist(err) { - if err = os.MkdirAll(d, fileutils.PermDir); err != nil { - return false, err - } - return false, nil - } - } - - return false, err -} - -func quickSetup(store *bolt.BoltStore) { - settings.Config.Auth.Key = utils.GenerateKey() - err := store.Settings.Save(&settings.Config) - utils.CheckErr("store.Settings.Save", err) - err = store.Settings.SaveServer(&settings.Config.Server) - utils.CheckErr("store.Settings.SaveServer", err) - passwordAuth := settings.Config.Auth.Methods.PasswordAuth.Enabled - noAuth := settings.Config.Auth.Methods.NoAuth - if passwordAuth || noAuth { - user := &users.User{} - settings.ApplyUserDefaults(user) - user.Username = settings.Config.Auth.AdminUsername - if settings.Config.Auth.AdminPassword == "" { - settings.Config.Auth.AdminPassword = "admin" - } - user.Password = settings.Config.Auth.AdminPassword - user.LockPassword = false - download := user.Permissions.Download - user.Permissions = settings.AdminPerms() - user.Permissions.Download = download - user.ShowFirstLogin = settings.Env.IsFirstLoad && user.Permissions.Admin - logger.Debugf("Creating user as admin: %v %v", user.Username, user.Password) - err = store.Users.Save(user, true, true) - utils.CheckErr("store.Users.Save", err) - } -} - -// create new user -func CreateUser(userInfo users.User, permissions users.Permissions) error { - newUser := &userInfo - newUser.ShowFirstLogin = settings.Env.IsFirstLoad && newUser.Permissions.Admin - if userInfo.LoginMethod == "password" { - if userInfo.Password == "" { - return fmt.Errorf("password is required to create a password login user") - } - } else { - hashpass, err := utils.HashPwd(userInfo.Username) - if err != nil { - return err - } - userInfo.Password = hashpass - } - // must have username - if userInfo.Username == "" { - return fmt.Errorf("username is required to create a user") - } - settings.ApplyUserDefaults(newUser) - newUser.Permissions = permissions - newUser.Version = users.CurrentUserMigrationVersion - logger.Debugf("Creating user: %v %v", userInfo.Username, userInfo.Scopes) - // create new home directories - err := userStore.Save(newUser, true, false) - if err != nil { - return err - } - return nil -} diff --git a/backend/database/users/conversions.go b/backend/database/users/conversions.go deleted file mode 100644 index 39beac093c..0000000000 --- a/backend/database/users/conversions.go +++ /dev/null @@ -1,131 +0,0 @@ -package users - -import ( - "fmt" - "strings" -) - -// ResolveSourceKey maps a string that is either: -// - the configured source filesystem path (canonical Bolt / in-memory form for -// SourceScope.Name and source-type SidebarLink.SourceName), or -// - the source display name (JSON form from clients). -// -// Path is checked first so absolute paths are unambiguous. Used on write paths -// (normalize to Path) and read paths (normalize API to display Name). -func ResolveSourceKey(key string) (SourceInfo, bool) { - if sourceConfig == nil || key == "" { - return SourceInfo{}, false - } - if info, ok := sourceConfig.GetSourceByPath(key); ok { - return info, true - } - return sourceConfig.GetSourceByName(key) -} - -// GetSourceNames returns all source names the user has access to (assumes backend-style scopes) -func (u *User) GetSourceNames() []string { - if sourceConfig == nil { - return []string{} - } - - sources := []string{} - allSources := sourceConfig.GetAllSources() - - // Preserves order of sources - for _, source := range allSources { - _, err := u.GetScopeForSourcePath(source.Path) - if err == nil { - sources = append(sources, source.Name) - } - } - return sources -} - -// GetBackendScopes normalizes scopes for Bolt: SourceScope.Name is always the source filesystem path. -// Incoming rows (API) may use display name or path; legacy rows may use either. -func (u *User) GetBackendScopes() ([]SourceScope, error) { - if len(u.Scopes) == 0 { - return []SourceScope{}, nil - } - if sourceConfig == nil { - return nil, fmt.Errorf("source config not initialized") - } - - newScopes := []SourceScope{} - for _, scope := range u.Scopes { - source, ok := ResolveSourceKey(scope.Name) - if !ok { - continue - } - if scope.Scope == "" { - scope.Scope = source.DefaultUserScope - } - scope.Scope = normalizeScope(scope.Scope) - newScopes = append(newScopes, SourceScope{ - Name: source.Path, - Scope: scope.Scope, - }) - } - return newScopes, nil -} - -// GetFrontendScopes converts scopes for JSON clients: SourceScope.Name is always the source display name. -// Assumes Bolt stores paths (GetBackendScopes); unknown keys are omitted. -func (u *User) GetFrontendScopes() []SourceScope { - if sourceConfig == nil { - return []SourceScope{} - } - - newScopes := []SourceScope{} - for _, scope := range u.Scopes { - source, ok := ResolveSourceKey(scope.Name) - if !ok { - continue - } - newScopes = append(newScopes, SourceScope{ - Name: source.Name, - Scope: scope.Scope, - }) - } - return newScopes -} - -// GetBackendSidebarLinks normalizes source links for Bolt: SourceName is the filesystem path. -func (u *User) GetBackendSidebarLinks() ([]SidebarLink, error) { - if sourceConfig == nil { - return nil, fmt.Errorf("source config not initialized") - } - - newLinks := []SidebarLink{} - for _, link := range u.SidebarLinks { - if strings.HasPrefix(link.Category, "source") { - if link.SourceName == "" { - return nil, fmt.Errorf("source link missing sourceName (link name: %v)", link.Name) - } - // Validate source exists - sourceInfo, ok := sourceConfig.GetSourceByName(link.SourceName) - sourceInfo2, ok2 := sourceConfig.GetSourceByPath(link.SourceName) - if !ok && !ok2 { - return nil, fmt.Errorf("source not found: %v (link name: %v)", link.SourceName, link.Name) - } - if ok { - link.SourceName = sourceInfo.Path - } else { - link.SourceName = sourceInfo2.Path - } - } - newLinks = append(newLinks, link) - } - return newLinks, nil -} - -// normalizeScope ensures scope starts with / and doesn't end with / (except for root) -func normalizeScope(scope string) string { - if !strings.HasPrefix(scope, "/") { - scope = "/" + scope - } - if scope != "/" && strings.HasSuffix(scope, "/") { - scope = strings.TrimSuffix(scope, "/") - } - return scope -} diff --git a/backend/database/users/storage_test.go b/backend/database/users/storage_test.go deleted file mode 100644 index 65d13de8db..0000000000 --- a/backend/database/users/storage_test.go +++ /dev/null @@ -1,4 +0,0 @@ -package users - -// Interface is implemented by storage -var _ Store = &Storage{} diff --git a/backend/ffmpeg/conditions.go b/backend/ffmpeg/conditions.go deleted file mode 100644 index 1f8b4c6c0d..0000000000 --- a/backend/ffmpeg/conditions.go +++ /dev/null @@ -1,29 +0,0 @@ -package ffmpeg - -import "github.com/gtsteffaniak/filebrowser/backend/common/settings" - -func CanConvertImage(ext string) bool { - if !MediaEnabled() { - return false - } - val := settings.Config.Integrations.Media.Convert.ImagePreview[settings.ImagePreviewType(ext)] - if val == nil { - return false // Extension not in the configured list - } - return *val -} - -func CanConvertVideo(ext string) bool { - if !MediaEnabled() { - return false - } - val := settings.Config.Integrations.Media.Convert.VideoPreview[settings.VideoPreviewType(ext)] - if val == nil { - return false // Extension not in the configured list - } - return *val -} - -func MediaEnabled() bool { - return settings.Env.FFmpegPath != "" && settings.Env.FFprobePath != "" -} diff --git a/backend/ffmpeg/image.go b/backend/ffmpeg/image.go deleted file mode 100644 index ed102dd945..0000000000 --- a/backend/ffmpeg/image.go +++ /dev/null @@ -1,392 +0,0 @@ -package ffmpeg - -import ( - "bytes" - "context" - "fmt" - "os" - "os/exec" - "path/filepath" - "strconv" - "strings" - - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" -) - -// GetImageOrientation extracts the EXIF orientation from an image file using exiftool -func (s *FFmpegService) GetImageOrientation(imagePath string) (string, error) { - exiftoolPath := settings.Config.Integrations.Media.ExiftoolPath - if exiftoolPath == "" { - return "Horizontal (normal)", nil - } - cmd := exec.Command(exiftoolPath, "-Orientation", "-s3", imagePath) - var out bytes.Buffer - var errOut bytes.Buffer - cmd.Stdout = &out - cmd.Stderr = &errOut - - if err := cmd.Run(); err != nil { - return "Horizontal (normal)", nil // Default to normal orientation - } - - orientation := strings.TrimSpace(out.String()) - if orientation == "" { - orientation = "Horizontal (normal)" // Default if no orientation found - } - return orientation, nil -} - -// GetOrientationFilter converts EXIF orientation to FFmpeg filter -func (s *FFmpegService) GetOrientationFilter(orientation string) string { - switch orientation { - // Text-based EXIF orientation values (from exiftool) - case "Rotate 90 CW", "Right-top": - return ",transpose=1" // 90° clockwise - case "Rotate 180", "Bottom-right": - return ",transpose=1,transpose=1" // 180° (two 90° rotations) - case "Rotate 270 CW", "Left-bottom": - return ",transpose=2" // 90° counter-clockwise - case "Mirror horizontal", "Top-right": - return ",hflip" // Horizontal flip - case "Mirror vertical", "Bottom-left": - return ",vflip" // Vertical flip (upside down) - case "Mirror horizontal and rotate 270 CW", "Right-bottom": - return ",transpose=0" // 90° counter-clockwise + horizontal flip - case "Mirror horizontal and rotate 90 CW", "Left-top": - return ",transpose=3" // 90° clockwise + horizontal flip - case "Horizontal (normal)", "Top-left": - return "" // No rotation needed - - // Numeric EXIF orientation values (standard EXIF specification) - case "1": - return "" // Top-left (normal) - case "2": - return ",hflip" // Top-right (flip horizontal) - case "3": - return ",transpose=1,transpose=1" // Bottom-right (rotate 180) - case "4": - return ",vflip" // Bottom-left (flip vertical) - case "5": - return ",transpose=3" // Left-top (transpose: 90° CW + horizontal flip) - case "6": - return ",transpose=1" // Right-top (rotate 90 CW) - case "7": - return ",transpose=0" // Right-bottom (transverse: 90° CCW + horizontal flip) - case "8": - return ",transpose=2" // Left-bottom (rotate 270 CW / 90° CCW) - - default: - return "" // Default to no rotation for unknown orientations - } -} - -// GetImageDimensions extracts the dimensions of an image file using ffprobe -func (s *FFmpegService) GetImageDimensions(imagePath string) (width, height int, err error) { - - // Get HEIC dimensions (fallback to individual stream dimensions for nowe re - probeCmd := exec.Command( - s.ffprobePath, - "-v", "error", - "-select_streams", "v:0", - "-show_entries", "stream=width,height", - "-of", "csv=p=0:s=x", - imagePath, - ) - - var probeOut bytes.Buffer - var probeErr bytes.Buffer - probeCmd.Stdout = &probeOut - probeCmd.Stderr = &probeErr - - if err = probeCmd.Run(); err != nil { - return 0, 0, fmt.Errorf("ffprobe command failed on image file '%s': %w", imagePath, err) - } - - dimensions := strings.TrimSpace(probeOut.String()) - - // Handle cases where ffprobe returns multiple lines or extra characters - // Take the first line and clean it up - lines := strings.Split(dimensions, "\n") - cleanDimensions := strings.TrimSpace(lines[0]) - - // Remove any trailing 'x' characters that might appear - cleanDimensions = strings.TrimSuffix(cleanDimensions, "x") - - parts := strings.Split(cleanDimensions, "x") - if len(parts) != 2 { - return 0, 0, fmt.Errorf("invalid dimensions format: %s", cleanDimensions) - } - - width, err = strconv.Atoi(parts[0]) - if err != nil { - return 0, 0, fmt.Errorf("invalid width: %w", err) - } - - height, err = strconv.Atoi(parts[1]) - if err != nil { - return 0, 0, fmt.Errorf("invalid height: %w", err) - } - - return width, height, nil -} - -// ConvertHEICToJPEGDirect converts a HEIC file to JPEG using direct FFmpeg conversion (fast method) -func (s *FFmpegService) ConvertHEICToJPEGDirect(ctx context.Context, heicPath string, targetWidth, targetHeight int, quality string) ([]byte, error) { - // Check if context is cancelled before starting - if ctx.Err() != nil { - return nil, ctx.Err() - } - - // Get EXIF orientation and create appropriate filter - orientation, err := s.GetImageOrientation(heicPath) - if err != nil { - orientation = "Horizontal (normal)" - } - orientationFilter := s.GetOrientationFilter(orientation) - - // Create temporary output file - outputDir := s.cacheDir - err = os.MkdirAll(outputDir, fileutils.PermDir) - if err != nil { - return nil, fmt.Errorf("failed to create cache directory: %w", err) - } - - outputFile := filepath.Join(outputDir, fmt.Sprintf("heic_direct_%d.jpg", os.Getpid())) - defer os.Remove(outputFile) - - // Build FFmpeg command for direct conversion - args := []string{"-i", heicPath} - - // Build video filter chain with scaling and orientation - var filterChain string - if targetWidth > 0 && targetHeight > 0 { - filterChain = fmt.Sprintf("scale=%d:%d:force_original_aspect_ratio=decrease%s", targetWidth, targetHeight, orientationFilter) - } else { - // For original size, only apply orientation if needed - if orientationFilter != "" { - filterChain = orientationFilter[1:] // Remove leading comma - } - } - - // Add video filter if we have one - if filterChain != "" { - args = append(args, "-vf", filterChain) - } - - // Add quality and output settings - args = append(args, "-q:v", quality, "-pix_fmt", "yuvj420p", "-y", outputFile) - - cmd := exec.CommandContext(ctx, s.ffmpegPath, args...) - var cmdOut bytes.Buffer - var cmdErr bytes.Buffer - cmd.Stdout = &cmdOut - cmd.Stderr = &cmdErr - - if err = cmd.Run(); err != nil { - if ctx.Err() != nil { - return nil, ctx.Err() - } - return nil, fmt.Errorf("direct HEIC conversion failed: %w", err) - } - - // Read the converted file - jpegBytes, err := os.ReadFile(outputFile) - if err != nil { - return nil, fmt.Errorf("failed to read converted JPEG: %w", err) - } - - return jpegBytes, nil -} - -// ConvertHEICToJPEG converts a HEIC file to JPEG with specified dimensions and quality using proper tile extraction -func (s *FFmpegService) ConvertHEICToJPEG(ctx context.Context, heicPath string, targetWidth, targetHeight int, quality string) ([]byte, error) { - // Check if context is cancelled before starting - if ctx.Err() != nil { - return nil, ctx.Err() - } - // Create temporary directory for tile processing - tempDir, err := os.MkdirTemp(s.cacheDir, "heic_convert") - if err != nil { - return nil, fmt.Errorf("failed to create temp directory: %w", err) - } - - defer os.RemoveAll(tempDir) - - // Step 1: Get grid info using trace output - - // Use ffprobe with trace level to get grid information (with time limit for speed) - gridCmd := exec.CommandContext(ctx, s.ffmpegPath, "-loglevel", "trace", "-i", heicPath, "-f", "null", "-", "-t", "0.1") - var gridOut bytes.Buffer - var gridErr bytes.Buffer - gridCmd.Stdout = &gridOut - gridCmd.Stderr = &gridErr - _ = gridCmd.Run() // Don't check error, we're just extracting info - - traceOutput := gridErr.String() - - // Parse grid dimensions from trace output - var gridCols, gridRows = 8, 6 // Default fallback - var val int - - // Look for grid_row and grid_col in trace output - lines := strings.Split(traceOutput, "\n") - for _, line := range lines { - if strings.Contains(line, "grid_row") { - // Try to extract grid_row value - if parts := strings.Split(line, "grid_row"); len(parts) > 1 { - if matches := strings.Fields(parts[1]); len(matches) > 0 { - if val, err = strconv.Atoi(strings.Trim(matches[0], " :=")); err == nil { - gridRows = val + 1 // HEIC grid_row is 0-based - } - } - } - } - if strings.Contains(line, "grid_col") { - // Try to extract grid_col value - if parts := strings.Split(line, "grid_col"); len(parts) > 1 { - if matches := strings.Fields(parts[1]); len(matches) > 0 { - if val, err = strconv.Atoi(strings.Trim(matches[0], " :=")); err == nil { - gridCols = val + 1 // HEIC grid_col is 0-based - } - } - } - } - } - - // Get EXIF orientation and create appropriate filter - orientation, err := s.GetImageOrientation(heicPath) - if err != nil { - orientation = "Horizontal (normal)" - } - orientationFilter := s.GetOrientationFilter(orientation) - - // Step 2: Extract tile streams (skip stream 0 which is compatibility image) - - // Check context again before extraction - if ctx.Err() != nil { - return nil, ctx.Err() - } - - // Extract using JPEG for faster I/O (PNG was unnecessarily slow and large) - // Skip the first output (stream 0) since it's the compatibility image - tilesPattern := filepath.Join(tempDir, "output_%d.jpg") - - extractCmd := exec.CommandContext(ctx, - s.ffmpegPath, - "-i", heicPath, - "-map", "0", // Map all streams - "-q:v", "3", // Medium quality for intermediate tiles - "-y", - tilesPattern, - ) - - var extractOut bytes.Buffer - var extractErr bytes.Buffer - extractCmd.Stdout = &extractOut - extractCmd.Stderr = &extractErr - - if err = extractCmd.Run(); err != nil { - if ctx.Err() != nil { - return nil, ctx.Err() - } - return nil, fmt.Errorf("tile extraction failed: %w", err) - } - - // Step 3: Filter tiles (skip output_0.png which is compatibility image) - - files, err := filepath.Glob(filepath.Join(tempDir, "output_*.jpg")) - if err != nil || len(files) == 0 { - return nil, fmt.Errorf("no tiles extracted, found %d files", len(files)) - } - - // Create filtered tiles, skipping output_0.jpg (compatibility image) - // and rename them to sequential tile_001.jpg, tile_002.jpg, etc. - tileIndex := 1 - expectedTiles := gridCols * gridRows - - for i := 1; i <= len(files); i++ { // Start from 1 to skip output_0.jpg - sourceFile := filepath.Join(tempDir, fmt.Sprintf("output_%d.jpg", i)) - var info os.FileInfo - if info, err = os.Stat(sourceFile); err == nil && info.Size() > 500 { - // This is a valid tile, rename it to sequential format - targetFile := filepath.Join(tempDir, fmt.Sprintf("tile_%03d.jpg", tileIndex)) - if err = os.Rename(sourceFile, targetFile); err != nil { - continue - } - tileIndex++ - - // Stop if we have enough tiles - if tileIndex > expectedTiles { - break - } - } - } - - actualTiles := tileIndex - 1 - - // Check context before merge - if ctx.Err() != nil { - return nil, ctx.Err() - } - - // Step 4: Merge tiles back into final image with proper quality and rotation - outputFile := filepath.Join(tempDir, "final_output.jpg") - - // Build the video filter chain - inputPattern := filepath.Join(tempDir, "tile_%03d.jpg") - - // Create filter chain: tile assembly + proper scaling - var filterChain string - - // For original size (targetWidth=0, targetHeight=0), don't scale - if targetWidth == 0 && targetHeight == 0 { - // This is original size - no scaling, maximum quality - // Use padding=0:margin=0 to eliminate black borders between tiles - filterChain = fmt.Sprintf("tile=%dx%d:nb_frames=%d:padding=0:margin=0%s", - gridCols, gridRows, actualTiles, orientationFilter) - } else { - // This is a resize request - apply scaling with proper aspect handling - filterChain = fmt.Sprintf("tile=%dx%d:nb_frames=%d:padding=0:margin=0%s,scale=%d:%d:force_original_aspect_ratio=decrease:eval=frame", - gridCols, gridRows, actualTiles, orientationFilter, targetWidth, targetHeight) - } - - mergeCmd := exec.CommandContext(ctx, - s.ffmpegPath, - "-i", inputPattern, - "-vf", filterChain, - "-frames:v", "1", - "-q:v", quality, // Use the quality setting passed in - "-pix_fmt", "yuvj420p", // Use full-range YUV for better JPEG compatibility - "-y", - outputFile, - ) - - var mergeOut bytes.Buffer - var mergeErr bytes.Buffer - mergeCmd.Stdout = &mergeOut - mergeCmd.Stderr = &mergeErr - - if err = mergeCmd.Run(); err != nil { - if ctx.Err() != nil { - return nil, ctx.Err() - } - return nil, fmt.Errorf("tile merge failed: %w", err) - } - - // Step 5: Read final output - jpegBytes, err := os.ReadFile(outputFile) - if err != nil { - return nil, fmt.Errorf("failed to read merged JPEG: %w", err) - } - - return jpegBytes, nil -} - -// ConvertImageToJPEG converts any image format (including problematic JPEGs) to standard JPEG using FFmpeg -// This handles extended JPEG formats that Go's image/jpeg decoder doesn't support (e.g., SOF1/C1 marker) -// and can be used as a fallback for images that fail to decode with Go's standard library. -func (s *FFmpegService) ConvertImageToJPEG(ctx context.Context, imagePath string, targetWidth, targetHeight int, quality string) ([]byte, error) { - // Use the direct conversion method which works for all image formats - return s.ConvertHEICToJPEGDirect(ctx, imagePath, targetWidth, targetHeight, quality) -} diff --git a/backend/ffmpeg/metadata.go b/backend/ffmpeg/metadata.go deleted file mode 100644 index d28df6569f..0000000000 --- a/backend/ffmpeg/metadata.go +++ /dev/null @@ -1,68 +0,0 @@ -package ffmpeg - -import ( - "context" - "fmt" - "os" - "os/exec" - "strconv" - "strings" -) - -// GetMediaDuration extracts the duration of a media file (audio or video) using ffprobe -// This method respects the concurrency limits, uses caching, and gracefully handles errors -// Cache key is based on file path + mod time for automatic cache invalidation on file changes -func (s *FFmpegService) GetMediaDuration(ctx context.Context, mediaPath string) (float64, error) { - // Get file info for cache key (path + mod time) - fileInfo, err := os.Stat(mediaPath) - if err != nil { - return 0, fmt.Errorf("failed to stat file: %w", err) - } - // Create cache key from path and modification time - cacheKey := fmt.Sprintf("%s:%d", mediaPath, fileInfo.ModTime().Unix()) - // Check cache first - if duration, found := MetadataCache.Get(cacheKey); found { - return duration, nil - } - // Acquire semaphore slot for concurrency control - if err = s.Acquire(ctx); err != nil { - return 0, err - } - defer s.Release() - - // Check if context is cancelled before starting - if ctx.Err() != nil { - return 0, ctx.Err() - } - - cmd := exec.CommandContext(ctx, - s.ffprobePath, - "-v", "error", - "-show_entries", "format=duration", - "-of", "default=noprint_wrappers=1:nokey=1", - mediaPath, - ) - - output, err := cmd.Output() - if err != nil { - MetadataCache.Set(cacheKey, 0) - return 0, fmt.Errorf("ffprobe failed: %w", err) - } - - durationStr := strings.TrimSpace(string(output)) - if durationStr == "" || durationStr == "N/A" { - MetadataCache.Set(cacheKey, 0) - return 0, fmt.Errorf("could not determine media duration") - } - - duration, err := strconv.ParseFloat(durationStr, 64) - if err != nil { - MetadataCache.Set(cacheKey, 0) - return 0, fmt.Errorf("invalid duration: %v", err) - } - - // Cache successful result - MetadataCache.Set(cacheKey, duration) - - return duration, nil -} diff --git a/backend/ffmpeg/service.go b/backend/ffmpeg/service.go deleted file mode 100644 index 3a29488566..0000000000 --- a/backend/ffmpeg/service.go +++ /dev/null @@ -1,104 +0,0 @@ -package ffmpeg - -import ( - "context" - "os/exec" - "path/filepath" - "runtime" - - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/go-logger/logger" -) - -// VideoService handles video preview operations with ffmpeg -type FFmpegService struct { - ffmpegPath string - ffprobePath string - debug bool - semaphore chan struct{} - cacheDir string - maxConcurrent int // For logging purposes -} - -// NewVideoService creates a new video service instance -func NewFFmpegService(maxConcurrent int, debug bool, cacheDir string) *FFmpegService { - if settings.Env.FFmpegPath == "" || settings.Env.FFprobePath == "" { - return nil - } - return &FFmpegService{ - ffmpegPath: settings.Env.FFmpegPath, - ffprobePath: settings.Env.FFprobePath, - debug: debug, - semaphore: make(chan struct{}, maxConcurrent), - maxConcurrent: maxConcurrent, - cacheDir: cacheDir, - } -} - -func (s *FFmpegService) Acquire(ctx context.Context) error { - select { - case s.semaphore <- struct{}{}: - return nil - case <-ctx.Done(): - return ctx.Err() - } -} - -func (s *FFmpegService) Release() { - <-s.semaphore -} - -// CheckValidFFmpeg checks for a valid ffmpeg executable. -// If a path is provided, it looks there. Otherwise, it searches the system's PATH. -func CheckValidFFmpeg(path string) (string, error) { - return checkExecutable(path, "ffmpeg") -} - -// CheckValidFFprobe checks for a valid ffprobe executable. -// If a path is provided, it looks there. Otherwise, it searches the system's PATH. -func CheckValidFFprobe(path string) (string, error) { - return checkExecutable(path, "ffprobe") -} - -// checkExecutable is an internal helper function to find and validate an executable. -// It checks a specific path if provided, otherwise falls back to searching the system PATH. -func checkExecutable(providedPath, execName string) (string, error) { - // Add .exe extension for Windows systems - if runtime.GOOS == "windows" { - execName += ".exe" - } - - var finalPath string - var err error - - if providedPath != "" { - // A path was provided, so we'll use it. - finalPath = filepath.Join(providedPath, execName) - } else { - // No path was provided, so search the system's PATH for the executable. - finalPath, err = exec.LookPath(execName) - if err != nil { - // The executable was not found in the system's PATH. - return "", err - } - } - - // Verify the executable is valid by running the "-version" command. - cmd := exec.Command(finalPath, "-version") - err = cmd.Run() - - return finalPath, err -} - -func SetFFmpegPaths() { - ffmpegMainPath, err := CheckValidFFmpeg(settings.Env.FFmpegPath) - if err != nil && settings.Env.FFmpegPath != "" { - logger.Warningf("the configured ffmpeg path does not contain a valid ffmpeg binary %s, err: %v", settings.Env.FFmpegPath, err) - } - ffprobePath, errprobe := CheckValidFFprobe(settings.Env.FFprobePath) - if errprobe != nil && settings.Env.FFprobePath != "" { - logger.Warningf("the configured ffmpeg path is not a valid ffprobe binary %s, err: %v", settings.Env.FFprobePath, err) - } - settings.Env.FFmpegPath = ffmpegMainPath - settings.Env.FFprobePath = ffprobePath -} diff --git a/backend/ffmpeg/subtitles.go b/backend/ffmpeg/subtitles.go deleted file mode 100644 index bf9e2b474f..0000000000 --- a/backend/ffmpeg/subtitles.go +++ /dev/null @@ -1,186 +0,0 @@ -package ffmpeg - -import ( - "encoding/json" - "fmt" - "os" - "os/exec" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/go-logger/logger" -) - -// FFProbeOutput represents the JSON output from ffprobe -type FFProbeOutput struct { - Streams []struct { - Index int `json:"index"` - CodecType string `json:"codec_type"` - CodecName string `json:"codec_name"` - Tags map[string]string `json:"tags,omitempty"` - Disposition map[string]int `json:"disposition,omitempty"` - } `json:"streams"` -} - -// DetectAllSubtitles finds both embedded and external subtitle tracks -func DetectAllSubtitles(videoPath string, parentDir string, modtime time.Time) []utils.SubtitleTrack { - key := "all_subtitles:" + videoPath + ":" + modtime.Format(time.RFC3339) - - // Check cache first - if cached, ok := MediaCache.Get(key); ok { - return cached - } - - var allSubtitles []utils.SubtitleTrack - - // First, get embedded subtitles - embeddedSubs := detectEmbeddedSubtitles(videoPath) - allSubtitles = append(allSubtitles, embeddedSubs...) - - // Then, get external subtitle files - externalSubs := detectExternalSubtitles(videoPath, parentDir) - allSubtitles = append(allSubtitles, externalSubs...) - - // Cache the complete list - MediaCache.Set(key, allSubtitles) - - return allSubtitles -} - -// DetectEmbeddedSubtitles detects embedded subtitle streams using ffprobe. -// This is the public API that can be called from other packages. -// Returns empty array if ffprobe is not available or fails. -func DetectEmbeddedSubtitles(videoPath string, modtime time.Time) []utils.SubtitleTrack { - // Check cache first - key := "embedded_subtitles:" + videoPath + ":" + modtime.Format(time.RFC3339) - if cached, ok := MediaCache.Get(key); ok { - return cached - } - // Detect embedded subtitles - subtitles := detectEmbeddedSubtitles(videoPath) - // Cache the results - MediaCache.Set(key, subtitles) - return subtitles -} - -// detectEmbeddedSubtitles uses ffprobe to find embedded subtitle tracks -// Always runs ffprobe - results are cached for performance -func detectEmbeddedSubtitles(realPath string) []utils.SubtitleTrack { - cmd := exec.Command("ffprobe", - "-v", "quiet", - "-print_format", "json", - "-show_streams", - "-select_streams", "s", - realPath) - - output, err := cmd.Output() - if err != nil { - logger.Debug("ffprobe failed for file: " + realPath + ", error: " + err.Error()) - return nil - } - - var probeOutput FFProbeOutput - if err := json.Unmarshal(output, &probeOutput); err != nil { - logger.Debug("failed to parse ffprobe output for file: " + realPath) - return nil - } - - var subtitles []utils.SubtitleTrack - for _, stream := range probeOutput.Streams { - if stream.CodecType == "subtitle" { - track := utils.SubtitleTrack{ - Index: &stream.Index, - Codec: stream.CodecName, - Embedded: true, // This is an embedded subtitle - } - - // Extract language and title from tags - if stream.Tags != nil { - if lang, ok := stream.Tags["language"]; ok { - track.Language = lang - } - if title, ok := stream.Tags["title"]; ok { - track.Title = title - } - } - - // Generate a descriptive name - if track.Title != "" { - track.Name = track.Title - } else if track.Language != "" { - track.Name = "Embedded (" + track.Language + ")" - } else { - track.Name = "Embedded Subtitle " + strconv.Itoa(stream.Index) - } - - subtitles = append(subtitles, track) - } - } - return subtitles -} - -// detectExternalSubtitles finds external subtitle files in the same directory -func detectExternalSubtitles(videoPath string, parentDir string) []utils.SubtitleTrack { - var subtitles []utils.SubtitleTrack - - // Get the base name of the video (without extension) - videoBaseName := strings.TrimSuffix(filepath.Base(videoPath), filepath.Ext(videoPath)) - - // Common subtitle extensions - subtitleExts := []string{".srt", ".vtt", ".lrc", ".sbv", ".ass", ".ssa", ".sub", ".smi"} - - // Look for subtitle files with matching base name - for _, ext := range subtitleExts { - subtitlePath := filepath.Join(parentDir, videoBaseName+ext) - if _, err := os.Stat(subtitlePath); err == nil { - // File exists - track := utils.SubtitleTrack{ - Name: filepath.Base(subtitlePath), - Embedded: false, // This is an external file - } - - // Try to infer language from filename patterns like "video.en.srt" - parts := strings.Split(videoBaseName, ".") - if len(parts) > 1 { - // Check if the last part before extension looks like a language code - lastPart := parts[len(parts)-1] - if len(lastPart) == 2 || len(lastPart) == 3 { - track.Language = lastPart - } - } - - subtitles = append(subtitles, track) - } - } - - return subtitles -} - -// ExtractSubtitleContent extracts subtitle content without service management -func ExtractSubtitleContent(videoPath string, streamIndex int) (string, error) { - cmd := exec.Command("ffmpeg", - "-i", videoPath, - "-map", fmt.Sprintf("0:%d", streamIndex), - "-c:s", "webvtt", - "-f", "webvtt", - "-") // output to stdout - - output, err := cmd.Output() - if err != nil { - return "", fmt.Errorf("subtitle extraction failed: %v", err) - } - - return string(output), nil -} - -// LoadSubtitleFile loads a subtitle file and returns its raw content -func LoadSubtitleFile(subtitlePath string) (string, error) { - content, err := os.ReadFile(subtitlePath) - if err != nil { - return "", err - } - return string(content), nil -} diff --git a/backend/ffmpeg/video.go b/backend/ffmpeg/video.go deleted file mode 100644 index e66587855f..0000000000 --- a/backend/ffmpeg/video.go +++ /dev/null @@ -1,114 +0,0 @@ -package ffmpeg - -import ( - "bytes" - "context" - "fmt" - "io" - "os" - "os/exec" - "strconv" - "strings" - - "github.com/gtsteffaniak/go-logger/logger" -) - -// GenerateVideoPreviewStreaming generates a video preview and streams it directly to a writer -// This is more memory efficient for large previews as it doesn't load the entire file into memory -func (s *FFmpegService) GenerateVideoPreviewStreaming(ctx context.Context, videoPath string, percentageSeek int, writer io.Writer) error { - if err := s.Acquire(ctx); err != nil { - return err - } - defer s.Release() - - // Check if context is cancelled before starting - if ctx.Err() != nil { - return ctx.Err() - } - - // Validate percentage parameter - if percentageSeek < 0 || percentageSeek > 100 { - percentageSeek = 10 // Default to 10% if invalid - } - - // Step 1: Get video duration from the container format - probeCmd := exec.CommandContext(ctx, - s.ffprobePath, - "-v", "error", - "-show_entries", "format=duration", - "-of", "default=noprint_wrappers=1:nokey=1", - videoPath, - ) - - var probeOut bytes.Buffer - probeCmd.Stdout = &probeOut - if s.debug { - probeCmd.Stderr = os.Stderr - } - if err := probeCmd.Run(); err != nil { - if ctx.Err() != nil { - return ctx.Err() - } - // Capture stderr output for better debugging - stderrOutput := "" - if probeCmd.Stderr != nil { - if stderrBuf, ok := probeCmd.Stderr.(*bytes.Buffer); ok { - stderrOutput = stderrBuf.String() - } - } - logger.Errorf("ffprobe command failed on file '%s': %v (stderr: %s)", videoPath, err, stderrOutput) - return fmt.Errorf("ffprobe failed: %w", err) - } - - durationStr := strings.TrimSpace(probeOut.String()) - if durationStr == "" || durationStr == "N/A" { - logger.Errorf("could not determine video duration for file '%v' using duration info '%v'", videoPath, durationStr) - return fmt.Errorf("could not determine video duration") - } - - durationFloat, err := strconv.ParseFloat(durationStr, 64) - if err != nil { - return fmt.Errorf("invalid duration: %v", err) - } - - if durationFloat <= 0 { - return fmt.Errorf("video duration must be positive") - } - - // Step 2: Calculate seek time with higher precision - seekTime := durationFloat * float64(percentageSeek) / 100.0 - seekTimeStr := strconv.FormatFloat(seekTime, 'f', 3, 64) // 3 decimal places precision - - // Step 3: Extract frame and stream directly to writer - cmd := exec.CommandContext(ctx, - s.ffmpegPath, - "-ss", seekTimeStr, // Use precise seek time - "-i", videoPath, - "-frames:v", "1", - "-q:v", "10", // Good quality/size balance - "-f", "image2", // Explicitly specify image format - "-vcodec", "mjpeg", // Use MJPEG codec for better compression - "-", // Output to stdout - ) - - cmd.Stdout = writer - var stderrBuf bytes.Buffer - if s.debug { - cmd.Stderr = os.Stderr - } else { - // Capture stderr for error logging - cmd.Stderr = &stderrBuf - } - err = cmd.Run() - if err != nil { - if ctx.Err() != nil { - return ctx.Err() - } - - stderrOutput := stderrBuf.String() - logger.Errorf("ffmpeg command failed on file '%s' (seek: %s): %v (stderr: %s)", - videoPath, seekTimeStr, err, stderrOutput) - return fmt.Errorf("ffmpeg command failed on file '%v' : %w", videoPath, err) - } - return nil -} diff --git a/backend/go.mod b/backend/go.mod index a76616827c..5031eb5ecc 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -1,13 +1,15 @@ module github.com/gtsteffaniak/filebrowser/backend -go 1.25.0 +go 1.26.0 require ( + github.com/alecthomas/kong v1.16.0 github.com/asdine/storm/v3 v3.2.1 github.com/coreos/go-oidc/v3 v3.20.0 github.com/coreos/go-systemd/v22 v22.7.0 github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8 github.com/dsoprea/go-exif/v3 v3.0.1 + github.com/evanoberholster/imagemeta v1.0.0 github.com/gen2brain/go-fitz v1.28.2 github.com/go-ldap/ldap/v3 v3.4.14 github.com/go-playground/validator/v10 v10.30.3 @@ -15,7 +17,9 @@ require ( github.com/goccy/go-yaml v1.19.2 github.com/golang-jwt/jwt/v4 v4.5.2 github.com/google/go-cmp v0.7.0 + github.com/google/uuid v1.6.0 github.com/gtsteffaniak/go-cache v1.1.0 + github.com/gtsteffaniak/go-ffmpeg v0.5.1 github.com/gtsteffaniak/go-logger v1.1.0 github.com/kovidgoyal/imaging v1.8.23 github.com/mattn/go-sqlite3 v1.14.49 @@ -30,6 +34,7 @@ require ( golang.org/x/net v0.57.0 golang.org/x/oauth2 v0.36.0 golang.org/x/sys v0.47.0 + golang.org/x/term v0.45.0 golang.org/x/time v0.15.0 golang.org/x/tools v0.48.0 gopkg.in/yaml.v3 v3.0.1 @@ -60,8 +65,8 @@ require ( github.com/Masterminds/semver/v3 v3.5.0 // indirect github.com/MirrexOne/unqueryvet v1.5.4 // indirect github.com/OpenPeeDeeP/depguard/v2 v2.2.1 // indirect - github.com/air-verse/air v1.65.3 // indirect - github.com/alecthomas/chroma/v2 v2.24.1 // indirect + github.com/air-verse/air v1.67.4 // indirect + github.com/alecthomas/chroma/v2 v2.27.0 // indirect github.com/alecthomas/go-check-sumtype v0.3.1 // indirect github.com/alexkohler/nakedret/v2 v2.0.6 // indirect github.com/alexkohler/prealloc v1.1.0 // indirect @@ -74,6 +79,7 @@ require ( github.com/beorn7/perks v1.0.1 // indirect github.com/bep/godartsass/v2 v2.5.0 // indirect github.com/bep/golibsass v1.2.0 // indirect + github.com/bits-and-blooms/bitset v1.24.5 // indirect github.com/bkielbasa/cyclop v1.2.3 // indirect github.com/blizzy78/varnamelen v0.8.0 // indirect github.com/bombsimon/wsl/v4 v4.7.0 // indirect @@ -100,9 +106,10 @@ require ( github.com/curioswitch/go-reassign v0.3.0 // indirect github.com/daixiang0/gci v0.13.7 // indirect github.com/dave/dst v0.27.3 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/denis-tingaikin/go-header v0.5.0 // indirect github.com/dlclark/regexp2 v1.12.0 // indirect + github.com/dlclark/regexp2/v2 v2.2.1 // indirect github.com/dsoprea/go-logging v0.0.0-20200710184922-b02d349568dd // indirect github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349 // indirect github.com/dustin/go-humanize v1.0.1 // indirect @@ -145,7 +152,8 @@ require ( github.com/gobwas/glob v0.2.3 // indirect github.com/godoc-lint/godoc-lint v0.11.2 // indirect github.com/gofrs/flock v0.13.0 // indirect - github.com/gohugoio/hugo v0.149.1 // indirect + github.com/gohugoio/hashstructure v0.6.0 // indirect + github.com/gohugoio/hugo v0.164.0 // indirect github.com/golang-jwt/jwt/v5 v5.3.1 // indirect github.com/golang/geo v0.0.0-20260713102120-857a528af641 // indirect github.com/golang/protobuf v1.5.3 // indirect @@ -162,7 +170,6 @@ require ( github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e // indirect github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e // indirect github.com/google/go-tpm v0.9.8 // indirect - github.com/google/uuid v1.6.0 // indirect github.com/gordonklaus/ineffassign v0.2.0 // indirect github.com/gostaticanalysis/analysisutil v0.7.1 // indirect github.com/gostaticanalysis/comment v1.5.0 // indirect @@ -218,9 +225,10 @@ require ( github.com/nishanths/predeclared v0.2.2 // indirect github.com/nunnatsa/ginkgolinter v0.23.0 // indirect github.com/pelletier/go-toml v1.9.5 // indirect - github.com/pelletier/go-toml/v2 v2.3.1 // indirect + github.com/pelletier/go-toml/v2 v2.4.3 // indirect github.com/philhofer/fwd v1.2.0 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_golang v1.12.1 // indirect github.com/prometheus/client_model v0.2.0 // indirect github.com/prometheus/common v0.32.1 // indirect @@ -233,7 +241,7 @@ require ( github.com/raeperd/recvcheck v0.2.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/rivo/uniseg v0.4.7 // indirect - github.com/rogpeppe/go-internal v1.14.1 // indirect + github.com/rogpeppe/go-internal v1.15.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd // indirect github.com/ryancurrah/gomodguard v1.4.1 // indirect @@ -248,7 +256,7 @@ require ( github.com/sivchari/containedctx v1.0.3 // indirect github.com/sonatard/noctx v0.5.1 // indirect github.com/sourcegraph/go-diff v0.8.0 // indirect - github.com/spf13/cast v1.9.2 // indirect + github.com/spf13/cast v1.10.0 // indirect github.com/spf13/cobra v1.10.2 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.10 // indirect @@ -258,7 +266,7 @@ require ( github.com/stretchr/objx v0.5.2 // indirect github.com/subosito/gotenv v1.4.1 // indirect github.com/swaggo/files v1.0.1 // indirect - github.com/tdewolff/parse/v2 v2.8.3 // indirect + github.com/tdewolff/parse/v2 v2.8.12 // indirect github.com/tetafro/godot v1.5.6 // indirect github.com/timakin/bodyclose v0.0.0-20260129054331-73d1f95b84b4 // indirect github.com/timonwong/loggercheck v0.11.0 // indirect @@ -289,7 +297,7 @@ require ( golang.org/x/exp/typeparams v0.0.0-20260209203927-2842357ff358 // indirect golang.org/x/sync v0.22.0 // indirect golang.org/x/text v0.40.0 // indirect - google.golang.org/protobuf v1.36.10 // indirect + google.golang.org/protobuf v1.36.11 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect honnef.co/go/tools v0.7.0 // indirect diff --git a/backend/go.sum b/backend/go.sum index 834213c7cf..eb1a001de3 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -85,14 +85,22 @@ github.com/OpenPeeDeeP/depguard/v2 v2.2.1 h1:vckeWVESWp6Qog7UZSARNqfu/cZqvki8zsu github.com/OpenPeeDeeP/depguard/v2 v2.2.1/go.mod h1:q4DKzC4UcVaAvcfd41CZh0PWpGgzrVxUYBlgKNGquUo= github.com/Sereal/Sereal v0.0.0-20190618215532-0b8ac451a863 h1:BRrxwOZBolJN4gIwvZMJY1tzqBvQgpaZiQRuIDD40jM= github.com/Sereal/Sereal v0.0.0-20190618215532-0b8ac451a863/go.mod h1:D0JMgToj/WdxCgd30Kc1UcA9E+WdZoJqeVOuYW7iTBM= -github.com/air-verse/air v1.65.3 h1:7NUAqofZuSf5vZbVoZpdTr/4LuKkOCj1JTiMrOdUs7A= -github.com/air-verse/air v1.65.3/go.mod h1:OaJZSfZqf7wyjS2oP/CcEVyIt0JmZuPh5x1gdtklmmY= +github.com/air-verse/air v1.67.1 h1:/n3nLDvGrbQbT5iFL4sTOGCjze4BAs+6HkLFwj/XLd8= +github.com/air-verse/air v1.67.1/go.mod h1:OaJZSfZqf7wyjS2oP/CcEVyIt0JmZuPh5x1gdtklmmY= +github.com/air-verse/air v1.67.3 h1:/mfgjG66EkLosKebWjsDtD5tINZcpD2ilRctrA2/aRA= +github.com/air-verse/air v1.67.3/go.mod h1:XumHRkXbIg8CU5FqhQHgQC4oxQW/OQLwUMQAWln8cZs= +github.com/air-verse/air v1.67.4 h1:pkWBQues0094VMgUZ9MboNfS1vyCBEXeU6QxuD6/PwU= +github.com/air-verse/air v1.67.4/go.mod h1:XumHRkXbIg8CU5FqhQHgQC4oxQW/OQLwUMQAWln8cZs= github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= github.com/alecthomas/chroma/v2 v2.24.1 h1:m5ffpfZbIb++k8AqFEKy9uVgY12xIQtBsQlc6DfZJQM= github.com/alecthomas/chroma/v2 v2.24.1/go.mod h1:l+ohZ9xRXIbGe7cIW+YZgOGbvuVLjMps/FYN/CwuabI= +github.com/alecthomas/chroma/v2 v2.27.0 h1:FodwmyOBgJULFYmDqibcp9pvfDLWdtPRh9v/r5BXYZs= +github.com/alecthomas/chroma/v2 v2.27.0/go.mod h1:NjJ3ciIgrqBNeIkWZ4e46nseoLDslxU1LmfCoL+wcY8= github.com/alecthomas/go-check-sumtype v0.3.1 h1:u9aUvbGINJxLVXiFvHUlPEaD7VDULsrxJb4Aq31NLkU= github.com/alecthomas/go-check-sumtype v0.3.1/go.mod h1:A8TSiN3UPRw3laIgWEUOHHLPa6/r9MtoigdlP5h3K/E= +github.com/alecthomas/kong v1.16.0 h1:g92/kUxBcdcTPOM79yE63viJgtcp5dNyrB3/O2cjYT4= +github.com/alecthomas/kong v1.16.0/go.mod h1:wrlbXem1CWqUV5Vbmss5ISYhsVPkBb1Yo7YKJghju2I= github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs= github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= @@ -142,20 +150,28 @@ github.com/bep/golibsass v1.2.0 h1:nyZUkKP/0psr8nT6GR2cnmt99xS93Ji82ZD9AgOK6VI= github.com/bep/golibsass v1.2.0/go.mod h1:DL87K8Un/+pWUS75ggYv41bliGiolxzDKWJAq3eJ1MA= github.com/bep/goportabletext v0.1.0 h1:8dqym2So1cEqVZiBa4ZnMM1R9l/DnC1h4ONg4J5kujw= github.com/bep/goportabletext v0.1.0/go.mod h1:6lzSTsSue75bbcyvVc0zqd1CdApuT+xkZQ6Re5DzZFg= +github.com/bep/goportabletext v0.2.0 h1:CZ9f8jADBWqHwBymQiJJPCTSV/tHSA+PYzlUf86Yze0= github.com/bep/gowebp v0.4.0 h1:QihuVnvIKbRoeBNQkN0JPMM8ClLmD6V2jMftTFwSK3Q= github.com/bep/gowebp v0.4.0/go.mod h1:95gtYkAA8iIn1t3HkAPurRCVGV/6NhgaHJ1urz0iIwc= github.com/bep/helpers v0.6.0 h1:qtqMCK8XPFNM9hp5Ztu9piPjxNNkk8PIyUVjg6v8Bsw= github.com/bep/helpers v0.6.0/go.mod h1:IOZlgx5PM/R/2wgyCatfsgg5qQ6rNZJNDpWGXqDR044= +github.com/bep/helpers v0.12.0 h1:tD6V2DQW0B+FUynF2etR/106S/TO9akm+vA/Hk24GxY= github.com/bep/imagemeta v0.12.0 h1:ARf+igs5B7pf079LrqRnwzQ/wEB8Q9v4NSDRZO1/F5k= github.com/bep/imagemeta v0.12.0/go.mod h1:23AF6O+4fUi9avjiydpKLStUNtJr5hJB4rarG18JpN8= +github.com/bep/imagemeta v0.17.2 h1:fDyXM1eAqCfBeqGLqS6UsN4OfuLM0cdu70KuLCehjOg= github.com/bep/lazycache v0.8.0 h1:lE5frnRjxaOFbkPZ1YL6nijzOPPz6zeXasJq8WpG4L8= github.com/bep/lazycache v0.8.0/go.mod h1:BQ5WZepss7Ko91CGdWz8GQZi/fFnCcyWupv8gyTeKwk= +github.com/bep/lazycache v0.8.1 h1:ko6ASLjkPxyV5DMWoNNZ8B2M0weyjqXX8IZkjBoBtvg= github.com/bep/logg v0.4.0 h1:luAo5mO4ZkhA5M1iDVDqDqnBBnlHjmtZF6VAyTp+nCQ= github.com/bep/logg v0.4.0/go.mod h1:Ccp9yP3wbR1mm++Kpxet91hAZBEQgmWgFgnXX3GkIV0= github.com/bep/overlayfs v0.10.0 h1:wS3eQ6bRsLX+4AAmwGjvoFSAQoeheamxofFiJ2SthSE= github.com/bep/overlayfs v0.10.0/go.mod h1:ouu4nu6fFJaL0sPzNICzxYsBeWwrjiTdFZdK4lI3tro= +github.com/bep/overlayfs v0.11.0 h1:aymHDGC0CHpvn0XvTfgpK6skCp16oMi+tdUF32l6pPs= github.com/bep/tmc v0.5.1 h1:CsQnSC6MsomH64gw0cT5f+EwQDcvZz4AazKunFwTpuI= github.com/bep/tmc v0.5.1/go.mod h1:tGYHN8fS85aJPhDLgXETVKp+PR382OvFi2+q2GkGsq0= +github.com/bep/tmc v0.6.0 h1:5zWy4L+3gS+Kk8czzLC4g7ETaC3wkX9ZtTRdAdL8V4s= +github.com/bits-and-blooms/bitset v1.24.5 h1:654xBVHc23gJMAgOTkPNoCVfiRxuIOAUnAZFtopqJ4w= +github.com/bits-and-blooms/bitset v1.24.5/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= github.com/bkielbasa/cyclop v1.2.3 h1:faIVMIGDIANuGPWH031CZJTi2ymOQBULs9H21HSMa5w= github.com/bkielbasa/cyclop v1.2.3/go.mod h1:kHTwA9Q0uZqOADdupvcFJQtp/ksSnytRMe8ztxG8Fuo= github.com/blizzy78/varnamelen v0.8.0 h1:oqSblyuQvFsW1hbBHh1zfwrKe3kcSj0rnXkKzsQ089M= @@ -229,6 +245,8 @@ github.com/dave/jennifer v1.7.1/go.mod h1:nXbxhEmQfOZhWml3D1cDK5M1FLnMSozpbFN/m3 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/denis-tingaikin/go-header v0.5.0 h1:SRdnP5ZKvcO9KKRP1KJrhFR3RrlGuD+42t4429eC9k8= github.com/denis-tingaikin/go-header v0.5.0/go.mod h1:mMenU5bWrok6Wl2UsZjy+1okegmwQ3UgWl4V1D8gjlY= github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8 h1:OtSeLS5y0Uy01jaKK4mA/WVIYtpzVm63vLVAPzJXigg= @@ -237,6 +255,8 @@ github.com/disintegration/gift v1.2.1 h1:Y005a1X4Z7Uc+0gLpSAsKhWi4qLtsdEcMIbbdvd github.com/disintegration/gift v1.2.1/go.mod h1:Jh2i7f7Q2BM7Ezno3PhfezbR1xpUg9dUg3/RlKGr4HI= github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8= github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dlclark/regexp2/v2 v2.2.1 h1:mf4KkFUj0gJuarK8P+LgiS+Lit7m9N1yAwEfPbee7R0= +github.com/dlclark/regexp2/v2 v2.2.1/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU= github.com/dsoprea/go-exif/v2 v2.0.0-20200321225314-640175a69fe4/go.mod h1:Lm2lMM2zx8p4a34ZemkaUV95AnMl4ZvLbCUbwOvLC2E= github.com/dsoprea/go-exif/v3 v3.0.0-20200717053412-08f1b6708903/go.mod h1:0nsO1ce0mh5czxGeLo4+OCZ/C6Eo6ZlMWsz7rH/Gxv8= github.com/dsoprea/go-exif/v3 v3.0.0-20210625224831-a6301f85c82b/go.mod h1:cg5SNYKHMmzxsr9X6ZeLh/nfBRHHp5PngtEPcujONtk= @@ -264,8 +284,11 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/ettle/strcase v0.2.0 h1:fGNiVF21fHXpX1niBgk0aROov1LagYsOwV/xqKDKR/Q= github.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A= +github.com/evanoberholster/imagemeta v1.0.0 h1:FlSihlsjkWIoS83wmgPOP3CbAxlRpxM8jQGZgLu+MWQ= +github.com/evanoberholster/imagemeta v1.0.0/go.mod h1:2ITZJjD1ygzWIhepvn8coRvpaFcnDNk3E6hx6v7z8DU= github.com/evanw/esbuild v0.25.9 h1:aU7GVC4lxJGC1AyaPwySWjSIaNLAdVEEuq3chD0Khxs= github.com/evanw/esbuild v0.25.9/go.mod h1:D2vIQZqV/vIf/VRHtViaUtViZmG7o+kKmlBfVQuRi48= +github.com/evanw/esbuild v0.28.1 h1:ds+yuRyUaZGx++GR56CrCeuXh8PVhVM4xq8v7PNELFc= github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w= github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE= github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4= @@ -287,6 +310,7 @@ github.com/gen2brain/go-fitz v1.28.2 h1:845G85N5TUgnq5oDqyYrW0JvehAkeo35UkkK2dJt github.com/gen2brain/go-fitz v1.28.2/go.mod h1:pY2hqAjp9Zy7qfPI2gwbJMHBFAdZpVXOLrRxD82l3Bs= github.com/getkin/kin-openapi v0.133.0 h1:pJdmNohVIJ97r4AUFtEXRXwESr8b0bD721u/Tz6k8PQ= github.com/getkin/kin-openapi v0.133.0/go.mod h1:boAciF6cXk5FhPqe/NQeBTeenbjqU4LhWBf09ILVvWE= +github.com/getkin/kin-openapi v0.140.0 h1:JFn675aXRFjyiZKa/BFWploGldQlI0gobp4J5k0EZ2g= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/ghostiam/protogetter v0.3.20 h1:oW7OPFit2FxZOpmMRPP9FffU4uUpfeE/rEdE1f+MzD0= @@ -322,6 +346,7 @@ github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkr github.com/go-openapi/jsonreference v1.0.0/go.mod h1:jtwdyGbJk0Xhe5Y+rwtglQP6Sb1WZST4rT32LWB+sv0= github.com/go-openapi/spec v0.22.9 h1:/vKIFDcGKp0ktZWGbym/tJEWbk6/XOEmAVU0kqKMH+w= github.com/go-openapi/spec v0.22.9/go.mod h1:b/mNUYIOQOyIiUzUzXEE8xzyZqf93KvM9hQGP91yfl0= +github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= github.com/go-openapi/swag/conv v0.28.0 h1:GtqqbyFe7vR5Y7ehxG9W6/OvrSFdf1OLeTGp40TqxH8= github.com/go-openapi/swag/conv v0.28.0/go.mod h1:mbUE+mzctnhxi864m0Q07SpN8OowD9JhxmxuYvZZD/k= @@ -396,16 +421,24 @@ github.com/gofrs/flock v0.13.0/go.mod h1:jxeyy9R1auM5S6JYDBhDt+E2TCo7DkratH4Pgi8 github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gohugoio/go-i18n/v2 v2.1.3-0.20230805085216-e63c13218d0e h1:QArsSubW7eDh8APMXkByjQWvuljwPGAGQpJEFn0F0wY= github.com/gohugoio/go-i18n/v2 v2.1.3-0.20230805085216-e63c13218d0e/go.mod h1:3Ltoo9Banwq0gOtcOwxuHG6omk+AwsQPADyw2vQYOJQ= +github.com/gohugoio/go-i18n/v2 v2.1.3-0.20251018145728-cfcc22d823c6 h1:pxlAea9eRwuAnt/zKbGqlFO2ZszpIe24YpOVLf+N+4I= github.com/gohugoio/hashstructure v0.5.0 h1:G2fjSBU36RdwEJBWJ+919ERvOVqAg9tfcYp47K9swqg= github.com/gohugoio/hashstructure v0.5.0/go.mod h1:Ser0TniXuu/eauYmrwM4o64EBvySxNzITEOLlm4igec= +github.com/gohugoio/hashstructure v0.6.0 h1:7wMB/2CfXoThFYhdWRGv3u3rUM761Cq29CxUW+NltUg= +github.com/gohugoio/hashstructure v0.6.0/go.mod h1:lapVLk9XidheHG1IQ4ZSbyYrXcaILU1ZEP/+vno5rBQ= github.com/gohugoio/httpcache v0.7.0 h1:ukPnn04Rgvx48JIinZvZetBfHaWE7I01JR2Q2RrQ3Vs= github.com/gohugoio/httpcache v0.7.0/go.mod h1:fMlPrdY/vVJhAriLZnrF5QpN3BNAcoBClgAyQd+lGFI= +github.com/gohugoio/httpcache v0.8.0 h1:hNdsmGSELztetYCsPVgjA960zSa4dfEqqF/SficorCU= github.com/gohugoio/hugo v0.149.1 h1:uWOc8Ve4h4e48FyYhBquRoHCJviyxA5yGrFJLT48yio= github.com/gohugoio/hugo v0.149.1/go.mod h1:HS6BP6e8FGxungP4CHC3zeLDvhBLnTJIjHJZWTZjs7o= +github.com/gohugoio/hugo v0.164.0 h1:oDElnVJNvDMpEOeoxBjzW8JTFk7u+gJj2kG74BsfXlM= +github.com/gohugoio/hugo v0.164.0/go.mod h1:QPBCN6Gntmm6YrYJEnTasaZjnMLRkv8YoyCOw7mo9JE= github.com/gohugoio/hugo-goldmark-extensions/extras v0.5.0 h1:dco+7YiOryRoPOMXwwaf+kktZSCtlFtreNdiJbETvYE= github.com/gohugoio/hugo-goldmark-extensions/extras v0.5.0/go.mod h1:CRrxQTKeM3imw+UoS4EHKyrqB7Zp6sAJiqHit+aMGTE= +github.com/gohugoio/hugo-goldmark-extensions/extras v0.7.0 h1:I/n6v7VImJ3aISLnn73JAHXyjcQsMVvbguQPTk9Ehus= github.com/gohugoio/hugo-goldmark-extensions/passthrough v0.3.1 h1:nUzXfRTszLliZuN0JTKeunXTRaiFX6ksaWP0puLLYAY= github.com/gohugoio/hugo-goldmark-extensions/passthrough v0.3.1/go.mod h1:Wy8ThAA8p2/w1DY05vEzq6EIeI2mzDjvHsu7ULBVwog= +github.com/gohugoio/hugo-goldmark-extensions/passthrough v0.5.0 h1:p13Q0DBCrBRpJGtbtlgkYNCs4TnIlZJh8vHgnAiofrI= github.com/gohugoio/locales v0.14.0 h1:Q0gpsZwfv7ATHMbcTNepFd59H7GoykzWJIxi113XGDc= github.com/gohugoio/locales v0.14.0/go.mod h1:ip8cCAv/cnmVLzzXtiTpPwgJ4xhKZranqNqtoIu0b/4= github.com/gohugoio/localescompressed v1.0.1 h1:KTYMi8fCWYLswFyJAeOtuk/EkXR/KPTHHNN9OS+RTxo= @@ -528,6 +561,8 @@ github.com/gostaticanalysis/testutil v0.5.0 h1:Dq4wT1DdTwTGCQQv3rl3IvD5Ld0E6HiY+ github.com/gostaticanalysis/testutil v0.5.0/go.mod h1:OLQSbuM6zw2EvCcXTz1lVq5unyoNft372msDY0nY5Hs= github.com/gtsteffaniak/go-cache v1.1.0 h1:ni/2cJpCxpGmaMZd92iTDIGOy+yUcMcxQuW7bSKhkCE= github.com/gtsteffaniak/go-cache v1.1.0/go.mod h1:rHUZvf4huhMX/bnNK4/oQ3sNAE2fYC2jFpAWZiBPWac= +github.com/gtsteffaniak/go-ffmpeg v0.5.1 h1:gpKXi/0mn0j1Ug3v9x21tqbkT/2EZ6cDB1Ngqe8YfjI= +github.com/gtsteffaniak/go-ffmpeg v0.5.1/go.mod h1:FefhoD+KZzHWqBaUpntcKp6lXtUzdFW00F74axnENUQ= github.com/gtsteffaniak/go-logger v1.1.0 h1:baFds+iibuLLNpNLwygz32bDqdsunI6dGWcdxwMIVKI= github.com/gtsteffaniak/go-logger v1.1.0/go.mod h1:rapapTju4D7bwt6h4JOdZNUXDjnp0WkTBd6TN5yWglI= github.com/hairyhenderson/go-codeowners v0.7.0 h1:s0W4wF8bdsBEjTWzwzSlsatSthWtTAF2xLgo4a4RwAo= @@ -703,14 +738,19 @@ github.com/nunnatsa/ginkgolinter v0.23.0 h1:x3o4DGYOWbBMP/VdNQKgSj+25aJKx2Pe6lHr github.com/nunnatsa/ginkgolinter v0.23.0/go.mod h1:9qN1+0akwXEccwV1CAcCDfcoBlWXHB+ML9884pL4SZ4= github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 h1:G7ERwszslrBzRxj//JalHPu/3yz+De2J+4aLtSRlHiY= github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037/go.mod h1:2bpvgLBZEtENV5scfDFEtB/5+1M4hkQhDQrccEJ/qGw= +github.com/oasdiff/yaml v0.1.0 h1:0bqZjfKc/8S9urj4JuwepX41WX9EoA6ifhU3SV06cXg= github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 h1:bQx3WeLcUWy+RletIKwUIt4x3t8n2SxavmoclizMb8c= github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90/go.mod h1:y5+oSEHCPT/DGrS++Wc/479ERge0zTFxaF8PbGKcg2o= +github.com/oasdiff/yaml3 v0.0.13 h1:06svmvOHOVBqF81+sY2EUScvUI/iS/vl2VIeUUxZQwg= github.com/olekukonko/errors v1.1.0 h1:RNuGIh15QdDenh+hNvKrJkmxxjV4hcS50Db478Ou5sM= github.com/olekukonko/errors v1.1.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y= +github.com/olekukonko/errors v1.2.0 h1:10Zcn4GeV59t/EGqJc8fUjtFT/FuUh5bTMzZ1XwmCRo= github.com/olekukonko/ll v0.0.9 h1:Y+1YqDfVkqMWuEQMclsF9HUR5+a82+dxJuL1HHSRpxI= github.com/olekukonko/ll v0.0.9/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g= +github.com/olekukonko/ll v0.1.6 h1:lGVTHO+Qc4Qm+fce/2h2m5y9LvqaW+DCN7xW9hsU3uA= github.com/olekukonko/tablewriter v1.0.9 h1:XGwRsYLC2bY7bNd93Dk51bcPZksWZmLYuaTHR0FqfL8= github.com/olekukonko/tablewriter v1.0.9/go.mod h1:5c+EBPeSqvXnLLgkm9isDdzR3wjfBkHR9Nhfp3NWrzo= +github.com/olekukonko/tablewriter v1.1.4 h1:ORUMI3dXbMnRlRggJX3+q7OzQFDdvgbN9nVWj1drm6I= github.com/onsi/ginkgo/v2 v2.28.2 h1:DTrMfpqxiNUyQ3Y0zhn1n3cOO2euFgQPYIpkWwxVFps= github.com/onsi/ginkgo/v2 v2.28.2/go.mod h1:CLtbVInNckU3/+gC8LzkGUb9oF+e8W8TdUsxPwvdOgE= github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28= @@ -728,6 +768,8 @@ github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3v github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7olPtrEc= github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY= +github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s= github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw= github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= @@ -738,6 +780,8 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs= github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= @@ -781,6 +825,8 @@ github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUc github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/rogpeppe/go-internal v1.15.0 h1:D0RCU5rMAp+SpgkiNdrjfJ+LX4J1M32V2NeCY7EJ6hc= +github.com/rogpeppe/go-internal v1.15.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -820,6 +866,8 @@ github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE= github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= +github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= +github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= @@ -853,10 +901,14 @@ github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI= github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg= github.com/tdewolff/minify/v2 v2.24.2 h1:vnY3nTulEAbCAAlxTxPPDkzG24rsq31SOzp63yT+7mo= github.com/tdewolff/minify/v2 v2.24.2/go.mod h1:1JrCtoZXaDbqioQZfk3Jdmr0GPJKiU7c1Apmb+7tCeE= +github.com/tdewolff/minify/v2 v2.24.13 h1:xrcF7gKDnUszseEY9WX9mUlZII2v2Go/QAcAwRASw58= github.com/tdewolff/parse/v2 v2.8.3 h1:5VbvtJ83cfb289A1HzRA9sf02iT8YyUwN84ezjkdY1I= github.com/tdewolff/parse/v2 v2.8.3/go.mod h1:Hwlni2tiVNKyzR1o6nUs4FOF07URA+JLBLd6dlIXYqo= +github.com/tdewolff/parse/v2 v2.8.12 h1:5BBjfaCv482v3nltlS0u6wH1xJaxjR6ofDrWttNvROg= +github.com/tdewolff/parse/v2 v2.8.12/go.mod h1:Hwlni2tiVNKyzR1o6nUs4FOF07URA+JLBLd6dlIXYqo= github.com/tdewolff/test v1.0.11 h1:FdLbwQVHxqG16SlkGveC0JVyrJN62COWTRyUFzfbtBE= github.com/tdewolff/test v1.0.11/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8= +github.com/tdewolff/test v1.0.12 h1:7F21DqIajswxuche0geHdrUZRCWE4oko4b7bcmkkrxk= github.com/tenntenn/modver v1.0.1 h1:2klLppGhDgzJrScMpkj9Ujy3rXPUspSjAcev9tSEBgA= github.com/tenntenn/modver v1.0.1/go.mod h1:bePIyQPb7UeioSRkw3Q0XeMhYZSMx9B8ePqg6SAMGH0= github.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3 h1:f+jULpRQGxTSkNYKJ51yaw6ChIqO+Je8UqsTKN/cDag= @@ -865,6 +917,7 @@ github.com/tetafro/godot v1.5.6 h1:IEkrFCwXaYHlOn4mGzGS3F3dkP6m9t0jpwqBFPIkKiA= github.com/tetafro/godot v1.5.6/go.mod h1:eOkMrVQurDui411nBY2FA05EYH01r14LuWY/NrVDVcU= github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I= github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM= +github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU= github.com/timakin/bodyclose v0.0.0-20260129054331-73d1f95b84b4 h1:SiHe5XLTn9sFWJ5pBwJ5FN/4j34q9ZlOAD//kMoMYp0= github.com/timakin/bodyclose v0.0.0-20260129054331-73d1f95b84b4/go.mod h1:sDHLK7rb/59v/ZxZ7KtymgcoxuUMxjXq8gtu9VMOK8M= github.com/timonwong/loggercheck v0.11.0 h1:jdaMpYBl+Uq9mWPXv1r8jc5fC3gyXx4/WGwTnnNKn4M= @@ -911,6 +964,7 @@ github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1 github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.7.13 h1:GPddIs617DnBLFFVJFgpo1aBfe/4xcvMc3SB5t/D0pA= github.com/yuin/goldmark v1.7.13/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= +github.com/yuin/goldmark v1.8.2 h1:kEGpgqJXdgbkhcOgBxkC0X0PmoPG1ZyoZ117rDVp4zE= github.com/yuin/goldmark-emoji v1.0.6 h1:QWfF2FYaXwL74tfGOW5izeiZepUDroDJfWubQI9HTHs= github.com/yuin/goldmark-emoji v1.0.6/go.mod h1:ukxJDKFpdFb5x0a5HqbdlcKtebh086iJpI31LTKmWuA= gitlab.com/bosi/decorder v0.4.2 h1:qbQaV3zgwnBZ4zPMhGLW4KZe7A7NwxEhJx39R3shffo= @@ -1111,6 +1165,8 @@ golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= +golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1262,6 +1318,8 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0 google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/backend/http/auth_ratelimit.go b/backend/http/auth_ratelimit.go deleted file mode 100644 index 92230f601b..0000000000 --- a/backend/http/auth_ratelimit.go +++ /dev/null @@ -1,269 +0,0 @@ -package http - -import ( - "fmt" - "math" - "net/http" - "strconv" - "time" - - "github.com/gtsteffaniak/go-cache/cache" - "golang.org/x/time/rate" -) - -// Built-in auth rate limits (per process). Toggle all off with http.disableRateLimit. -// -// Credential tier (login, OTP verify): dual token buckets (per IP + per username) plus -// failed-login lockout (per IP+username). Tune burst ≤ maxAttempts so rapid floods hit -// HTTP 429 from the bucket before lockout; lockout covers paced attacks that stay under RPM. -const ( - authCredentialRPM = 10 // sustained ~1 attempt / 6s per IP and per username - authCredentialBurst = 8 // rapid burst; 9th immediate attempt gets 429 - authModerateRPM = 30 // signup, logout, OTP generate - authModerateBurst = 10 - authOIDCRPM = 60 // OIDC redirects (browser-driven, higher ceiling) - authOIDCBurst = 20 - authAuthenticatedRPM = 180 // session/token management for logged-in users - authAuthenticatedBurst = 60 - authFailedLoginMaxAttempts = 8 // lockout after N consecutive 401s (same IP + username) - authFailedLoginLockoutMins = 15 - // Evict idle per-key token buckets so unique IPs/usernames cannot grow without bound. - authLimiterEntryTTL = 24 * time.Hour -) - -// In-memory failed-attempt counters and lockout flags (per server process). -var ( - authFailCounts = cache.NewCache[int](time.Minute, 10*time.Minute) - authLockouts = cache.NewCache[bool](time.Minute, 10*time.Minute) -) - -// Per-route-class token buckets (keys: IP or username). Expired entries are dropped by go-cache. -var ( - authRateLimitCredentialByIP = cache.NewCache[*rate.Limiter](authLimiterEntryTTL) - authRateLimitCredentialByUsername = cache.NewCache[*rate.Limiter](authLimiterEntryTTL) - authRateLimitModerateByIP = cache.NewCache[*rate.Limiter](authLimiterEntryTTL) - authRateLimitOIDCByIP = cache.NewCache[*rate.Limiter](authLimiterEntryTTL) - authRateLimitAuthenticatedByUser = cache.NewCache[*rate.Limiter](authLimiterEntryTTL) -) - -const authRateKeySep = "\x1e" - -// AuthRateLimitKind selects which /api/auth rate limit tier applies (see withRateLimit and withRateLimitChain). -type AuthRateLimitKind int - -const ( - // AuthRateLimitCredential: strict per-IP and per-username limits; no failed-login lockout. - AuthRateLimitCredential AuthRateLimitKind = iota - // AuthRateLimitCredentialLockout: same limits as Credential, plus lockout after repeated 401s. - AuthRateLimitCredentialLockout - AuthRateLimitModerate - AuthRateLimitOIDC - // AuthRateLimitAuthenticated: per logged-in username (compose: withUser(withRateLimitChain(AuthRateLimitAuthenticated, h))). - AuthRateLimitAuthenticated -) - -// withRateLimitChain applies a rate limit tier then fn for nesting inside withUser / withOrWithoutUser / withoutUser. -func withRateLimitChain(kind AuthRateLimitKind, fn handleFunc) handleFunc { - switch kind { - case AuthRateLimitCredential: - return withAuthRateLimitCredential(false, fn) - case AuthRateLimitCredentialLockout: - return withAuthRateLimitCredential(true, fn) - case AuthRateLimitModerate: - return withAuthRateLimitModerate(fn) - case AuthRateLimitOIDC: - return withAuthRateLimitOIDC(fn) - case AuthRateLimitAuthenticated: - return withAuthRateLimitAuthenticated(fn) - default: - return fn - } -} - -// withRateLimit registers a rate-limited route (same shape as withTimeout: option first, handler second). -func withRateLimit(kind AuthRateLimitKind, fn handleFunc) http.HandlerFunc { - return wrapHandler(withRateLimitChain(kind, fn)) -} - -func authRateLimitActive() bool { - if config.Http.DisableRateLimit { - return false - } - if config.Auth.Methods.NoAuth { - return false - } - return true -} - -func tokenBucketLimiter(c *cache.KeyCache[*rate.Limiter], key string, requestsPerMinute, burst int) *rate.Limiter { - if requestsPerMinute < 1 { - requestsPerMinute = 1 - } - if burst < 1 { - burst = 1 - } - if lim, ok := c.Get(key); ok && lim != nil { - c.SetWithExp(key, lim, authLimiterEntryTTL) - return lim - } - lim := rate.NewLimiter(rate.Limit(float64(requestsPerMinute))/60.0, burst) - c.SetWithExp(key, lim, authLimiterEntryTTL) - return lim -} - -func retryAfterSeconds(lim *rate.Limiter) int { - res := lim.Reserve() - delay := res.Delay() - res.Cancel() - secs := int(math.Ceil(delay.Seconds())) - if secs < 1 { - secs = 1 - } - return secs -} - -func allowCredential(r *http.Request, loginUsername string) (retryAfter int, ok bool) { - ip := getRemoteIP(r) - limIP := tokenBucketLimiter(authRateLimitCredentialByIP, ip, authCredentialRPM, authCredentialBurst) - if !limIP.Allow() { - return retryAfterSeconds(limIP), false - } - if loginUsername != "" { - limUser := tokenBucketLimiter(authRateLimitCredentialByUsername, loginUsername, authCredentialRPM, authCredentialBurst) - if !limUser.Allow() { - return retryAfterSeconds(limUser), false - } - } - return 0, true -} - -func allowModerate(r *http.Request) (retryAfter int, ok bool) { - ip := getRemoteIP(r) - lim := tokenBucketLimiter(authRateLimitModerateByIP, ip, authModerateRPM, authModerateBurst) - if !lim.Allow() { - return retryAfterSeconds(lim), false - } - return 0, true -} - -func allowOIDC(r *http.Request) (retryAfter int, ok bool) { - ip := getRemoteIP(r) - lim := tokenBucketLimiter(authRateLimitOIDCByIP, ip, authOIDCRPM, authOIDCBurst) - if !lim.Allow() { - return retryAfterSeconds(lim), false - } - return 0, true -} - -func allowAuthenticated(username string) (retryAfter int, ok bool) { - lim := tokenBucketLimiter(authRateLimitAuthenticatedByUser, username, authAuthenticatedRPM, authAuthenticatedBurst) - if !lim.Allow() { - return retryAfterSeconds(lim), false - } - return 0, true -} - -func authFailKey(ip, username string) string { - return "fail" + authRateKeySep + ip + authRateKeySep + username -} - -func authLockKey(ip, username string) string { - return "lock" + authRateKeySep + ip + authRateKeySep + username -} - -func authLockoutRetryAfterSecs() int { - return authFailedLoginLockoutMins * 60 -} - -func isAuthLockout(ip, username string) bool { - locked, ok := authLockouts.Get(authLockKey(ip, username)) - return ok && locked -} - -func clearAuthLockout(ip, username string) { - authLockouts.Delete(authLockKey(ip, username)) - authFailCounts.Delete(authFailKey(ip, username)) -} - -func recordAuthFailure(ip, username string) { - if username == "" { - return - } - window := time.Duration(authFailedLoginLockoutMins) * time.Minute - fk := authFailKey(ip, username) - n := 0 - if v, ok := authFailCounts.Get(fk); ok { - n = v - } - n++ - authFailCounts.SetWithExp(fk, n, window) - if n >= authFailedLoginMaxAttempts { - authLockouts.SetWithExp(authLockKey(ip, username), true, window) - } -} - -// withRateLimitInternal applies token-bucket allow checks: when inactive, calls fn; when denied, 429 + Retry-After. -func withRateLimitInternal(fn handleFunc, allow func(*http.Request, *requestContext) (retryAfter int, ok bool)) handleFunc { - return func(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !authRateLimitActive() { - return fn(w, r, d) - } - if after, ok := allow(r, d); !ok { - w.Header().Set("Retry-After", strconv.Itoa(after)) - return http.StatusTooManyRequests, fmt.Errorf("too many requests") - } - return fn(w, r, d) - } -} - -// withAuthRateLimitCredential enforces the credential tier (and optional per-username limits). -// When trackFailures is true, 401 responses increment failed-attempt state for lockout; success clears it. -func withAuthRateLimitCredential(trackFailures bool, fn handleFunc) handleFunc { - return func(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !authRateLimitActive() { - return fn(w, r, d) - } - username := r.URL.Query().Get("username") - if isAuthLockout(getRemoteIP(r), username) { - w.Header().Set("Retry-After", strconv.Itoa(authLockoutRetryAfterSecs())) - return http.StatusTooManyRequests, fmt.Errorf("too many failed authentication attempts") - } - if after, ok := allowCredential(r, username); !ok { - w.Header().Set("Retry-After", strconv.Itoa(after)) - return http.StatusTooManyRequests, fmt.Errorf("too many requests") - } - status, err := fn(w, r, d) - if !trackFailures { - return status, err - } - ip := getRemoteIP(r) - if status == http.StatusUnauthorized && username != "" { - recordAuthFailure(ip, username) - } - if err == nil && (status == 0 || status == http.StatusOK) { - clearAuthLockout(ip, username) - } - return status, err - } -} - -func withAuthRateLimitModerate(fn handleFunc) handleFunc { - return withRateLimitInternal(fn, func(r *http.Request, _ *requestContext) (int, bool) { - return allowModerate(r) - }) -} - -func withAuthRateLimitOIDC(fn handleFunc) handleFunc { - return withRateLimitInternal(fn, func(r *http.Request, _ *requestContext) (int, bool) { - return allowOIDC(r) - }) -} - -func withAuthRateLimitAuthenticated(fn handleFunc) handleFunc { - return withRateLimitInternal(fn, func(_ *http.Request, d *requestContext) (int, bool) { - if d.user == nil || d.user.Username == "" || d.user.Username == "anonymous" { - return 0, true - } - return allowAuthenticated(d.user.Username) - }) -} diff --git a/backend/http/download.go b/backend/http/download.go deleted file mode 100644 index 28bb040115..0000000000 --- a/backend/http/download.go +++ /dev/null @@ -1,303 +0,0 @@ -package http - -import ( - "context" - "fmt" - "io" - "net/http" - "net/url" - "os" - "path/filepath" - "strings" - - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/indexing" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" - "github.com/gtsteffaniak/go-logger/logger" - "golang.org/x/time/rate" -) - -// throttledReadSeeker is a wrapper around an io.ReadSeeker that throttles the reading speed. -// Used for single-file downloads and for share archive downloads (see serveArchiveWithServeContent); -// archives are built to a temp file first, then bytes to the client are limited on read. -type throttledReadSeeker struct { - rs io.ReadSeeker - limiter *rate.Limiter - ctx context.Context -} - -// newThrottledReadSeeker creates a new throttledReadSeeker. -func newThrottledReadSeeker(rs io.ReadSeeker, limit rate.Limit, burst int, ctx context.Context) *throttledReadSeeker { - return &throttledReadSeeker{ - rs: rs, - limiter: rate.NewLimiter(limit, burst), - ctx: ctx, - } -} - -func (r *throttledReadSeeker) Read(p []byte) (n int, err error) { - n, err = r.rs.Read(p) - if n > 0 { - if waitErr := r.limiter.WaitN(r.ctx, n); waitErr != nil { - // The original error (like io.EOF) is potentially more important - // than the context error. - if err == nil { - err = waitErr - } - } - } - return -} - -func (r *throttledReadSeeker) Seek(offset int64, whence int) (int64, error) { - return r.rs.Seek(offset, whence) -} - -// throttledWriter wraps an io.Writer and rate-limits outbound bytes (streaming archives to the client). -type throttledWriter struct { - w io.Writer - limiter *rate.Limiter - ctx context.Context -} - -func newThrottledWriter(w io.Writer, limit rate.Limit, burst int, ctx context.Context) *throttledWriter { - return &throttledWriter{ - w: w, - limiter: rate.NewLimiter(limit, burst), - ctx: ctx, - } -} - -func (tw *throttledWriter) Write(p []byte) (n int, err error) { - n, err = tw.w.Write(p) - if n > 0 { - if waitErr := tw.limiter.WaitN(tw.ctx, n); waitErr != nil { - if err == nil { - err = waitErr - } - } - } - return -} - -// toASCIIFilename converts a filename to ASCII-safe format by replacing non-ASCII characters with underscores -func toASCIIFilename(fileName string) string { - var result strings.Builder - for _, r := range fileName { - if r > 127 { - // Replace non-ASCII characters with underscore - result.WriteRune('_') - } else { - result.WriteRune(r) - } - } - return result.String() -} - -func setContentDisposition(w http.ResponseWriter, r *http.Request, fileName string) { - dispositionType := "attachment" - if r.URL.Query().Get("inline") == "true" { - dispositionType = "inline" - // Inline SVG (and similar) can execute embedded scripts when opened as a top-level document; match upstream filebrowser mitigation. - w.Header().Set("Content-Security-Policy", "script-src 'none'") - } - - // standard: ASCII-only safe fallback - asciiFileName := toASCIIFilename(fileName) - // RFC 5987: UTF-8 encoded - encodedFileName := url.PathEscape(fileName) - - // Always set both filename (ASCII) and filename* (UTF-8) for maximum compatibility (RFC 6266) - w.Header().Set("Content-Disposition", fmt.Sprintf("%s; filename=%q; filename*=utf-8''%s", dispositionType, asciiFileName, encodedFileName)) -} - -// downloadHandler serves the raw content of a file, multiple files, or directory in various formats. -// @Summary Download content of a file, multiple files, or directory -// @Description Returns the raw content of a file, multiple files, or a directory. Supports downloading files as archives in various formats. -// @Description -// @Description **Filename Encoding:** -// @Description - The Content-Disposition header will always include both: -// @Description 1. `filename="..."`: An ASCII-safe version of the filename for compatibility. -// @Description 2. `filename*=utf-8"...`: The full UTF-8 encoded filename (RFC 6266/5987) for modern clients. -// @Description -// @Description **Multiple Files:** -// @Description - Use repeated query parameters: `?file=file1.txt&file=file2.txt&file=file3.txt` -// @Description - This supports filenames containing commas and special characters -// @Tags Resources -// @Accept json -// @Param source query string true "Source name for the files (required)" -// @Param file query []string true "File path (can be repeated for multiple files)" -// @Param inline query bool false "If true, sets 'Content-Disposition' to 'inline'. Otherwise, defaults to 'attachment'." -// @Param algo query string false "Compression algorithm for archiving multiple files or directories. Options: 'zip' and 'tar.gz'. Default is 'zip'." -// @Success 200 {file} file "Raw file or directory content, or archive for multiple files" -// @Failure 202 {object} map[string]string "Modify permissions required" -// @Failure 400 {object} map[string]string "Invalid request path" -// @Failure 404 {object} map[string]string "File or directory not found" -// @Failure 500 {object} map[string]string "Internal server error" -// @Router /api/resources/download [get] -func downloadHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - source := r.URL.Query().Get("source") - fileList := r.URL.Query()["file"] - - // Rule 1: Validate all user-provided file paths to prevent path traversal - for i, filePath := range fileList { - cleanPath, err := utils.SanitizeUserPath(filePath) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("invalid file path: %v", err) - } - fileList[i] = cleanPath - } - - return rawFilesHandler(w, r, d, source, fileList) -} - -func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext, source string, fileList []string) (int, error) { - if !d.user.Permissions.Download && d.share == nil { - return http.StatusForbidden, fmt.Errorf("user is not allowed to download") - } - - if len(fileList) == 0 && d.share == nil { - return http.StatusBadRequest, fmt.Errorf("no files specified") - } - - firstFilePath := fileList[0] - var err error - var userscope string - fileName := filepath.Base(firstFilePath) - - // Check if this is an OnlyOffice file early for error logging - isOnlyOffice := isOnlyOfficeCompatibleFile(fileName) && config.Integrations.OnlyOffice.Url != "" - var documentId string - var logContext *OnlyOfficeLogContext - - // modify all filepaths for user scope - if d.share == nil { - userscope, err = d.user.GetScopeForSourceName(source) - if err != nil { - // Send OnlyOffice error log if this was an OnlyOffice file - if isOnlyOffice { - // Try to get document ID for error logging - idx := indexing.GetIndex(source) - if idx != nil { - tempPath := utils.JoinPathAsUnix(userscope, firstFilePath) - if realPath, _, realErr := idx.GetRealPath(tempPath); realErr == nil { - if docId, _ := getOnlyOfficeId(realPath); docId != "" { - if ctx := getOnlyOfficeLogContext(docId); ctx != nil { - sendOnlyOfficeLogEvent(ctx, "ERROR", "download", - fmt.Sprintf("OnlyOffice download failed - source not available: %s - %v", firstFilePath, err)) - } - } - } - } - } - return http.StatusForbidden, err - } - for i, filePath := range fileList { - fileList[i] = utils.JoinPathAsUnix(userscope, filePath) - } - } - firstFilePath = fileList[0] - // For shares, the path is already correctly resolved by publicRawHandler - idx := indexing.GetIndex(source) - if idx == nil { - // Send OnlyOffice error log if this was an OnlyOffice file - if isOnlyOffice { - sendOnlyOfficeLogEvent(logContext, "ERROR", "download", - fmt.Sprintf("OnlyOffice download failed - source index not available: %s", source)) - } - return http.StatusInternalServerError, fmt.Errorf("source %s is not available", source) - } - realPath, isDir, err := idx.GetRealPath(firstFilePath) - if err != nil { - // Send OnlyOffice error log if this was an OnlyOffice file - if isOnlyOffice { - if docId, _ := getOnlyOfficeId(realPath); docId != "" { - if ctx := getOnlyOfficeLogContext(docId); ctx != nil { - sendOnlyOfficeLogEvent(ctx, "ERROR", "download", - fmt.Sprintf("OnlyOffice download failed - could not resolve path: %s - %v", firstFilePath, err)) - } - } - } - return http.StatusInternalServerError, err - } - - // ** Single file download with Content-Length ** - if len(fileList) == 1 && !isDir { - // Get document ID and log context for OnlyOffice downloads - if isOnlyOffice { - documentId, _ = getOnlyOfficeId(realPath) - if documentId != "" { - logContext = getOnlyOfficeLogContext(documentId) - } - } - - // Verify access control before opening the file (direct rule check) - if d.share == nil && store.Access != nil { - if !store.Access.Permitted(idx.Path, firstFilePath, d.user.Username) { - logger.Debugf("user %s denied access to path %s", d.user.Username, firstFilePath) - // Send OnlyOffice error log if this was an OnlyOffice download - if isOnlyOffice && logContext != nil { - sendOnlyOfficeLogEvent(logContext, "ERROR", "download", - fmt.Sprintf("OnlyOffice download failed - access denied by rule: %s", firstFilePath)) - } - return http.StatusForbidden, fmt.Errorf("access denied to path %s", firstFilePath) - } - } - - fd, err2 := os.Open(realPath) - if err2 != nil { - // Send OnlyOffice error log if this was an OnlyOffice download - if isOnlyOffice && logContext != nil { - sendOnlyOfficeLogEvent(logContext, "ERROR", "download", - fmt.Sprintf("OnlyOffice download failed - could not open file: %s - %v", firstFilePath, err2)) - } - return http.StatusInternalServerError, err2 - } - defer fd.Close() - - // Get file size - fileInfo, err2 := fd.Stat() - if err2 != nil { - // Send OnlyOffice error log if this was an OnlyOffice download - if isOnlyOffice && logContext != nil { - sendOnlyOfficeLogEvent(logContext, "ERROR", "download", - fmt.Sprintf("OnlyOffice download failed - could not get file info: %s - %v", firstFilePath, err2)) - } - return http.StatusInternalServerError, err2 - } - - // Send success log for OnlyOffice downloads - if isOnlyOffice && logContext != nil { - logger.Infof("OnlyOffice Server is downloading file: %s (documentId: %s)", - firstFilePath, documentId) - - sendOnlyOfficeLogEvent(logContext, "INFO", "download", - fmt.Sprintf("OnlyOffice Server downloading file: %s", firstFilePath)) - } - - // ServeContent sets Content-Length (full resource or range); avoid pre-setting so partial/range responses stay consistent. - setContentDisposition(w, r, fileName) - w.Header().Set("Cache-Control", "private") - w.Header().Set("X-Content-Type-Options", "nosniff") - // video scrubbing, etc. - // Note: http.ServeContent will respect our already-set Content-Disposition header - var reader io.ReadSeeker = fd - if d.share != nil && d.share.MaxBandwidth > 0 { - // convert KB/s to B/s - limit := rate.Limit(d.share.MaxBandwidth * 1024) - // burst size can be the same as limit - burst := d.share.MaxBandwidth * 1024 - reader = newThrottledReadSeeker(fd, limit, burst, r.Context()) - } - http.ServeContent(w, r, fileName, fileInfo.ModTime(), reader) - return 200, nil - } - - // ** Archive (ZIP/TAR.GZ) handling ** — delegate to archive package - return BuildAndStreamArchive(w, r, d, source, fileList) -} - -// isOnlyOfficeCompatibleFile checks if a file extension is supported by OnlyOffice -func isOnlyOfficeCompatibleFile(fileName string) bool { - return iteminfo.IsOnlyOffice(fileName) -} diff --git a/backend/http/httpRouter.go b/backend/http/httpRouter.go deleted file mode 100644 index 48f45fb3c6..0000000000 --- a/backend/http/httpRouter.go +++ /dev/null @@ -1,410 +0,0 @@ -package http - -import ( - "context" - "crypto/tls" - "embed" - "encoding/json" - "fmt" - "html/template" - "io/fs" - "net" - "net/http" - "os" - "time" - - _ "net/http/pprof" - - "github.com/coreos/go-systemd/v22/activation" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/database/storage/bolt" - "github.com/gtsteffaniak/filebrowser/backend/events" - "github.com/gtsteffaniak/go-logger/logger" - // http-swagger middleware -) - -// Embed the files in the frontend/dist directory -// -//go:embed embed/* -var assets embed.FS - -// GetEmbeddedAssets returns the embedded assets filesystem -func GetEmbeddedAssets() embed.FS { - return assets -} - -var ( - store *bolt.BoltStore - config *settings.Settings - assetFs fs.FS -) - -func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete chan struct{}) { - store = storage - config = &settings.Config - var err error - // Start pprof server in a separate goroutine - if settings.Env.IsDevMode { - go func() { - if err = http.ListenAndServe("localhost:6060", nil); err != nil { - logger.Fatalf("pprof server error: %v", err) - } - }() - } - - // Get the asset filesystem from fileutils - assetFs = fileutils.GetAssetFS() - if assetFs == nil { - logger.Fatal("Asset filesystem not initialized. Call fileutils.InitAssetFS first.") - } - - // In development mode, we want to reload the templates on each request. - // In production (embedded), we parse them once. - templates := template.New("").Funcs(template.FuncMap{ - "marshal": func(v interface{}) (string, error) { - a, err := json.Marshal(v) - return string(a), err - }, - }) - if !settings.Env.IsDevMode { - templates = template.Must(templates.ParseFS(assetFs, "public/index.html")) - } - templateRenderer = &TemplateRenderer{ - templates: templates, - devMode: settings.Env.IsDevMode, - } - - // Core routing - router := http.NewServeMux() - api := http.NewServeMux() - publicRoutes := http.NewServeMux() - publicApi := http.NewServeMux() - - // health routes - api.HandleFunc("GET /health", healthHandler) - publicApi.HandleFunc("GET /health", healthHandler) - - // ======================================== - // User Routes - /api/users/ (with public routes) - // ======================================== - api.HandleFunc("GET /users", withUser(userGetHandler)) - api.HandleFunc("POST /users", withSelfOrAdmin(usersPostHandler)) - api.HandleFunc("PUT /users", withUser(userPutHandler)) - api.HandleFunc("PATCH /users/pinnedItems", withUser(userPatchPinnedItemsHandler)) - api.HandleFunc("DELETE /users", withSelfOrAdmin(userDeleteHandler)) - publicApi.HandleFunc("GET /users", withUser(userGetHandler)) - - // ======================================== - // Auth Routes - /api/auth/ - // ======================================== - api.HandleFunc("POST /auth/login", withRateLimit(AuthRateLimitCredentialLockout, loginHelper(loginHandler))) - 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))) - api.HandleFunc("POST /auth/otp/verify", withOrWithoutUser(withRateLimitChain(AuthRateLimitCredentialLockout, verifyOTPHandler))) - api.HandleFunc("POST /auth/renew", withUser(withRateLimitChain(AuthRateLimitAuthenticated, renewHandler))) - api.HandleFunc("POST /auth/token", withUser(withRateLimitChain(AuthRateLimitAuthenticated, createApiTokenHandler))) - api.HandleFunc("DELETE /auth/token", withUser(withRateLimitChain(AuthRateLimitAuthenticated, deleteApiTokenHandler))) - api.HandleFunc("GET /auth/token/list", withUser(withRateLimitChain(AuthRateLimitAuthenticated, listApiTokensHandler))) - api.HandleFunc("GET /auth/token", withUser(withRateLimitChain(AuthRateLimitAuthenticated, getApiTokenHandler))) - api.HandleFunc("GET /auth/oidc/callback", withRateLimit(AuthRateLimitOIDC, oidcCallbackHandler)) - api.HandleFunc("GET /auth/oidc/login", withRateLimit(AuthRateLimitOIDC, oidcLoginHandler)) - api.HandleFunc("POST /auth/webauthn/begin-login", withoutUser(withRateLimitChain(AuthRateLimitCredential, beginPasskeyLoginHandler))) - api.HandleFunc("POST /auth/webauthn/finish-login", withoutUser(withRateLimitChain(AuthRateLimitCredential, finishPasskeyLoginHandler))) - api.HandleFunc("POST /auth/webauthn/begin-register", withUser(withRateLimitChain(AuthRateLimitAuthenticated, beginPasskeyRegistrationHandler))) - api.HandleFunc("POST /auth/webauthn/finish-register", withUser(withRateLimitChain(AuthRateLimitAuthenticated, finishPasskeyRegistrationHandler))) - api.HandleFunc("DELETE /auth/webauthn/{id}", withUser(withRateLimitChain(AuthRateLimitAuthenticated, deletePasskeyCredentialHandler))) - - // ======================================== - // Resources Routes - /api/resources/ (with public routes) - // ======================================== - api.HandleFunc("GET /resources", withUser(resourceGetHandler)) - api.HandleFunc("GET /resources/items", withUser(itemsGetHandler)) - api.HandleFunc("DELETE /resources", withUser(resourceDeleteHandler)) - api.HandleFunc("POST /resources", withUser(resourcePostHandler)) - api.HandleFunc("PUT /resources", withUser(resourcePutHandler)) - api.HandleFunc("PATCH /resources", withUser(resourcePatchHandler)) - api.HandleFunc("DELETE /resources/bulk", withUser(resourceBulkDeleteHandler)) - api.HandleFunc("POST /resources/archive", withUser(archiveCreateHandler)) - api.HandleFunc("POST /resources/unarchive", withUser(unarchiveHandler)) - api.HandleFunc("GET /resources/download", withUser(downloadHandler)) - api.HandleFunc("GET /resources/preview", withTimeout(30*time.Second, withUserHelper(previewHandler))) - api.HandleFunc("POST /resources/pause", withUser(resourcePauseHandler)) - publicApi.HandleFunc("GET /resources", withHashFile(publicGetResourceHandler)) - publicApi.HandleFunc("GET /resources/items", withHashFile(publicItemsGetHandler)) - publicApi.HandleFunc("POST /resources", withHashFile(publicUploadHandler)) - publicApi.HandleFunc("PUT /resources", withHashFile(publicPutHandler)) - publicApi.HandleFunc("DELETE /resources", withHashFile(publicDeleteHandler)) - publicApi.HandleFunc("DELETE /resources/bulk", withHashFile(publicBulkDeleteHandler)) - publicApi.HandleFunc("PATCH /resources", withHashFile(publicPatchHandler)) - publicApi.HandleFunc("GET /resources/download", withHashFile(publicDownloadHandler)) - publicApi.HandleFunc("GET /resources/preview", withTimeout(30*time.Second, withHashFileHelper(publicPreviewHandler))) - publicApi.HandleFunc("POST /resources/pause", withHashFile(publicPauseHandler)) - // Legacy routes (backwards compatibility) - api.HandleFunc("GET /raw", withUser(downloadHandler)) - publicApi.HandleFunc("GET /raw", withHashFile(publicDownloadHandler)) - - // ======================================== - // Access Routes - /api/access/ - // ======================================== - api.HandleFunc("GET /access", withAdmin(accessGetHandler)) - api.HandleFunc("POST /access", withAdmin(accessPostHandler)) - api.HandleFunc("PATCH /access", withAdmin(accessPatchHandler)) - api.HandleFunc("DELETE /access", withAdmin(accessDeleteHandler)) - api.HandleFunc("GET /access/groups", withAdmin(groupGetHandler)) - api.HandleFunc("POST /access/group", withAdmin(groupPostHandler)) - api.HandleFunc("DELETE /access/group", withAdmin(groupDeleteHandler)) - - // ======================================== - // Share Routes - /api/share/ - // ======================================== - api.HandleFunc("GET /share/list", withPermShare(shareListHandler)) - api.HandleFunc("GET /share/direct", withPermShare(shareDirectDownloadHandler)) - api.HandleFunc("GET /share", withUser(shareGetHandler)) - api.HandleFunc("POST /share", withPermShare(sharePostHandler)) - api.HandleFunc("PATCH /share", withPermShare(sharePatchHandler)) - api.HandleFunc("DELETE /share", withPermShare(shareDeleteHandler)) - publicApi.HandleFunc("GET /share/info", withOrWithoutUser(shareInfoHandler)) - publicApi.HandleFunc("PATCH /share/pinnedItems", withPermShare(sharePatchPinnedItemsHandler)) - publicApi.HandleFunc("GET /share/image", withHashFile(getShareImage)) - - // ======================================== - // Settings Routes - /api/settings/ - // ======================================== - api.HandleFunc("GET /settings", withAdmin(settingsGetHandler)) - api.HandleFunc("GET /settings/config", withAdmin(settingsConfigHandler)) - api.HandleFunc("GET /settings/sources", withUser(getSourceInfoHandler)) - - // ======================================== - // Tools Routes - /api/tools/ - // ======================================== - api.HandleFunc("GET /tools/search", withUser(searchHandler)) - api.HandleFunc("GET /tools/duplicateFinder", withUser(duplicatesHandler)) - api.HandleFunc("GET /tools/fileWatcher", withUser(fileWatchHandler)) - api.HandleFunc("GET /tools/fileWatcher/sse", withUser(fileWatchSSEHandler)) - - // ======================================== - // Media Routes - /api/media/ (with public routes) - // ======================================== - api.HandleFunc("GET /media/subtitles", withUser(subtitlesHandler)) - api.HandleFunc("GET /media/metadata", withUser(metadataHandler)) - api.HandleFunc("GET /media/lyrics", withUser(lyricsHandler)) - publicApi.HandleFunc("GET /media/metadata", withHashFile(publicMetadataHandler)) - publicApi.HandleFunc("GET /media/lyrics", withHashFile(publicLyricsHandler)) - - // ======================================== - // OnlyOffice Routes - /api/office/ (with public routes) - // ======================================== - api.HandleFunc("GET /office/config", withUser(onlyofficeClientConfigGetHandler)) - api.HandleFunc("POST /office/callback", withUser(onlyofficeCallbackHandler)) - api.HandleFunc("GET /office/callback", withUser(onlyofficeCallbackHandler)) - publicApi.HandleFunc("POST /office/callback", withHashFile(onlyofficeCallbackHandler)) - publicApi.HandleFunc("GET /office/callback", withHashFile(onlyofficeCallbackHandler)) - publicApi.HandleFunc("GET /office/config", withHashFile(onlyofficeClientConfigGetHandler)) - - // ======================================== - // Misc Routes - // ======================================== - api.HandleFunc("GET /events", withUser(sseHandler)) - if settings.Env.IsDevMode { - api.HandleFunc("GET /inspectIndex", inspectIndex) - api.HandleFunc("GET /mockData", mockData) - } - - // Mount public API - publicRoutes.Handle("/api/", http.StripPrefix("/api", publicApi)) - - // ======================================== - // Configure Main Router - // ======================================== - apiPath := config.Server.BaseURL + "api" - publicPath := config.Server.BaseURL + "public" - webDavPath := config.Server.BaseURL + "dav" - - // Mount primary API and public routes - router.Handle(apiPath+"/", http.StripPrefix(apiPath, api)) - router.Handle(publicPath+"/", http.StripPrefix(publicPath, publicRoutes)) - - // WebDAV handler - if !config.Server.DisableWebDAV { - // Uses Basic Auth where password is JWT token - // Note: do not trim /dav prefix here - webdav library requires it - router.Handle(webDavPath+"/{source}/{path...}", withBasicAuth(webDAVHandler)) - } - - // Frontend share route redirect (DEPRECATED - maintain for backwards compatibility) - // TODO: Playwright tests need updating to remove this redirect - router.HandleFunc(fmt.Sprintf("GET %vshare/", config.Server.BaseURL), withOrWithoutUser(redirectToShare)) - - // New frontend share route handler - publicRoutes.HandleFunc("GET /share/", withOrWithoutUser(indexHandler)) - - // Static assets - publicRoutes.Handle("GET /static/", http.HandlerFunc(staticAssetHandler)) - router.HandleFunc("GET /favicon.svg", http.HandlerFunc(staticAssetHandler)) - - // Index and utility routes - router.HandleFunc(config.Server.BaseURL, withOrWithoutUser(indexHandler)) - router.HandleFunc(fmt.Sprintf("GET %vhealth", config.Server.BaseURL), healthHandler) - router.Handle(fmt.Sprintf("%vswagger/", config.Server.BaseURL), withUser(swaggerHandler)) - - // Base URL redirect (non-root deployments) - if config.Server.BaseURL != "/" { - router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - http.Redirect(w, r, config.Server.BaseURL, http.StatusMovedPermanently) - }) - } - - srv := &http.Server{ - Addr: fmt.Sprintf("%v:%v", config.Server.ListenAddress, config.Server.Port), - Handler: muxWithMiddleware(router), - } - listenAddress := config.Server.ListenAddress - go func() { - var listener net.Listener - - if config.Server.Socket != "" { - if err := os.Remove(config.Server.Socket); err != nil && !os.IsNotExist(err) { - logger.Fatalf("Could not remove existing socket: %v", err) - } - var err error - listener, err = net.Listen("unix", config.Server.Socket) - if err != nil { - logger.Fatalf("Could not listen on unix socket: %v", err) - } - logger.Infof("Running at : unix://%s%s", config.Server.Socket, config.Server.BaseURL) - } else if config.Server.TLSCert != "" && config.Server.TLSKey != "" { - var scheme string - port := "" - // Determine whether to use HTTPS (TLS) or HTTP - // Load the TLS certificate and key - cer, err := tls.LoadX509KeyPair(config.Server.TLSCert, config.Server.TLSKey) - if err != nil { - logger.Fatalf("Could not load certificate: %v", err) - } - - // Create a custom TLS configuration - tlsConfig := &tls.Config{ - MinVersion: tls.VersionTLS12, - Certificates: []tls.Certificate{cer}, - } - - // Set HTTPS scheme and default port for TLS - scheme = "https" - if config.Server.Port != 443 { - port = fmt.Sprintf(":%d", config.Server.Port) - } - - // Build the full URL with host and port - fullURL := fmt.Sprintf("%s://%s%s%s", scheme, listenAddress, port, config.Server.BaseURL) - logger.Infof("Running at : %s", fullURL) - - // Attempt to get listener from socket activation with TLS configuration - socketActivationListeners, err := activation.TLSListeners(tlsConfig) - if err == nil && len(socketActivationListeners) > 0 { - listener = socketActivationListeners[0] - logger.Debug("Socket activation detected. Listening address is being controlled by systemd.") - } else if err != nil { - // if Socket Activation fails we can just fall back to create our own sockets as normal. - // so is only interesting to those who are debugging the app. - logger.Debugf("Socket activation failed: %v", err) - } - - // Create our own TLS listener if socket activation is not available. - if listener == nil { - listener, err = tls.Listen("tcp", srv.Addr, tlsConfig) - if err != nil { - logger.Fatalf("Could not start TLS server: %v", err) - } - } - - } else { - var scheme string - port := "" - // Set HTTP scheme and the default port for HTTP - scheme = "http" - if config.Server.Port != 80 { - port = fmt.Sprintf(":%d", config.Server.Port) - } - - // Build the full URL with host and port - fullURL := fmt.Sprintf("%s://%s%s%s", scheme, listenAddress, port, config.Server.BaseURL) - logger.Infof("Running at : %s", fullURL) - - // Attempt to get the listener from socket activation - socketActivationListeners, err := activation.Listeners() - if err == nil && len(socketActivationListeners) > 0 { - listener = socketActivationListeners[0] - logger.Debug("Socket activation detected. Listening address is being controlled by systemd.") - } else if err != nil { - // if Socket Activation fails we can just fall back to create our own sockets as normal. - // so is only interesting to those who are debugging the app. - logger.Debugf("Socket activation failed: %v", err) - } - - // Create our own listener if socket activation is not available. - if listener == nil { - // Replicate the behaviour of ListenAndServe - addr := srv.Addr - if addr == "" { - addr = ":http" - } - - listener, err = net.Listen("tcp", addr) - if err != nil { - logger.Fatalf("Server error: %v", err) - } - } - - } - - if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed { - logger.Fatalf("Server error: %v", err) - } - }() - - // Wait for context cancellation to shut down the server - <-ctx.Done() - logger.Info("Shutting down HTTP server...") - - // Close all SSE sessions - events.Shutdown() - - // Persist in-memory state before shutting down the HTTP server - if store != nil { - if store.Share != nil { - if err := store.Share.Flush(); err != nil { - logger.Errorf("Failed to flush share storage: %v", err) - } - } - if store.Access != nil { - if err := store.Access.Flush(); err != nil { - logger.Errorf("Failed to flush access storage: %v", err) - } - } - if store.Indexing != nil { - if err := store.Indexing.Flush(); err != nil { - logger.Errorf("Failed to flush indexing storage: %v", err) - } - } - } - - // Graceful shutdown with a timeout - 30 seconds, in case downloads are happening - shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - if err := srv.Shutdown(shutdownCtx); err != nil { - logger.Errorf("HTTP server forced to shut down: %v", err) - } else { - logger.Info("HTTP server shut down gracefully.") - } - - if config.Server.Socket != "" { - if err := os.Remove(config.Server.Socket); err != nil && !os.IsNotExist(err) { - logger.Debugf("Could not remove unix socket: %v", err) - } - } - - // Signal that shutdown is complete - close(shutdownComplete) -} diff --git a/backend/http/middleware_test.go b/backend/http/middleware_test.go deleted file mode 100644 index d14ec45194..0000000000 --- a/backend/http/middleware_test.go +++ /dev/null @@ -1,312 +0,0 @@ -package http - -import ( - "net/http" - "net/http/httptest" - "path/filepath" - "testing" - "time" - - storm "github.com/asdine/storm/v3" - "github.com/gtsteffaniak/filebrowser/backend/auth" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/access" - "github.com/gtsteffaniak/filebrowser/backend/database/share" - "github.com/gtsteffaniak/filebrowser/backend/database/storage/bolt" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" -) - -func setupTestEnv(t *testing.T) { - dbPath := filepath.Join(t.TempDir(), "db") - db, err := storm.Open(dbPath) - if err != nil { - t.Fatal(err) - } - store, err = bolt.NewStorage(db) - if err != nil { - t.Fatal(err) - } - config = &settings.Config // mocked - config.Server.SourceMap = map[string]*settings.Source{ - "/srv": &settings.Source{ - Path: "/srv", - Name: "srv", - }, - } - config.Server.NameToSource = map[string]*settings.Source{ - "srv": &settings.Source{ - Path: "/srv", - Name: "srv", - }, - } - // Initialize user resolvers so users package can resolve source names - settings.InitializeUserResolvers() - mockFileInfoFaster(t) // Mock FileInfoFasterFunc for this test -} - -func mockFileInfoFaster(t *testing.T) { - // Backup the original function - originalFileInfoFaster := FileInfoFasterFunc - // Defer restoration of the original function - t.Cleanup(func() { FileInfoFasterFunc = originalFileInfoFaster }) - - // Mock the function to skip execution - FileInfoFasterFunc = func(opts utils.FileOptions, access *access.Storage, user *users.User, share *share.Storage) (*iteminfo.ExtendedFileInfo, error) { - return &iteminfo.ExtendedFileInfo{ - FileInfo: iteminfo.FileInfo{ - Path: opts.Path, - ItemInfo: iteminfo.ItemInfo{ - Name: "mocked_file", - Size: 12345, - }, - }, - }, nil - } -} - -func TestWithAdminHelper(t *testing.T) { - setupTestEnv(t) - // Mock a user who has admin permissions - adminUser := &users.User{ - ID: 1, - Username: "admin", - Permissions: users.Permissions{Admin: true}, // Ensure the user is an admin - } - nonAdminUser := &users.User{ - ID: 2, - Username: "non-admin", - Permissions: users.Permissions{Admin: false}, // Non-admin user - } - // Save the users to the mock database - if err := store.Users.Save(adminUser, true, true); err != nil { - t.Fatal("failed to save admin user:", err) - } - if err := store.Users.Save(nonAdminUser, true, true); err != nil { - t.Fatal("failed to save non-admin user:", err) - } - // Test cases for different scenarios - testCases := []struct { - name string - expectedStatusCode int - user *users.User - }{ - { - name: "Admin access allowed", - expectedStatusCode: http.StatusOK, // Admin should be able to access - user: adminUser, - }, - { - name: "Non-admin access forbidden", - expectedStatusCode: http.StatusForbidden, // Non-admin should be forbidden - user: nonAdminUser, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - // Mock the context with the current user - data := &requestContext{ - user: tc.user, - } - tokenString, _, err := auth.MakeSignedTokenAPI(tc.user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), time.Hour*2, tc.user.Perm, false) - if err != nil { - t.Fatalf("Error making token for request: %v", err) - } - - // Wrap the usersGetHandler with the middleware - handler := withAdminHelper(mockHandler) - - // Create a response recorder to capture the handler's output - recorder := httptest.NewRecorder() - // Create the request and apply the token as a cookie - req, err := http.NewRequest(http.MethodGet, "/users", http.NoBody) - if err != nil { - t.Fatalf("Error creating request: %v", err) - } - req.AddCookie(&http.Cookie{ - Name: "filebrowser_quantum_jwt", - Value: tokenString, - }) - - // Call the handler with the test request and mock context - status, err := handler(recorder, req, data) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - // Verify the status code - if status != tc.expectedStatusCode { - t.Errorf("\"%v\" expected status code %d, got %d", tc.name, tc.expectedStatusCode, status) - } - }) - } -} - -func TestPublicShareHandlerAuthentication(t *testing.T) { - setupTestEnv(t) - - const passwordBcrypt = "$2y$10$TFAmdCbyd/mEZDe5fUeZJu.MaJQXRTwdqb/IQV.eTn6dWrF58gCSe" // bcrypt hashed password - - // Create and save a dummy user with ID 1 (all shares use UserID: 1) - dummyUser := &users.User{ - ID: 1, - Username: "testuser", - Permissions: users.Permissions{Admin: false}, - Scopes: []users.SourceScope{ - {Name: "srv", Scope: "/"}, // Root scope on srv source - }, - } - if err := store.Users.Save(dummyUser, true, true); err != nil { - t.Fatal("failed to save dummy user:", err) - } - - testCases := []struct { - name string - share *share.Link - token string - password string - extraHeaders map[string]string - expectedStatusCode int - }{ - { - name: "Public share, no auth required", - share: &share.Link{ - Hash: "public_hash", - UserID: 1, - CommonShare: share.CommonShare{ - Source: "/srv", - }, - }, - expectedStatusCode: http.StatusOK, // zero means 200 on helpers - }, - { - name: "Private share, valid password when token exists", - share: &share.Link{ - Hash: "pw_and_token_hash", - UserID: 1, - PasswordHash: passwordBcrypt, - Token: "some_random_token", - CommonShare: share.CommonShare{ - Source: "/srv", - }, - }, - extraHeaders: map[string]string{ - "X-SHARE-PASSWORD": "password", - }, - expectedStatusCode: http.StatusOK, // zero means 200 on helpers - }, - { - name: "Private share, no auth provided", - share: &share.Link{ - Hash: "private_hash", - UserID: 1, - PasswordHash: passwordBcrypt, - Token: "123", - }, - expectedStatusCode: http.StatusUnauthorized, - }, - { - name: "Private share, valid token", - share: &share.Link{ - Hash: "token_hash", - UserID: 1, - PasswordHash: passwordBcrypt, - Token: "123", - CommonShare: share.CommonShare{ - Source: "/srv", - }, - }, - token: "123", - expectedStatusCode: http.StatusOK, // zero means 200 on helpers - }, - { - name: "Private share, invalid password", - share: &share.Link{ - Hash: "pw_hash", - UserID: 1, - PasswordHash: passwordBcrypt, - Token: "123", - }, - extraHeaders: map[string]string{ - "X-SHARE-PASSWORD": "wrong-password", - }, - expectedStatusCode: http.StatusUnauthorized, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - // Save the share in the mock store - if err := store.Share.Save(tc.share); err != nil { - t.Fatal("failed to save share:", err) - } - - // Create a response recorder to capture handler output - recorder := httptest.NewRecorder() - - // Wrap the handler with authentication middleware - handler := withHashFileHelper(publicGetResourceHandler) - if err := store.Settings.Save(&settings.Settings{ - Auth: settings.Auth{ - Key: "key", - }, - }); err != nil { - t.Fatalf("failed to save settings: %v", err) - } - - // Prepare the request with query parameters and optional headers - req := newTestRequest(t, tc.share.Hash, tc.token, tc.password, tc.extraHeaders) - - // Serve the request - status, _ := handler(recorder, req, &requestContext{}) - - // Check if the response matches the expected status code - if status != tc.expectedStatusCode { - t.Errorf("expected status code %d, got %d", tc.expectedStatusCode, status) - } - }) - } -} - -// Helper function to create a new HTTP request with optional parameters -func newTestRequest(t *testing.T, hash, token, password string, headers map[string]string) *http.Request { - req := newHTTPRequest(t, hash, func(r *http.Request) { - // Set query parameters based on provided values - q := r.URL.Query() - q.Set("path", "/") - q.Set("hash", hash) - if token != "" { - q.Set("token", token) - } - if password != "" { - q.Set("password", password) - } - r.URL.RawQuery = q.Encode() - - // Set any extra headers if provided - for key, value := range headers { - r.Header.Set(key, value) - } - }) - return req -} - -func mockHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - return http.StatusOK, nil // mock response -} - -// Modify newHTTPRequest to accept the hash and use it in the URL path. -func newHTTPRequest(t *testing.T, hash string, requestModifiers ...func(*http.Request)) *http.Request { - t.Helper() - url := "/public/share/" + hash + "/" // Dynamically include the hash in the URL path - r, err := http.NewRequest(http.MethodGet, url, http.NoBody) - if err != nil { - t.Fatalf("failed to create request: %v", err) - } - for _, modify := range requestModifiers { - modify(r) - } - return r -} diff --git a/backend/http/onlyOffice_test.go b/backend/http/onlyOffice_test.go deleted file mode 100644 index e07b088f24..0000000000 --- a/backend/http/onlyOffice_test.go +++ /dev/null @@ -1,182 +0,0 @@ -package http - -import ( - "fmt" - "net/url" - "testing" - - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/access" - "github.com/gtsteffaniak/filebrowser/backend/database/share" - "github.com/gtsteffaniak/filebrowser/backend/database/storage/bolt" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" -) - -func TestResolveOnlyOfficeDownloadURL(t *testing.T) { - orig := config.Integrations.OnlyOffice - t.Cleanup(func() { - config.Integrations.OnlyOffice = orig - }) - - config.Integrations.OnlyOffice.Url = "http://192.168.88.100:8282" - config.Integrations.OnlyOffice.InternalUrl = "http://onlyoffice" - - cachePath := "/cache/files/data/doc_1/output.ods/output.ods?md5=abc&expires=1" - publicURL := "http://192.168.88.100:8282" + cachePath - internalURL := "http://onlyoffice" + cachePath - - tests := []struct { - name string - input string - want string - }{ - { - name: "rewrites public cache URL to internal host", - input: publicURL, - want: internalURL, - }, - { - name: "empty URL", - input: "", - want: "", - }, - { - name: "untrusted host rejected", - input: "http://other-host:8282" + cachePath, - want: "", - }, - { - name: "non-http scheme rejected", - input: "ftp://192.168.88.100:8282" + cachePath, - want: "", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := resolveOnlyOfficeDownloadURL(tt.input) - if got != tt.want { - t.Errorf("resolveOnlyOfficeDownloadURL() = %q, want %q", got, tt.want) - } - }) - } - - t.Run("pass through public URL when internalUrl unset", func(t *testing.T) { - config.Integrations.OnlyOffice.InternalUrl = "" - got := resolveOnlyOfficeDownloadURL(publicURL) - if got != publicURL { - t.Errorf("resolveOnlyOfficeDownloadURL() = %q, want %q", got, publicURL) - } - }) - - t.Run("hostname match with default http port", func(t *testing.T) { - config.Integrations.OnlyOffice.Url = "http://office.local" - config.Integrations.OnlyOffice.InternalUrl = "http://onlyoffice" - input := "http://office.local:80" + cachePath - want := "http://onlyoffice" + cachePath - got := resolveOnlyOfficeDownloadURL(input) - if got != want { - t.Errorf("resolveOnlyOfficeDownloadURL() = %q, want %q", got, want) - } - }) - - t.Run("reject when public url not configured", func(t *testing.T) { - config.Integrations.OnlyOffice.Url = "" - config.Integrations.OnlyOffice.InternalUrl = "http://onlyoffice" - got := resolveOnlyOfficeDownloadURL(publicURL) - if got != "" { - t.Errorf("resolveOnlyOfficeDownloadURL() = %q, want empty", got) - } - }) -} - -func TestDeleteOfficeId(t *testing.T) { - const rawPath = "/docs/document.docx" - - tests := []struct { - name string - resolve func(utils.FileOptions) (*iteminfo.ExtendedFileInfo, error) - deleteKey string - remainKey string - }{ - { - name: "deletes resolved realpath", - resolve: func(utils.FileOptions) (*iteminfo.ExtendedFileInfo, error) { - return &iteminfo.ExtendedFileInfo{RealPath: "/some/path/document.docx"}, nil - }, - deleteKey: "/some/path/document.docx", - remainKey: rawPath, - }, - { - name: "fallback to raw path on error", - resolve: func(utils.FileOptions) (*iteminfo.ExtendedFileInfo, error) { - return nil, fmt.Errorf("could not resolve path") - }, - deleteKey: rawPath, - remainKey: "/some/path/document.docx", - }, - { - name: "also deletes realpath when partially resolved before erroring", - resolve: func(utils.FileOptions) (*iteminfo.ExtendedFileInfo, error) { - return &iteminfo.ExtendedFileInfo{RealPath: "/some/path/document.docx"}, fmt.Errorf("access check failed") - }, - deleteKey: "/some/path/document.docx", - remainKey: rawPath, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - origStore := store - store = &bolt.BoltStore{Access: &access.Storage{}, Share: &share.Storage{}} - t.Cleanup(func() { store = origStore }) - - origFunc := files.FileInfoFasterFunc - t.Cleanup(func() { files.FileInfoFasterFunc = origFunc }) - files.FileInfoFasterFunc = func(opts utils.FileOptions, accessStore *access.Storage, user *users.User, shareStore *share.Storage) (*iteminfo.ExtendedFileInfo, error) { - if opts.Path != rawPath { - t.Errorf("expected opts.Path=%q, got %q", rawPath, opts.Path) - } - if opts.Source != "source" { - t.Errorf("expected opts.Source=%q, got %q", "source", opts.Source) - } - if !opts.FollowSymlinks { - t.Error("expected FollowSymlinks=true") - } - return tt.resolve(opts) - } - utils.OnlyOfficeCache.Set(tt.deleteKey, "document-key") - utils.OnlyOfficeCache.Set(tt.remainKey, "other-key") - t.Cleanup(func() { - utils.OnlyOfficeCache.Delete(tt.deleteKey) - utils.OnlyOfficeCache.Delete(tt.remainKey) - }) - deleteOfficeId("source", rawPath, &users.User{}) - if _, err := getOnlyOfficeId(tt.deleteKey); err == nil { - t.Errorf("expected cache entry %q to be deleted", tt.deleteKey) - } - if _, err := getOnlyOfficeId(tt.remainKey); err != nil { - t.Errorf("expected cache entry %q to remain, but it was deleted", tt.remainKey) - } - }) - } -} - -func TestOnlyOfficeURLHostsMatch(t *testing.T) { - mustParse := func(raw string) *url.URL { - t.Helper() - u, err := url.Parse(raw) - if err != nil { - t.Fatalf("url.Parse(%q): %v", raw, err) - } - return u - } - - if !onlyOfficeURLHostsMatch(mustParse("http://office.local:80/x"), mustParse("http://office.local/x")) { - t.Fatal("expected office.local:80 to match office.local with default port") - } - if onlyOfficeURLHostsMatch(mustParse("http://evil.example/x"), mustParse("http://office.local/x")) { - t.Fatal("expected different hostnames not to match") - } -} diff --git a/backend/http/public.go b/backend/http/public.go deleted file mode 100644 index 3a7f317257..0000000000 --- a/backend/http/public.go +++ /dev/null @@ -1,506 +0,0 @@ -package http - -import ( - "encoding/json" - "fmt" - "net/http" - "strings" - - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/preview" - "github.com/gtsteffaniak/go-logger/logger" - - _ "github.com/gtsteffaniak/filebrowser/backend/swagger/docs" -) - -// publicDownloadHandler serves the raw content of a file, multiple files, or directory via a public share. -// @Summary Download files from a public share -// @Description Downloads raw content from a public share. Supports single files, multiple files, or directories as archives. Enforces download limits (global or per-user) and blocks anonymous users when per-user limits are enabled. -// @Description -// @Description **Multiple Files:** -// @Description - Use repeated query parameters: `?file=file1.txt&file=file2.txt&file=file3.txt` -// @Description - This supports filenames containing commas and special characters -// @Tags Shares -// @Accept json -// @Produce octet-stream -// @Param hash query string true "Share hash for authentication" -// @Param file query []string true "File path (can be repeated for multiple files)" -// @Param inline query bool false "If true, sets 'Content-Disposition' to 'inline'. Otherwise, defaults to 'attachment'." -// @Param algo query string false "Compression algorithm for archiving multiple files or directories. Options: 'zip' and 'tar.gz'. Default is 'zip'." -// @Success 200 {file} file "Raw file or directory content, or archive for multiple files" -// @Failure 400 {object} map[string]string "Invalid request path or encoding" -// @Failure 403 {object} map[string]string "Download limit reached, anonymous access blocked, or share unavailable" -// @Failure 404 {object} map[string]string "Share not found or file not found" -// @Failure 500 {object} map[string]string "Internal server error" -// @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 *requestContext) (int, error) { - if d.share.ShareType == "upload" { - return http.StatusNotImplemented, fmt.Errorf("downloads are disabled for upload shares") - } - - // Check DisableDownload permission for normal shares - if d.share.DisableDownload { - return http.StatusForbidden, fmt.Errorf("downloads are not allowed for this share") - } - - // Check global download limit (if not using per-user limits) - if !d.share.PerUserDownloadLimit && d.share.DownloadsLimit > 0 && d.share.Downloads >= d.share.DownloadsLimit { - return http.StatusForbidden, fmt.Errorf("share downloads limit reached") - } - - // Check per-user download limit - if d.share.PerUserDownloadLimit { - // Block anonymous users - if d.user.Username == "anonymous" { - return http.StatusForbidden, fmt.Errorf("anonymous downloads are not allowed with per-user limits") - } - // Check if user has reached their limit - if d.share.HasReachedUserLimit(d.user.Username) { - return http.StatusForbidden, fmt.Errorf("user download limit reached for this share") - } - } - - d.share.Mu.Lock() - d.share.Downloads++ - d.share.Mu.Unlock() - - // Track per-user download if enabled - if d.share.PerUserDownloadLimit { - d.share.IncrementUserDownload(d.user.Username) - } - - // Get all "file" parameter values (supports repeated params) - files := r.URL.Query()["file"] - if len(files) == 0 { - files = []string{"/"} - } - - // Get the actual source name from the share's source mapping - sourceInfo, ok := config.Server.SourceMap[d.share.Source] - if !ok { - return http.StatusInternalServerError, fmt.Errorf("source not found for share") - } - actualSourceName := sourceInfo.Name - - // Process each file path - fileList := []string{} - for _, file := range files { - // Rule 1: Validate each file path to prevent path traversal - cleanFile, err := utils.SanitizeUserPath(file) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("invalid file path: %v", err) - } - - // Join the share path with the requested path - filePath := utils.JoinPathAsUnix(d.share.Path, cleanFile) - fileList = append(fileList, filePath) - } - - status, err := rawFilesHandler(w, r, d, actualSourceName, fileList) - if err != nil { - if err == errors.ErrDownloadNotAllowed { - return http.StatusForbidden, errors.ErrDownloadNotAllowed - } - logger.Errorf("public share handler: error processing filelist: %v with error %v", files, err) - return status, fmt.Errorf("error processing filelist: %v", files) - } - return status, nil -} - -// publicShareHandler returns file or directory information from a public share. -// @Summary Get file/directory information from a public share -// @Description Returns metadata for files or directories accessible via a public share link. Browsing is disabled for upload-only shares. -// @Tags Shares -// @Accept json -// @Produce json -// @Param hash query string true "Share hash for authentication" -// @Param path query string false "Path within the share to retrieve information for. Defaults to share root." -// @Param content query string false "Include file content if true" -// @Param metadata query string false "Extract audio/video metadata if true" -// @Success 200 {object} iteminfo.FileInfo "File or directory metadata" -// @Failure 403 {object} map[string]string "Share unavailable or access denied" -// @Failure 404 {object} map[string]string "Share not found or file not found" -// @Failure 500 {object} map[string]string "Internal server error" -// @Failure 501 {object} map[string]string "Browsing disabled for upload shares" -// @Router /public/api/resources [get] -func publicGetResourceHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if d.share.ShareType == "upload" { - return http.StatusNotImplemented, fmt.Errorf("browsing is disabled for upload shares") - } - return renderJSON(w, r, d.fileInfo) -} - -// publicUploadHandler processes file uploads to a public upload share. -// @Summary Upload files to a public upload share -// @Description Handles file and directory uploads to an upload-only public share. Supports chunked uploads, conflict resolution (override), and directory creation. -// @Tags Shares -// @Accept multipart/form-data -// @Produce json -// @Param hash query string true "Share hash for authentication" -// @Param path query string true "path within the share to upload to. Must be relative to share root." -// @Param override query bool false "If true, overwrite existing files/folders. Defaults to false." -// @Param action query string false "Upload action: 'override' to replace files, 'rename' to auto-rename" -// @Param file formData file true "File to upload" -// @Success 200 {object} map[string]string "Upload successful" -// @Failure 400 {object} map[string]string "Invalid request or parameters" -// @Failure 403 {object} map[string]string "Share unavailable or upload not allowed" -// @Failure 404 {object} map[string]string "Share not found" -// @Failure 409 {object} map[string]string "File or directory already exists (conflict)" -// @Failure 500 {object} map[string]string "Internal server error during upload" -// @Failure 501 {object} map[string]string "Uploading disabled for non-upload shares" -// @Router /public/api/resources [post] -func publicUploadHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if d.share.ShareType != "upload" && !d.share.AllowCreate { - return http.StatusForbidden, fmt.Errorf("uploading is disabled for this share") - } - if !d.share.AllowReplacements && r.URL.Query().Get("action") == "override" { - return http.StatusForbidden, fmt.Errorf("cannot overwrite files for this share") - } - // Go automatically decodes query params - source := config.Server.SourceMap[d.share.Source].Name - // adjust query params to match resourcePostHandler - q := r.URL.Query() - q.Set("source", source) - q.Set("path", d.IndexPath) - r.URL.RawQuery = q.Encode() - status, err := resourcePostHandler(w, r, d) - if err != nil { - logger.Errorf("public upload handler: error uploading with error %v", err) - return http.StatusInternalServerError, fmt.Errorf("upload failure occured on backend") - } - return status, nil -} - -// health godoc -// @Summary Health Check -// @Schemes -// @Description Returns the health status of the API. -// @Accept json -// @Produce json -// @Success 200 {object} HttpResponse "successful health check response" -// @Router /health [get] -func healthHandler(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - response := HttpResponse{Message: "ok"} // Create response with status "ok" - err := json.NewEncoder(w).Encode(response) // Encode the response into JSON - if err != nil { - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - } -} - -// publicPreviewHandler handles the preview request for images from public shares. -// @Summary Get image/video preview from a public share -// @Description Returns a preview (thumbnail) for images or videos accessible via a public share. Preview generation can be disabled globally or per-share. Not available for upload-only shares. -// @Tags Shares -// @Accept json -// @Produce image/jpeg -// @Param hash query string true "Share hash for authentication" -// @Param path query string true "File path within the share to preview" -// @Param size query string false "Preview size: 'small' or 'large'. Default is based on server config." -// @Success 200 {file} file "Preview image content (JPEG)" -// @Failure 403 {object} map[string]string "Share unavailable or access denied" -// @Failure 404 {object} map[string]string "File not found or preview not available" -// @Failure 500 {object} map[string]string "Internal server error" -// @Failure 501 {object} map[string]string "Previews disabled globally, for this share, or for upload shares" -// @Router /public/api/resources/preview [get] -func publicPreviewHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if config.Server.DisablePreviews || d.share.DisableThumbnails { - return http.StatusNotImplemented, fmt.Errorf("preview is disabled") - } - if d.share.ShareType == "upload" { - return http.StatusNotImplemented, fmt.Errorf("preview is disabled for upload shares") - } - status, err := previewHelperFunc(w, r, d) - if err != nil { - logger.Errorf("public preview handler: error getting preview with error %v", err) - // Obfuscate errors for shares to prevent information leakage - return http.StatusNotFound, fmt.Errorf("preview not available for this item") - } - return status, err -} - -// publicPutHandler handles the PUT request for a public share. -// @Summary Update a file in a public share -// @Description Updates the content of a file in a public share. -// @Tags Shares -// @Accept json -// @Produce json -// @Param hash query string true "Share hash for authentication" -// @Param path query string true "Path to the file to update" -// @Param content body string true "New content for the file" -// @Success 200 {object} map[string]string "File updated successfully" -// @Failure 400 {object} map[string]string "Invalid request or parameters" -// @Failure 403 {object} map[string]string "Share unavailable or update not allowed" -// @Failure 404 {object} map[string]string "Share not found or file not found" -// @Failure 500 {object} map[string]string "Internal server error" -// @Router /public/api/resources [put] -func publicPutHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - // update path to be the source path - if !d.share.AllowModify { - return http.StatusForbidden, fmt.Errorf("create is not allowed for this share") - } - sourceName := d.share.GetSourceName() - if sourceName == "" { - return http.StatusNotFound, fmt.Errorf("source not available") - } - - if !d.share.AllowModify { - return http.StatusForbidden, fmt.Errorf("edit permission not allowed for this share") - } - // Go automatically decodes query params - path := r.URL.Query().Get("path") - - // Rule 1: Validate user-provided path to prevent path traversal - cleanPath, err := utils.SanitizeUserPath(path) - if err != nil { - return http.StatusBadRequest, err - } - - resolvedPath := utils.JoinPathAsUnix(d.share.Path, cleanPath) - err = files.WriteFile(sourceName, resolvedPath, r.Body) - // hide the error - if err != nil { - logger.Errorf("public put handler: error updating resource with error %v", err) - return http.StatusInternalServerError, fmt.Errorf("an error occurred while updating the resource") - } - return http.StatusOK, nil -} - -// deprecated -- see publicBulkDeleteHandler -func publicDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !d.share.AllowDelete { - return http.StatusForbidden, fmt.Errorf("delete is not allowed for this share") - } - fileInfo, err := files.FileInfoFaster(utils.FileOptions{ - FollowSymlinks: true, - Path: d.IndexPath, - Source: d.share.Source, - }, store.Access, d.shareUser, store.Share) - if err != nil { - return http.StatusNotFound, fmt.Errorf("resource not available") - } - err = files.DeleteFiles(d.share.Source, fileInfo.RealPath, fileInfo.Type == "directory") - if err != nil { - logger.Errorf("public delete handler: error deleting resource with error %v", err) - return http.StatusInternalServerError, fmt.Errorf("an error occured while deleting the resource") - } - // delete thumbnails - preview.DelThumbs(r.Context(), *fileInfo) - return http.StatusOK, nil -} - -// publicBulkDeleteHandler deletes multiple resources from a public share in a single request. -// @Summary Bulk delete resources from public share -// @Description Deletes multiple resources specified in the request body. Returns a list of succeeded and failed deletions. -// @Tags Shares -// @Accept json -// @Produce json -// @Param hash query string true "Share hash for authentication" -// @Param items body []BulkDeleteItem true "Array of items to delete, each with source and path" -// @Success 200 {object} BulkDeleteResponse "All resources deleted successfully" -// @Success 207 {object} BulkDeleteResponse "Partial success - some resources deleted, some failed" -// @Failure 400 {object} map[string]string "Bad request - invalid JSON or empty items array" -// @Failure 403 {object} map[string]string "Forbidden - delete not allowed for this share" -// @Failure 500 {object} map[string]string "Internal server error - all deletions failed" -// @Router /public/api/resources/bulk [delete] -func publicBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !d.share.AllowDelete { - return http.StatusForbidden, fmt.Errorf("delete is not allowed for this share") - } - // hide the error - status, err := resourceBulkDeleteHandler(w, r, d) - if err != nil { - logger.Errorf("public bulk delete handler: error deleting resources with error %v", err) - return http.StatusInternalServerError, fmt.Errorf("an error occurred while processing the request") - } - return status, nil -} - -// publicPatchHandler performs a patch operation (e.g., move, copy, rename) on resources in a public share. -// @Summary Move, copy, or rename resources in a public share -// @Description Performs move, copy, or rename operations on multiple resources within a public share. All operations are performed atomically. -// @Tags Shares -// @Accept json -// @Produce json -// @Param hash query string true "Share hash for authentication" -// @Param request body MoveCopyRequest true "Move/copy request with items and action" -// @Success 200 {object} MoveCopyResponse "All operations completed successfully" -// @Success 207 {object} MoveCopyResponse "Partial success - some operations succeeded, some failed" -// @Failure 400 {object} map[string]string "Bad request - invalid JSON or parameters" -// @Failure 403 {object} map[string]string "Forbidden - modify not allowed for this share" -// @Failure 404 {object} map[string]string "Share or resource not found" -// @Failure 500 {object} MoveCopyResponse "Internal server error" -// @Router /public/api/resources [patch] -func publicPatchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !d.share.AllowModify { - return http.StatusForbidden, fmt.Errorf("edit permission not allowed for this share") - } - - // Get the source from the share - sourceName := d.share.GetSourceName() - if sourceName == "" { - return http.StatusNotFound, fmt.Errorf("source not available") - } - - // Replace user with the share creator's user for proper permission checking - shareCreatedByUser, err := store.Users.Get(d.share.UserID) - if err != nil { - return http.StatusNotFound, fmt.Errorf("user for share no longer exists") - } - d.user = shareCreatedByUser - - // Parse the request body - var req MoveCopyRequest - if err = json.NewDecoder(r.Body).Decode(&req); err != nil { - return http.StatusBadRequest, fmt.Errorf("invalid JSON body: %v", err) - } - - if req.Action == "" { - return http.StatusBadRequest, fmt.Errorf("action is required (copy, move, or rename)") - } - - // Transform the request: prepend share path and add source to each item - // This normalizes the request to look like a regular user request - // Note: Share paths are absolute, so we don't strip user scope here - // resourcePatchHandler will skip adding scope for shares - for i := range req.Items { - var sanitizedPath string - sanitizedPath, err = utils.SanitizeUserPath(req.Items[i].FromPath) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("invalid from path: %w", err) - } - req.Items[i].FromSource = sourceName - req.Items[i].FromPath = utils.JoinPathAsUnix(d.share.Path, sanitizedPath) - sanitizedPath, err = utils.SanitizeUserPath(req.Items[i].ToPath) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("invalid to path: %w", err) - } - req.Items[i].ToSource = sourceName - req.Items[i].ToPath = utils.JoinPathAsUnix(d.share.Path, sanitizedPath) - } - d.Data = req - - // Call the regular handler (will treat this like a normal user request now) - status, err := resourcePatchHandler(w, r, d) - - // For shares, we need to sanitize the response to hide internal details - // The response has already been written by resourcePatchHandler, but we can still return error - if err != nil { - logger.Errorf("public patch handler: error processing patch with error %v", err) - // Obfuscate errors for security - return http.StatusInternalServerError, fmt.Errorf("an error occurred while processing the request") - } - - return status, err -} - -// getShareImage serves banner or favicon files for shares as resizable previews -// @Summary Get share image (banner or favicon) as preview -// @Description Returns a resizable preview (large size) for the banner or favicon file of a share -// @Tags Shares -// @Produce image/jpeg -// @Param hash query string true "Share hash" -// @Param banner query bool false "Request banner file" -// @Param favicon query bool false "Request favicon file" -// @Success 200 {file} file "Preview image content (JPEG)" -// @Failure 400 {object} map[string]string "Invalid request" -// @Failure 403 {object} map[string]string "Permission denied" -// @Failure 404 {object} map[string]string "Asset not found" -// @Router /public/api/share/image [get] -func getShareImage(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - // Determine which asset is being requested - isBanner := r.URL.Query().Get("banner") == "true" - isFavicon := r.URL.Query().Get("favicon") == "true" - - if !isBanner && !isFavicon { - return http.StatusBadRequest, fmt.Errorf("either banner or favicon parameter must be true") - } - - shareCreatedByUser, err := store.Users.Get(d.share.UserID) - if err != nil { - return http.StatusNotFound, fmt.Errorf("user for share no longer exists") - } - - sourceName, assetPath, err := d.share.GetShareImagePartsHelper(isBanner) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("invalid asset configuration: %v", err) - } - - // Get file info - fileInfo, err := files.FileInfoFaster(utils.FileOptions{ - Path: assetPath, - Source: sourceName, - Expand: false, - Content: false, - Metadata: false, - ShowHidden: false, - FollowSymlinks: true, - }, store.Access, shareCreatedByUser, store.Share) - - if err != nil { - logger.Errorf("error accessing share asset: source=%v path=%v error=%v", sourceName, assetPath, err) - return http.StatusNotFound, fmt.Errorf("asset file not found or not accessible") - } - - // Ensure it's an image file - if !strings.HasPrefix(fileInfo.Type, "image/") { - return http.StatusBadRequest, fmt.Errorf("invalid file type, must be image") - } - - // Set file info in request context for preview generation - d.fileInfo = *fileInfo - q := r.URL.Query() - if isBanner { - q.Set("size", "xlarge") - } else { - q.Set("size", "small") - } - r.URL.RawQuery = q.Encode() - - // Use the preview helper to generate and serve a resized preview - status, err := previewHelperFunc(w, r, d) - if err != nil { - logger.Errorf("error generating preview for share asset: source=%v path=%v error=%v", sourceName, assetPath, err) - return http.StatusNotFound, fmt.Errorf("preview not available for this asset") - } - - return status, err -} - -// publicItemsGetHandler efficiently returns a basic list of items for a directory in a public share. -// @Summary Get directory items (public share) -// @Description Efficiently returns a basic list of items for the specified path in a public share. Use hash for authentication instead of source. Use 'only' parameter to filter by only files or folders. -// @Tags Shares -// @Accept json -// @Produce json -// @Param hash query string true "Share hash for authentication" -// @Param path query string false "Path within the share to list child items. Defaults to share root." -// @Param only query string false "Filter: 'files', 'folders', or omit for both" -// @Success 200 {object} files.Items "lists files and folders" -// @Failure 403 {object} map[string]string "Forbidden (access denied)" -// @Failure 404 {object} map[string]string "Share not found or source not found" -// @Failure 500 {object} map[string]string "Internal server error" -// @Router /public/api/resources/items [get] -func publicItemsGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - sourceInfo, ok := config.Server.SourceMap[d.share.Source] - if !ok { - return http.StatusNotFound, fmt.Errorf("source not found") - } - items, err := files.GetDirItems(utils.FileOptions{ - FollowSymlinks: true, - Path: d.IndexPath, - Source: sourceInfo.Name, - ShowHidden: d.shareUser.ShowHidden, - Only: r.URL.Query().Get("only"), - }, store.Access, d.shareUser) - if err != nil { - if err == errors.ErrAccessDenied { - return http.StatusForbidden, err - } - return http.StatusInternalServerError, err - } - return renderJSON(w, r, items) -} diff --git a/backend/http/settings.go b/backend/http/settings.go deleted file mode 100644 index 28ba875689..0000000000 --- a/backend/http/settings.go +++ /dev/null @@ -1,117 +0,0 @@ -package http - -import ( - "fmt" - "net/http" - "os" - - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/indexing" - "github.com/gtsteffaniak/go-logger/logger" -) - -// settingsGetHandler retrieves the current system settings. -// @Summary Get system settings -// @Description Returns the current configuration settings for signup, user directories, rules, frontend. -// @Tags Settings -// @Accept json -// @Produce json -// @Param property query string false "Property to retrieve: `userDefaults`, `frontend`, `auth`, `server`, `sources`" -// @Success 200 {object} settings.Settings "System settings data" -// @Router /api/settings [get] -func settingsGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - property := r.URL.Query().Get("property") - if property != "" { - // get property by name - switch property { - case "userDefaults": - return renderJSON(w, r, config.UserDefaults) - case "frontend": - return renderJSON(w, r, config.Frontend) - case "auth": - return renderJSON(w, r, config.Auth) - case "server": - return renderJSON(w, r, config.Server) - case "sources": - return renderJSON(w, r, config.Server.Sources) - default: - return http.StatusNotFound, nil - } - } - return renderJSON(w, r, config) -} - -// settingsConfigHandler returns the current system settings as YAML. -// @Summary Get system settings as YAML -// @Description Returns the current running configuration settings as YAML format with optional comments and filtering. -// @Tags Settings -// @Accept json -// @Produce text/plain -// @Param full query boolean false "Show all values (true) or only non-default values (false, default)" -// @Param comments query boolean false "Include comments in YAML (true) or plain YAML (false, default)" -// @Success 200 {string} string "System settings in YAML format" -// @Router /api/settings/config [get] -func settingsConfigHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - // Parse query parameters - fullParam := r.URL.Query().Get("full") - commentsParam := r.URL.Query().Get("comments") - - showFull := fullParam == "true" - showComments := commentsParam == "true" - - var err error - var yamlConfig string - - // Try to read the generated YAML file for comments (should always exist) - var embeddedYaml []byte - var readErr error - - if settings.Env.EmbeddedFs { - embeddedYaml, readErr = assets.ReadFile("embed/config.generated.yaml") - } else { - embeddedYaml, readErr = os.ReadFile("http/dist/config.generated.yaml") - if readErr != nil { - return http.StatusInternalServerError, fmt.Errorf("error reading generated YAML: %v", readErr) - } - } - - // If we successfully read the generated YAML, use it as the comment source - if readErr == nil && len(embeddedYaml) > 0 { - yamlConfig, err = settings.GenerateConfigYamlWithEmbedded(config, showComments, showFull, false, string(embeddedYaml)) - if err != nil { - return http.StatusInternalServerError, fmt.Errorf("error generating YAML: %v", err) - } - } else { - // Fallback to Go source parsing if generated YAML doesn't exist - yamlConfig, err = settings.GenerateConfigYaml(config, showComments, showFull, false) - if err != nil { - return http.StatusInternalServerError, fmt.Errorf("error generating YAML: %v", err) - } - } - - // Set content type and write response - w.Header().Set("Content-Type", "text/plain; charset=utf-8") - if _, err := w.Write([]byte(yamlConfig)); err != nil { - return http.StatusInternalServerError, err - } - - return http.StatusOK, nil -} - -func getSourceInfoHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - sources := d.user.GetSourceNames() - reducedIndexes := map[string]indexing.ReducedIndex{} - for _, source := range sources { - reducedIndex, err := indexing.GetIndexInfo(source, false) - if err != nil { - logger.Debugf("error getting index info: %v", err) - continue - } - showScannerInfo := r.URL.Query().Get("scanners") == "true" - if !showScannerInfo { - reducedIndex.Scanners = nil - } - reducedIndexes[source] = reducedIndex - } - return renderJSON(w, r, reducedIndexes) -} diff --git a/backend/http/share.go b/backend/http/share.go deleted file mode 100644 index e9b6bd94dc..0000000000 --- a/backend/http/share.go +++ /dev/null @@ -1,777 +0,0 @@ -package http - -import ( - "crypto/hmac" - "crypto/rand" - "crypto/sha256" - "encoding/base64" - "encoding/json" - "fmt" - "net/http" - "net/url" - "path/filepath" - "strconv" - "strings" - "time" - - "golang.org/x/crypto/bcrypt" - - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/share" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/filebrowser/backend/indexing" - "github.com/gtsteffaniak/go-logger/logger" -) - -// ShareResponse represents a share with computed username field and download URL -type ShareResponse struct { - *share.Link - Source string `json:"source"` // Override embedded field to show source name - Username string `json:"username,omitempty"` - PathExists bool `json:"pathExists"` -} - -// convertToFrontendShareResponse converts shares to response format with usernames -func convertToFrontendShareResponse(r *http.Request, shares []*share.Link, user *users.User) ([]*ShareResponse, error) { - responses := make([]*ShareResponse, 0, len(shares)) - for _, s := range shares { - // Look for the username of the user who created the share - creator, err := store.Users.Get(s.UserID) - username := "" - if err == nil { - username = creator.Username - } - - // Get source info to convert path to name for frontend - sourceInfo, ok := config.Server.SourceMap[s.Source] - if !ok { - // Source not found - likely corrupted data. Try to find by name as fallback - sourceInfo, ok = config.Server.NameToSource[s.Source] - if !ok { - continue - } - // Found by name - this is corrupted data, fix it - logger.Warning("Share has corrupted source - fixing", "hash", s.Hash, "from", s.Source, "to", sourceInfo.Path) - s.Source = sourceInfo.Path - _ = store.Share.Save(s) // Best effort fix - } - - // Check if the path exists on the filesystem - pathExists := utils.CheckPathExists(filepath.Join(sourceInfo.Path, s.Path)) - - s.CommonShare.HasPassword = s.HasPassword() - s.DownloadURL = getShareURL(r, s.Hash, true, s.Token) - s.ShareURL = getShareURL(r, s.Hash, false, s.Token) - if s.UserCanEdit(user) { - s.CommonShare.SourceURL = s.SourceURL(user) - } - // Create response with source name (overrides the embedded Link's source field) - responses = append(responses, &ShareResponse{ - Link: s, - Source: sourceInfo.Name, // Override to show source name instead of backend path - Username: username, - PathExists: pathExists, - }) - } - return responses, nil -} - -// shareListHandler returns a list of all share links. -// @Summary List share links -// @Description Returns a list of share links for the current user, or all links if the user is an admin. -// @Tags Shares -// @Accept json -// @Produce json -// @Success 200 {array} share.Link "List of share links" -// @Failure 500 {object} map[string]string "Internal server error" -// @Router /api/share/list [get] -func shareListHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - var err error - var shares []*share.Link - if d.user.Permissions.Admin { - shares, err = store.Share.All() - } else { - shares, err = store.Share.FindByUserID(d.user.ID) - } - if err != nil && err != errors.ErrNotExist { - return http.StatusInternalServerError, err - } - shares = utils.NonNilSlice(shares) - sharesWithUsernames, err := convertToFrontendShareResponse(r, shares, d.user) - if err != nil { - return http.StatusInternalServerError, err - } - return renderJSON(w, r, sharesWithUsernames) -} - -// shareGetsHandler retrieves share links for a specific resource path. -// @Summary Get share links by path -// @Description Retrieves all share links associated with a specific resource path for the current user. -// @Tags Shares -// @Accept json -// @Produce json -// @Param path query string true "Resource path for which to retrieve share links" -// @Param source query string true "Source name for share links" -// @Success 200 {array} share.Link "List of share links for the specified path" -// @Failure 500 {object} map[string]string "Internal server error" -// @Router /api/share [get] -func shareGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - path := r.URL.Query().Get("path") - sourceName := r.URL.Query().Get("source") - sourceInfo, ok := config.Server.NameToSource[sourceName] // backend source is path - if !ok { - return http.StatusBadRequest, fmt.Errorf("invalid source name: %s", sourceName) - } - userscope, err := d.user.GetScopeForSourceName(sourceName) - if err != nil { - return http.StatusForbidden, err - } - scopePath := utils.JoinPathAsUnix(userscope, path) - scopePath = utils.AddTrailingSlashIfNotExists(scopePath) - s, err := store.Share.Gets(scopePath, sourceInfo.Path, d.user.ID) - if err == errors.ErrNotExist || len(s) == 0 { - return renderJSON(w, r, []*ShareResponse{}) - } - // DownloadURL will be set in convertToFrontendShareResponse - - if err != nil { - return http.StatusInternalServerError, fmt.Errorf("error getting share info from server") - } - sharesWithUsernames, err := convertToFrontendShareResponse(r, s, d.user) - if err != nil { - return http.StatusInternalServerError, err - } - return renderJSON(w, r, sharesWithUsernames) -} - -// shareDeleteHandler deletes a specific share link by its hash. -// @Summary Delete a share link -// @Description Deletes a share link specified by its hash. -// @Tags Shares -// @Accept json -// @Produce json -// @Param hash query string true "Hash of the share link to delete" -// @Success 200 "Share link deleted successfully" -// @Failure 400 {object} map[string]string "Bad request - missing or invalid hash" -// @Failure 500 {object} map[string]string "Internal server error" -// @Router /api/share [delete] -func shareDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - hash := r.URL.Query().Get("hash") - - if hash == "" { - return http.StatusBadRequest, nil - } - - // only allow users to delete their own shares - thisShare, err := store.Share.GetByHash(hash) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("share not found") - } - if thisShare.UserID != d.user.ID && !d.user.Permissions.Admin { - return http.StatusForbidden, fmt.Errorf("you are not allowed to delete this share") - } - - err = store.Share.Delete(hash) - if err != nil { - return errToStatus(err), err - } - - return errToStatus(err), err -} - -// sharePatchHandler updates a share link's path. -// @Summary Update share link path -// @Description Updates the path for a specific share link identified by hash -// @Tags Shares -// @Accept json -// @Produce json -// @Param body body object{hash=string,path=string} true "Hash and new path" -// @Success 200 {object} ShareResponse "Updated share link" -// @Failure 400 {object} map[string]string "Bad request - missing or invalid parameters" -// @Failure 500 {object} map[string]string "Internal server error" -// @Router /api/share [patch] -func sharePatchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - var body struct { - Hash string `json:"hash"` - Path string `json:"path"` - } - - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - return http.StatusBadRequest, fmt.Errorf("failed to decode body: %w", err) - } - defer r.Body.Close() - - if body.Hash == "" || body.Path == "" { - return http.StatusBadRequest, fmt.Errorf("hash and path are required") - } - - sanitizedPath, err := utils.SanitizeUserPath(body.Path) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("invalid path: %w", err) - } - body.Path = sanitizedPath - - // only allow users to update their own shares - thisShare, err := store.Share.GetByHash(body.Hash) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("share not found") - } - if thisShare.UserID != d.user.ID && !d.user.Permissions.Admin { - return http.StatusForbidden, fmt.Errorf("you are not allowed to update this share") - } - // Update the share path - err = store.Share.UpdateSharePath(body.Hash, sanitizedPath) - if err != nil { - return http.StatusInternalServerError, err - } - - // Get the updated share - updatedShare, err := store.Share.GetByHash(body.Hash) - if err != nil { - return http.StatusInternalServerError, err - } - - // Convert to response format - sharesWithUsernames, err := convertToFrontendShareResponse(r, []*share.Link{updatedShare}, d.user) - if err != nil { - return http.StatusInternalServerError, err - } - - return renderJSON(w, r, sharesWithUsernames[0]) -} - -// sharePostHandler creates a new share link. -// @Summary Create a share link -// @Description Creates a new share link with an optional expiration time and password protection. -// @Tags Shares -// @Accept json -// @Produce json -// @Param body body share.CreateBody true "Share creation parameters" -// @Success 200 {object} share.Link "Created share link" -// @Failure 400 {object} map[string]string "Bad request - failed to decode body" -// @Failure 500 {object} map[string]string "Internal server error" -// @Router /api/share [post] -func sharePostHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - var s *share.Link - var err error - var body share.CreateBody - if r.Body != nil { - if err = json.NewDecoder(r.Body).Decode(&body); err != nil { - return http.StatusBadRequest, fmt.Errorf("failed to decode body: %w", err) - } - defer r.Body.Close() - } - - // check if body.Hash is a valid hash - if body.Hash != "" { - s, err = store.Share.GetByHash(body.Hash) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("invalid hash provided") - } - } - - var expire int64 = 0 - - if body.Expires != "" { - var num int - num, err = strconv.Atoi(body.Expires) - if err != nil { - return http.StatusInternalServerError, err - } - - var add time.Duration - switch body.Unit { - case "seconds": - add = time.Second * time.Duration(num) - case "minutes": - add = time.Minute * time.Duration(num) - case "days": - add = time.Hour * 24 * time.Duration(num) - default: - add = time.Hour * time.Duration(num) - } - - expire = time.Now().Add(add).Unix() - } - - hash, status, err := getSharePasswordHash(body) - if err != nil { - return status, err - } - stringHash := "" - var token string - if len(hash) > 0 { - // Generate a cryptographically secure token similar to JWT - // Create a random payload - payloadBuffer := make([]byte, 24) - if _, err = rand.Read(payloadBuffer); err != nil { - return http.StatusInternalServerError, err - } - payload := base64.URLEncoding.EncodeToString(payloadBuffer) - - // Sign the payload with HMAC-SHA256 using the same secret key as JWT tokens - mac := hmac.New(sha256.New, []byte(config.Auth.Key)) - mac.Write([]byte(payload)) - signature := base64.URLEncoding.EncodeToString(mac.Sum(nil)) - - // Combine payload and signature: payload.signature (similar to JWT format) - token = payload + "." + signature - stringHash = string(hash) - } - if s != nil { - // Check if downloads limit or per-user limit changed - reset counts if so - shouldResetCounts := s.DownloadsLimit != body.DownloadsLimit || s.PerUserDownloadLimit != body.PerUserDownloadLimit - - s.Expire = expire - s.PasswordHash = stringHash - s.Token = token - // Preserve immutable fields for updates. Path and Source should not change on edits. - // If the request attempts to provide empty values (or any values) for these, - // keep the existing ones from the stored share. - body.Path = s.Path - body.Source = s.Source - s.CommonShare = body.CommonShare - if s.ShareType == "upload" && !body.AllowCreate { - s.AllowCreate = true - } - - // Reset download counts if limit settings changed - if shouldResetCounts { - s.ResetDownloadCounts() - } - - if err = store.Share.Save(s); err != nil { - return http.StatusInternalServerError, err - } - // Convert to ShareResponse format with username - var user *users.User - user, err = store.Users.Get(s.UserID) - username := "" - if err == nil { - username = user.Username - } - response := &ShareResponse{ - Link: s, - Username: username, - } - return renderJSON(w, r, response) - } - - source, ok := config.Server.NameToSource[body.Source] - if !ok { - return http.StatusForbidden, fmt.Errorf("source with name not found: %s", body.Source) - } - - if source.Config.Private { - return http.StatusForbidden, fmt.Errorf("the target source is private, sharing is not permitted") - } - - // create a new share link - secure_hash, err := generateShortUUID() - if err != nil { - return http.StatusInternalServerError, err - } - // validate source path exists - idx := indexing.GetIndex(source.Name) - if idx == nil { - return http.StatusForbidden, fmt.Errorf("source with name not found: %s", body.Source) - } - userscope, err := d.user.GetScopeForSourceName(source.Name) - if err != nil { - return http.StatusForbidden, err - } - providedPath := body.Path - - // Rule 1: Validate user-provided path to prevent path traversal - cleanPath, err := utils.SanitizeUserPath(providedPath) - if err != nil { - return http.StatusBadRequest, err - } - - body.Path = utils.JoinPathAsUnix(userscope, cleanPath) - body.Path = utils.AddTrailingSlashIfNotExists(body.Path) - // validate path exists as file or folder - _, _, err = idx.GetRealPath(body.Path) - if err != nil { - return http.StatusForbidden, fmt.Errorf("path not found: %s", providedPath) - } - - if body.ShareType == "upload" && !body.AllowCreate { - body.AllowCreate = true - } - body.Source = source.Path // backend source is path - s = &share.Link{ - Expire: expire, - UserID: d.user.ID, - Hash: secure_hash, - PasswordHash: stringHash, - Token: token, - CommonShare: body.CommonShare, - Version: 1, // Set version for new shares - } - if err = store.Share.Save(s); err != nil { - return http.StatusInternalServerError, err - } - sharesWithUsernames, err := convertToFrontendShareResponse(r, []*share.Link{s}, d.user) - if err != nil { - return http.StatusInternalServerError, err - } - return renderJSON(w, r, sharesWithUsernames[0]) -} - -// DirectDownloadResponse represents the response for direct download endpoint -type DirectDownloadResponse struct { - Status string `json:"status"` - Hash string `json:"hash"` - DownloadURL string `json:"url"` - ShareURL string `json:"shareUrl"` -} - -// shareDirectDownloadHandler creates a direct download link for files only. -// @Summary Create direct download link -// @Description Creates a direct download link for a specific file with configurable duration, download count, and speed limits. If a share already exists with matching parameters, the existing share will be reused. -// @Tags Shares -// @Accept json -// @Produce json -// @Param path query string true "File path to create download link for" -// @Param source query string true "Source name for the file" -// @Param duration query string false "Duration in minutes for link validity (default: 60)" -// @Param count query string false "Maximum number of downloads allowed (default: unlimited)" -// @Param speed query string false "Download speed limit in kbps (default: unlimited)" -// @Success 201 {object} DirectDownloadResponse "Direct download link created" -// @Failure 400 {object} map[string]string "Bad request - invalid parameters or path is not a file" -// @Failure 403 {object} map[string]string "Forbidden - access denied" -// @Failure 500 {object} map[string]string "Internal server error" -// @Router /api/share/direct [get] -func shareDirectDownloadHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - // Extract query parameters - path := r.URL.Query().Get("path") - source := r.URL.Query().Get("source") - duration := r.URL.Query().Get("duration") - downloadCountStr := r.URL.Query().Get("count") - downloadSpeedStr := r.URL.Query().Get("speed") - - // Validate required parameters - if path == "" || source == "" { - return http.StatusBadRequest, fmt.Errorf("path and source are required") - } - - // Validate source exists - sourceInfo, ok := config.Server.NameToSource[source] - if !ok { - return http.StatusBadRequest, fmt.Errorf("invalid source name: %s", source) - } - - // Get user scope for this source - userscope, err := d.user.GetScopeForSourceName(source) - if err != nil { - return http.StatusForbidden, err - } - - // Validate the path exists and is a file (not a folder) - idx := indexing.GetIndex(source) - if idx == nil { - return http.StatusForbidden, fmt.Errorf("source with name not found: %s", source) - } - - metadata, exists := idx.GetReducedMetadata(path, false) - if !exists { - return http.StatusBadRequest, fmt.Errorf("path is either not a file or not found: %s", path) - } - - // Check if it's a file (not a directory) - if metadata.Type == "directory" { - return http.StatusBadRequest, fmt.Errorf("path must be a file, not a directory: %s", path) - } - - // Set default duration to 60 minutes if not provided - if duration == "" { - duration = "60" - } - - // Parse download count - var downloadCount int - if downloadCountStr != "" { - downloadCount, err = strconv.Atoi(downloadCountStr) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("invalid downloadCount: %v", err) - } - } - - // Parse download speed (in bytes per second) - var downloadSpeed int - if downloadSpeedStr != "" { - downloadSpeed, err = strconv.Atoi(downloadSpeedStr) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("invalid downloadSpeed: %v", err) - } - } - - // Calculate expiration time - durationNum, err := strconv.Atoi(duration) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("invalid duration: %v", err) - } - expire := time.Now().Add(time.Minute * time.Duration(durationNum)).Unix() - - // Generate secure hash for the share - secureHash, err := generateShortUUID() - if err != nil { - return http.StatusInternalServerError, err - } - - // Create the scope path - scopePath := utils.JoinPathAsUnix(userscope, path) - - // Check if an existing share already matches these parameters - existingShares, err := store.Share.Gets(scopePath, sourceInfo.Path, d.user.ID) - if err == nil && len(existingShares) > 0 { - // Look for a share that matches our parameters - for _, existing := range existingShares { - if existing.DownloadsLimit == downloadCount && - existing.MaxBandwidth == downloadSpeed && - existing.QuickDownload && - (existing.Expire == 0 || existing.Expire >= expire) { // Existing expires later or never - - response := DirectDownloadResponse{ - Status: "201", - Hash: existing.Hash, - DownloadURL: getShareURL(r, existing.Hash, true, existing.Token), - ShareURL: getShareURL(r, existing.Hash, false, existing.Token), - } - return renderJSON(w, r, response) - } - } - } - - // No matching existing share found, create a new one - shareLink := &share.Link{ - Expire: expire, - UserID: d.user.ID, - Hash: secureHash, - Version: 1, // Set version for new shares - CommonShare: share.CommonShare{ - Path: scopePath, - Source: idx.Path, - DownloadsLimit: downloadCount, - MaxBandwidth: downloadSpeed, - QuickDownload: true, // Enable quick download for direct downloads - }, - } - - // Save the share - if err := store.Share.Save(shareLink); err != nil { - return http.StatusInternalServerError, err - } - - // Return response - response := DirectDownloadResponse{ - Status: "200", - Hash: secureHash, - DownloadURL: getShareURL(r, secureHash, true, shareLink.Token), - ShareURL: getShareURL(r, secureHash, false, shareLink.Token), - } - - return renderJSON(w, r, response) -} - -func getShareURL(r *http.Request, hash string, isDirectDownload bool, token string) string { - var shareURL string - tokenParam := "" - if token != "" && isDirectDownload { - tokenParam = fmt.Sprintf("&token=%s", url.QueryEscape(token)) - } - - if config.Server.ExternalUrl != "" { - if isDirectDownload { - shareURL = fmt.Sprintf("%s%spublic/api/resources/download?hash=%s%s", config.Server.ExternalUrl, config.Server.BaseURL, hash, tokenParam) - } else { - shareURL = fmt.Sprintf("%s%spublic/share/%s", config.Server.ExternalUrl, config.Server.BaseURL, hash) - } - - } else { - // Prefer X-Forwarded-Host for proxy support - var host string - var scheme string - if forwardedHost := r.Header.Get("X-Forwarded-Host"); forwardedHost != "" { - host = forwardedHost - // Use X-Forwarded-Proto if available, otherwise default to https for proxied requests - if forwardedProto := r.Header.Get("X-Forwarded-Proto"); forwardedProto != "" { - scheme = forwardedProto - } else { - scheme = "https" - } - } else { - // Fallback to simple approach - host = r.Host - scheme = getScheme(r) - } - if isDirectDownload { - shareURL = fmt.Sprintf("%s://%s%spublic/api/resources/download?hash=%s%s", scheme, host, config.Server.BaseURL, hash, tokenParam) - } else { - shareURL = fmt.Sprintf("%s://%s%spublic/share/%s", scheme, host, config.Server.BaseURL, hash) - } - } - return shareURL -} - -// shareInfoHandler retrieves share information by hash. -// @Summary Get share information by hash -// @Description Returns information about a share link based on its hash. This endpoint is publicly accessible and can be used with or without authentication. -// @Tags Shares -// @Accept json -// @Produce json -// @Param hash query string true "Hash of the share link" -// @Success 200 {object} share.CommonShare "Share information" -// @Failure 404 {object} map[string]string "Share hash not found" -// @Router /public/api/share/info [get] -func shareInfoHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - hash := r.URL.Query().Get("hash") - // Get the file link by hash (need full Link to get Token) - shareLink, err := store.Share.GetByHash(hash) - if err != nil { - return http.StatusNotFound, fmt.Errorf("share hash not found") - } - commonShare := shareLink.CommonShare - commonShare.ShareURL = getShareURL(r, hash, false, "") - commonShare.BannerUrl = shareLink.BannerURL() - commonShare.FaviconUrl = shareLink.FaviconURL() - commonShare.Source = "" - commonShare.Path = "" - commonShare.DownloadURL = "" - commonShare.SidebarLinks = []users.SidebarLink{} - for _, link := range shareLink.SidebarLinks { - if link.Category == "download" && shareLink.ShareType == "upload" { - continue - } else { - commonShare.SidebarLinks = append(commonShare.SidebarLinks, link) - } - } - commonShare.SourceURL = shareLink.SourceURL(d.user) - commonShare.CanEditShare = shareLink.UserCanEdit(d.user) - if commonShare.SourceURL != "" { - link := users.SidebarLink{ - Name: "sourceLocation", - Category: "custom", - Target: commonShare.SourceURL, - } - commonShare.SidebarLinks = append(commonShare.SidebarLinks, link) - } - - return renderJSON(w, r, commonShare) -} - -func getSharePasswordHash(body share.CreateBody) (data []byte, statuscode int, err error) { - if body.Password == "" { - return nil, 0, nil - } - - hash, err := bcrypt.GenerateFromPassword([]byte(body.Password), bcrypt.DefaultCost) - if err != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("failed to hash password") - } - - return hash, 0, nil -} - -func generateShortUUID() (string, error) { - // Generate 16 random bytes (128 bits of entropy) - bytes := make([]byte, 16) - _, err := rand.Read(bytes) - if err != nil { - return "", err - } - - // Encode the bytes to a URL-safe base64 string - uuid := base64.RawURLEncoding.EncodeToString(bytes) - - // Trim the length to 22 characters for a shorter ID - return uuid[:22], nil -} - -func redirectToShare(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - // Remove the base URL and "/share/" prefix to get the full path after share - sharePath := strings.TrimPrefix(r.URL.Path, config.Server.BaseURL+"share/") - newURL := config.Server.BaseURL + "public/share/" + sharePath - if r.URL.RawQuery != "" { - newURL += "?" + r.URL.RawQuery - } - http.Redirect(w, r, newURL, http.StatusMovedPermanently) - return http.StatusMovedPermanently, nil -} - -// publicSharePatchPinnedItemsHandler adds or removes a pinned item on a share link. -// @Summary Add or remove a pinned item on a share -// @Description Patches one pinned item at a time for share owners. Defaults to add; pass ?action=remove to unpin. -// @Tags Shares -// @Accept json -// @Produce json -// @Param hash query string true "Share hash" -// @Param action query string false "add (default) or remove" -// @Param body body sharePinnedItemPatchRequest true "Pinned item" -// @Success 204 "No Content" -// @Failure 400 {object} map[string]string "Bad Request" -// @Failure 403 {object} map[string]string "Forbidden" -// @Failure 404 {object} map[string]string "Share not found" -// @Failure 500 {object} map[string]string "Internal Server Error" -// @Router /public/api/share/pinnedItems [patch] -func sharePatchPinnedItemsHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - hash := r.URL.Query().Get("hash") - if hash == "" { - return http.StatusBadRequest, fmt.Errorf("hash is required") - } - - link, err := store.Share.GetByHash(hash) - if err != nil { - return http.StatusNotFound, fmt.Errorf("share hash not found") - } - - if d.user.Username == "anonymous" || !link.UserCanEdit(d.user) { - return http.StatusForbidden, fmt.Errorf("share pin editing is not allowed for this user") - } - - if link.ShareType == "upload" { - return http.StatusForbidden, fmt.Errorf("pinning is disabled for upload shares") - } - - var body sharePinnedItemPatchRequest - if err = json.NewDecoder(r.Body).Decode(&body); err != nil { - return http.StatusBadRequest, fmt.Errorf("failed to decode body: %w", err) - } - defer r.Body.Close() - - action := pinnedItemAction(r) - if action != "add" && action != "remove" { - return http.StatusBadRequest, fmt.Errorf("action must be add or remove") - } - - if body.Path == "" || body.Name == "" { - return http.StatusBadRequest, fmt.Errorf("path and name are required") - } - - shareRelDir, err := normalizeShareRelativeDir(body.Path) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("invalid path: %s", body.Path) - } - - cleanName, err := utils.SanitizeUserPath(body.Name) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("invalid name: %s", body.Name) - } - body.Name = cleanName - - pinned := link.EnsurePinnedItems() - switch action { - case "add": - pinned.Add(shareRelDir, body.Name) - case "remove": - pinned.Remove(shareRelDir, body.Name) - } - - if err := store.Share.Save(link); err != nil { - return http.StatusInternalServerError, fmt.Errorf("failed to save share: %w", err) - } - - return http.StatusNoContent, nil -} diff --git a/backend/http/totp_test.go b/backend/http/totp_test.go deleted file mode 100644 index 7dd6780977..0000000000 --- a/backend/http/totp_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package http - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "net/url" - "testing" - "time" - - "github.com/gtsteffaniak/filebrowser/backend/auth" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/pquerna/otp/totp" -) - -func otpRequest(username, password, code string) *http.Request { - req := httptest.NewRequest(http.MethodPost, "/api/auth/otp?username="+username, http.NoBody) - req.Header.Set("X-Password", password) - if code != "" { - req.Header.Set("X-Secret", code) - } - return req -} - -func TestVerifyOTP_CachedSecretTakesPrecedence(t *testing.T) { - setupTestEnv(t) - - oldSecret := "SOMEOLDSECRET234" - user := &users.User{ - ID: 1, - Username: "test", - NonAdminEditable: users.NonAdminEditable{Password: "testPass"}, - TOTPSecret: oldSecret, - OtpEnabled: true, - } - if err := store.Users.Save(user, true, true); err != nil { - t.Fatalf("failed to save user: %v", err) - } - t.Cleanup(func() { auth.TotpCache.Delete(user.Username) }) - - d := &requestContext{user: user} - - rec := httptest.NewRecorder() - if _, err := generateOTPHandler(rec, otpRequest(user.Username, "testPass", ""), d); err != nil { - t.Fatalf("genration failed: %v", err) - } - var resp map[string]string - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("failed to decode response: %v", err) - } - u, err := url.Parse(resp["url"]) - if err != nil { - t.Fatalf("failed to parse url: %v", err) - } - newSecret := u.Query().Get("secret") - if newSecret == oldSecret { - t.Fatal("expected a fresh secret") - } - oldCode, err := totp.GenerateCode(oldSecret, time.Now()) - if err != nil { - t.Fatalf("failed to generate old code: %v", err) - } - if _, verifyErr := verifyOTPHandler(httptest.NewRecorder(), otpRequest(user.Username, "testPass", oldCode), d); verifyErr == nil { - t.Error("expected old secret to be rejected") - } - newCode, err := totp.GenerateCode(newSecret, time.Now()) - if err != nil { - t.Fatalf("failed to generate new code: %v", err) - } - if _, verifyErr := verifyOTPHandler(httptest.NewRecorder(), otpRequest(user.Username, "testPass", newCode), d); verifyErr != nil { - t.Fatalf("expected new secret to be accepted: %v", verifyErr) - } - updated, err := store.Users.Get(user.Username) - if err != nil { - t.Fatalf("failed to reload user: %v", err) - } - if updated.TOTPSecret != newSecret { - t.Error("expected TOTPSecret to be updated to the new secret") - } - if _, found := auth.TotpCache.Get(user.Username); found { - t.Error("expected cache to be cleared after verification") - } -} - -func TestLogin_EnforcedOtp(t *testing.T) { - setupTestEnv(t) - config.Auth.Key = "test-key" - config.Auth.TokenExpirationHours = 1 - config.Auth.Methods.PasswordAuth.EnforcedOtp = true - - user := &users.User{ID: 2, Username: "loginuser", LoginMethod: users.LoginMethodPassword} - d := &requestContext{user: user} - - status, err := loginHandler(httptest.NewRecorder(), otpRequest(user.Username, "", ""), d) - if status != http.StatusForbidden || err != errors.ErrNoTotpConfigured { - t.Fatalf("expected login without TOTP to fail, got=%d err=%v", status, err) - } - - user.TOTPSecret = "SOMESECRET123456" - if _, loginErr := loginHandler(httptest.NewRecorder(), otpRequest(user.Username, "", ""), d); loginErr != nil { - t.Fatalf("expected login with TOTP to succed, got err=%v", loginErr) - } -} diff --git a/backend/http/users.go b/backend/http/users.go deleted file mode 100644 index 25935b707f..0000000000 --- a/backend/http/users.go +++ /dev/null @@ -1,476 +0,0 @@ -package http - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "reflect" - "slices" - "sort" - "strconv" - "strings" - - "github.com/gtsteffaniak/filebrowser/backend/auth" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/storage" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/go-logger/logger" -) - -type UserRequest struct { - Which []string `json:"which"` - User users.User `json:"data"` -} - -// userGetHandler retrieves a user by ID. -// @Summary Retrieve a user by ID -// @Description Returns a user's details based on their ID, or all users if no id is provided. -// @Tags Users -// @Accept json -// @Produce json -// @Param id query string false "User ID or 'self'" -// @Success 200 {object} users.User "User details or list of users" -// @Failure 403 {object} map[string]string "Forbidden" -// @Failure 404 {object} map[string]string "Not Found" -// @Failure 500 {object} map[string]string "Internal Server Error" -// @Router /api/users [get] -func userGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - givenUserIdString := r.URL.Query().Get("id") - - // since api self is used to validate a logged in user - w.Header().Add("X-Renew-Token", "false") - - var givenUserId uint - if givenUserIdString == "self" { - givenUserId = d.user.ID - } else if givenUserIdString == "" { - - userList, err := store.Users.Gets() - if err != nil { - return http.StatusInternalServerError, err - } - - selfUserList := []*users.User{} - for _, u := range userList { - prepForFrontend(u) - if u.ID == d.user.ID { - selfUserList = append(selfUserList, u) - } - } - - sort.Slice(userList, func(i, j int) bool { - return userList[i].ID < userList[j].ID - }) - - if !d.user.Permissions.Admin { - userList = selfUserList - } - return renderJSON(w, r, userList) - } else { - num, _ := strconv.ParseUint(givenUserIdString, 10, 32) - givenUserId = uint(num) - } - - if givenUserId != d.user.ID && !d.user.Permissions.Admin { - return http.StatusForbidden, nil - } - - // Fetch the user details - u, err := store.Users.Get(givenUserId) - if err == errors.ErrNotExist { - return http.StatusNotFound, err - } - if err != nil { - return http.StatusInternalServerError, err - } - prepForFrontend(u) - return renderJSON(w, r, u) -} - -// prepForFrontend strips secrets and maps source identifiers to display names for JSON (never expose paths). -func prepForFrontend(u *users.User) { - u.Password = "" - u.ApiKeys = nil - u.Tokens = nil - u.OtpEnabled = u.TOTPSecret != "" - u.TOTPSecret = "" - u.TOTPNonce = "" - u.Scopes = u.GetFrontendScopes() - u.SidebarLinks = GetFrontendSidebarLinks(u.SidebarLinks, u.ShowToolsInSidebar) - u.PinnedItems = nil - u.Locale = normalizeLocale(u.Locale) - for i := range u.PasskeyCredentials { - u.PasskeyCredentials[i].PublicKey = "" - u.PasskeyCredentials[i].AttestationType = "" - u.PasskeyCredentials[i].AttestationFormat = "" - u.PasskeyCredentials[i].Flags = users.WebAuthnCredentialFlags{} - u.PasskeyCredentials[i].SignCount = 0 - u.PasskeyCredentials[i].ClientDataJSON = "" - u.PasskeyCredentials[i].ClientDataHash = "" - u.PasskeyCredentials[i].AuthenticatorData = "" - u.PasskeyCredentials[i].PublicKeyAlg = 0 - u.PasskeyCredentials[i].AttestationObj = "" - } -} - -// GetFrontendSidebarLinks converts the user's sidebar links from backend-style to frontend-style: -func GetFrontendSidebarLinks(links []users.SidebarLink, showToolsInSidebar bool) []users.SidebarLink { - if !users.SourceConfigLoaded() { - return []users.SidebarLink{} - } - hasTools := false - newLinks := []users.SidebarLink{} - for _, link := range links { - if strings.HasPrefix(link.Category, "source") { - if link.SourceName == "" { - continue - } - source, ok := users.ResolveSourceKey(link.SourceName) - if !ok { - continue - } - if full, ok := config.Server.SourceMap[source.Path]; ok { - if full.Config.ResolvedRules.IndexingDisabled && link.Category != "source-minimal" { - link.Category = "source-alt" - } - } - link.SourceName = source.Name - } else if link.Category == "tool" && link.Target == "/tools" { - hasTools = true - } - newLinks = append(newLinks, link) - } - if !hasTools && showToolsInSidebar { - newLinks = append(newLinks, users.SidebarLink{ - Name: "Tools", - Category: "tool", - Target: "/tools", - Icon: "build", - }) - } - return newLinks -} - -// normalizeLocale converts various locale formats (xx_xx, xx-xx, xxxx) to camelCase format (xxXX) -// Frontend expects camelCase for compound locales (zhCN, ptBR, etc.) as shown in select option values -func normalizeLocale(locale string) string { - if locale == "" { - return locale - } - - // Convert to lowercase for processing - lower := strings.ToLower(locale) - - // Special case mappings (standard locale codes to frontend camelCase format) - specialCases := map[string]string{ - "cs": "cz", // Czech - "uk": "ua", // Ukrainian - "zh-cn": "zhCN", - "zh_cn": "zhCN", - "zhcn": "zhCN", - "zh-tw": "zhTW", - "zh_tw": "zhTW", - "zhtw": "zhTW", - "pt-br": "ptBR", - "pt_br": "ptBR", - "ptbr": "ptBR", - "sv-se": "svSE", - "sv_se": "svSE", - "svse": "svSE", - "nl-be": "nlBE", - "nl_be": "nlBE", - "nlbe": "nlBE", - } - - // Check special cases first - if normalized, ok := specialCases[lower]; ok { - return normalized - } - - // If already in camelCase format (4+ chars, has uppercase), return as-is - if len(locale) >= 4 { - // Check if it's a known camelCase locale - knownCamelCase := map[string]bool{ - "zhCN": true, "zhTW": true, "ptBR": true, "svSE": true, "nlBE": true, - } - if knownCamelCase[locale] { - return locale - } - } - - // Handle xx_xx or xx-xx format: convert to xxXX (camelCase) - parts := strings.FieldsFunc(lower, func(r rune) bool { - return r == '_' || r == '-' - }) - - if len(parts) == 2 { - // Convert to camelCase: first part lowercase, second part capitalized - first := parts[0] - second := parts[1] - if len(second) > 0 { - second = strings.ToUpper(second[:1]) + second[1:] - } - normalized := first + second - - // Check if this matches a known compound locale - knownCompound := map[string]string{ - "zhcn": "zhCN", "zhtw": "zhTW", "ptbr": "ptBR", - "svse": "svSE", "nlbe": "nlBE", - } - if normalizedVal, ok := knownCompound[normalized]; ok { - return normalizedVal - } - return normalized - } - - // Single part locale (en, fr, de, etc.) - return as-is (lowercase is fine) - return lower -} - -// userDeleteHandler deletes a user by ID. -// @Summary Delete a user by ID -// @Description Deletes a user identified by their ID. When the authenticated actor uses password login, they must send their current password in the X-Password header. -// @Tags Users -// @Accept json -// @Produce json -// @Param id query string true "User ID" -// @Param X-Password header string false "Actor's current password (URL-encoded); required for password-login actors" -// @Success 200 "User deleted successfully" -// @Failure 401 {object} map[string]string "Unauthorized - invalid or missing actor password when required" -// @Failure 403 {object} map[string]string "Forbidden" -// @Failure 500 {object} map[string]string "Internal Server Error" -// @Router /api/users [delete] -func userDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - givenUserIdString := r.URL.Query().Get("id") - num, _ := strconv.ParseUint(givenUserIdString, 10, 32) - givenUserId := uint(num) - - if givenUserId == d.user.ID { - return http.StatusForbidden, fmt.Errorf("cannot delete your own user") - } - - if !d.user.Permissions.Admin { - return http.StatusForbidden, fmt.Errorf("cannot delete users without admin permissions") - } - - status, err := verifyActorPasswordForUserActions(r, d) - if err != nil { - return status, err - } - - // Delete the user - err = store.Users.Delete(givenUserId) - if err != nil { - return errToStatus(err), err - } - return http.StatusOK, nil -} - -// usersPostHandler creates a new user. -// @Summary Create a new user -// @Description Adds a new user to the system. When the authenticated actor uses password login, they must send their current password in the X-Password header. -// @Tags Users -// @Accept json -// @Produce json -// @Param X-Password header string false "Actor's current password (URL-encoded); required for password-login actors" -// @Param data body users.User true "User data to create a new user" -// @Success 201 {object} users.User "Created user" -// @Failure 400 {object} map[string]string "Bad Request" -// @Failure 401 {object} map[string]string "Unauthorized - invalid or missing actor password when required" -// @Failure 500 {object} map[string]string "Internal Server Error" -// @Router /api/users [post] -func usersPostHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !d.user.Permissions.Admin { - return http.StatusForbidden, nil - } - // Read the JSON body - body, err := io.ReadAll(r.Body) - if err != nil { - return http.StatusInternalServerError, err - } - // Parse the JSON into the UserRequest struct - var req UserRequest - if err = json.Unmarshal(body, &req); err != nil { - return http.StatusBadRequest, err - } - r.Body.Close() - - if req.User.Username == "" { - return http.StatusBadRequest, errors.ErrEmptyUsername - } - - if len(req.Which) != 0 { - return http.StatusBadRequest, nil - } - - if req.User.Password == "" && req.User.LoginMethod == "password" { - return http.StatusBadRequest, errors.ErrEmptyPassword - } - - status, err := verifyActorPasswordForUserActions(r, d) - if err != nil { - return status, err - } - - err = storage.CreateUser(req.User, req.User.Permissions) - if err != nil { - return http.StatusInternalServerError, err - } - - w.Header().Set("Location", "/settings/users/"+strconv.FormatUint(uint64(req.User.ID), 10)) - return http.StatusCreated, nil -} - -// nonAdminEditableFieldNameSet returns User.NonAdminEditable struct field names (e.g. "Locale", "Preview"). -func nonAdminEditableFieldNameSet() map[string]struct{} { - m := make(map[string]struct{}) - t := reflect.TypeOf(users.NonAdminEditable{}) - for i := 0; i < t.NumField(); i++ { - m[t.Field(i).Name] = struct{}{} - } - return m -} - -// userPutOnlyNonAdminEditableFields reports whether req.Which lists exclusively NonAdminEditable fields, -// excluding Password. Empty which or which[0] == "all" means a broad update and returns false. -func userPutOnlyNonAdminEditableFields(which []string) bool { - if len(which) == 0 || strings.EqualFold(strings.TrimSpace(which[0]), "all") { - return false - } - allowed := nonAdminEditableFieldNameSet() - for _, w := range which { - f := utils.CapitalizeFirst(strings.TrimSpace(w)) - if f == "" { - return false - } - if strings.EqualFold(f, "Password") { - return false - } - if _, ok := allowed[f]; !ok { - return false - } - } - return true -} - -// verifyActorPasswordForUserPut requires URL-encoded X-Password when the authenticated actor uses -// password login. Callers should invoke this only when the update requires re-authentication. -func verifyActorPasswordForUserActions(r *http.Request, d *requestContext) (int, error) { - if d.user.LoginMethod != users.LoginMethodPassword { - return 0, nil - } - encoded := r.Header.Get("X-Password") - if encoded == "" { - return http.StatusUnauthorized, fmt.Errorf("X-Password header is required to confirm your password") - } - plain, err := url.QueryUnescape(encoded) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("invalid password encoding") - } - if plain == "" { - return http.StatusUnauthorized, fmt.Errorf("X-Password header is required to confirm your password") - } - actor, err := store.Users.Get(d.user.ID) - if err != nil { - return http.StatusInternalServerError, err - } - if err := utils.CheckPwd(plain, actor.Password); err != nil { - return http.StatusUnauthorized, fmt.Errorf("invalid password") - } - return 0, nil -} - -// userPutHandler updates an existing user's details. -// @Summary Update a user's details -// @Description Updates the details of a user identified by ID. When the authenticated actor uses password login, they must send their current password in the X-Password header unless the update only touches NonAdminEditable profile fields (not password). Full updates (which empty or "all") or any admin-only field require confirmation. -// @Tags Users -// @Accept json -// @Param id query string false "user ID to update" -// @Param id query string false "usename to update" -// @Param X-Password header string false "Actor's current password (URL-encoded); required for password-login actors when updating password, using which=all, or any field outside NonAdminEditable" -// @Param data body users.User true "User data to update" -// @Success 204 "No Content - User updated successfully" -// @Failure 400 {object} map[string]string "Bad Request" -// @Failure 401 {object} map[string]string "Unauthorized - invalid or missing actor password when required" -// @Failure 403 {object} map[string]string "Forbidden" -// @Failure 500 {object} map[string]string "Internal Server Error" -// @Router /api/users [put] -func userPutHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - givenUserIdString := r.URL.Query().Get("id") - username := r.URL.Query().Get("username") - num, _ := strconv.ParseUint(givenUserIdString, 10, 32) - givenUserId := uint(num) - - if givenUserId != d.user.ID && !d.user.Permissions.Admin { - return http.StatusForbidden, nil - } - - // Read the JSON body - body, err := io.ReadAll(r.Body) - if err != nil { - return http.StatusBadRequest, err - } - defer r.Body.Close() - - // Parse the JSON into the UserRequest struct - var req UserRequest - if err = json.Unmarshal(body, &req); err != nil { - return http.StatusBadRequest, err - } - if givenUserId != 0 { - u, err2 := store.Users.Get(givenUserId) - if err2 != nil { - return http.StatusBadRequest, fmt.Errorf("no user not found, please provide a valid id or username") - } - req.User.ID = u.ID - req.User.Username = u.Username - } else { - u, err2 := store.Users.Get(username) - if err2 != nil { - return http.StatusBadRequest, fmt.Errorf("no user not found, please provide a valid id or username") - } - req.User.ID = u.ID - req.User.Username = u.Username - } - if !req.User.OtpEnabled { - req.User.TOTPSecret = "" - req.User.TOTPNonce = "" - } - - // Get the old user to check if permissions changed - oldUser, err := store.Users.Get(req.User.ID) - if err != nil { - return http.StatusBadRequest, fmt.Errorf("failed to get user: %w", err) - } - - if d.user.LoginMethod == users.LoginMethodPassword && !userPutOnlyNonAdminEditableFields(req.Which) { - var status int - status, err = verifyActorPasswordForUserActions(r, d) - if err != nil { - return status, err - } - } - - err = store.Users.Update(&req.User, d.user.Permissions.Admin, req.Which...) - if err != nil { - return http.StatusBadRequest, err - } - - // Revoke all API keys if API permission was removed - if slices.Contains(req.Which, "Permissions") && oldUser.Permissions.Api && !req.User.Permissions.Api { - for _, tokenInfo := range oldUser.Tokens { - if err := auth.RevokeApiToken(store.Access, tokenInfo.Token); err != nil { - logger.Errorf("Failed to revoke API key: %v", err) - } - // Also remove from HashedTokens - if err := store.Access.RemoveApiToken(tokenInfo.Token); err != nil { - logger.Errorf("Failed to remove api token: %v", err) - } - } - } - - return http.StatusNoContent, nil -} diff --git a/backend/http/utils.go b/backend/http/utils.go deleted file mode 100644 index f0893c4ac2..0000000000 --- a/backend/http/utils.go +++ /dev/null @@ -1,32 +0,0 @@ -package http - -import ( - "errors" - "net/http" - "os" - - libErrors "github.com/gtsteffaniak/filebrowser/backend/common/errors" -) - -func errToStatus(err error) int { - switch { - case err == nil: - return http.StatusOK - case os.IsPermission(err): - return http.StatusForbidden - case errors.Is(err, libErrors.ErrAccessDenied): - return http.StatusForbidden - case os.IsNotExist(err), err == libErrors.ErrNotExist: - return http.StatusNotFound - case os.IsExist(err), err == libErrors.ErrExist: - return http.StatusConflict - case errors.Is(err, libErrors.ErrPermissionDenied): - return http.StatusForbidden - case errors.Is(err, libErrors.ErrInvalidRequestParams): - return http.StatusBadRequest - case errors.Is(err, libErrors.ErrIsDirectory): - return http.StatusMethodNotAllowed - default: - return http.StatusInternalServerError - } -} diff --git a/backend/internal/activity/actor.go b/backend/internal/activity/actor.go new file mode 100644 index 0000000000..9ddd837e44 --- /dev/null +++ b/backend/internal/activity/actor.go @@ -0,0 +1,13 @@ +package activity + +import ( + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// Actor carries request-scoped identity for activity recording and filtering. +type Actor struct { + User *users.User + Share share.Share + Token string +} diff --git a/backend/internal/activity/deps.go b/backend/internal/activity/deps.go new file mode 100644 index 0000000000..29efc17793 --- /dev/null +++ b/backend/internal/activity/deps.go @@ -0,0 +1,34 @@ +package activity + +import ( + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + "github.com/gtsteffaniak/filebrowser/backend/internal/ports" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" +) + +// QueryDeps holds access and share dependencies for activity query filtering. +type QueryDeps struct { + Access ports.AccessGate + Shares ports.ShareReader +} + +var queryDeps QueryDeps + +// SetQueryDeps registers access and share ports for activity queries (called from app.WireServices). +func SetQueryDeps(access ports.AccessGate, shares ports.ShareReader) { + queryDeps = QueryDeps{Access: access, Shares: shares} +} + +func accessPermitted(sourcePath string, indexPath utils.IndexPath, username string) bool { + if queryDeps.Access == nil { + return true + } + return queryDeps.Access.AccessPermitted(sourcePath, indexPath, username) +} + +func getShare(hash string) (share.Share, error) { + if queryDeps.Shares == nil { + return share.Share{}, nil + } + return queryDeps.Shares.GetShare(hash) +} diff --git a/backend/internal/activity/diff.go b/backend/internal/activity/diff.go new file mode 100644 index 0000000000..3a77492200 --- /dev/null +++ b/backend/internal/activity/diff.go @@ -0,0 +1,415 @@ +package activity + +import ( + "encoding/json" + "fmt" + "reflect" + "sort" + "strings" + + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/usersidebar" +) + +var userActivitySkipJSONTags = normalizedSkipTags( + "id", + "password", + "totpSecret", + "totpNonce", + "tokens", + "apiKeys", + "backendScopes", + "perm", + "passkeyCredentials", + "version", + "pinnedItems", +) + +var activitySkipStructJSONTags = normalizedSkipTags( + "configured", +) + +var shareActivitySkipJSONTags = normalizedSkipTags( + "hash", + "password_hash", + "token", + "userID", + "userDownloads", + "version", + "sourcePath", + "pinnedItems", + "pathExists", + "downloads", + "username", + "downloadURL", + "shareURL", + "faviconUrl", + "bannerUrl", + "sourceURL", + "canEditShare", + "hasPassword", +) + +func normalizedSkipTags(tags ...string) map[string]struct{} { + out := make(map[string]struct{}, len(tags)) + for _, t := range tags { + out[strings.ToLower(strings.TrimSpace(t))] = struct{}{} + } + return out +} + +func UserUpdateChanges(before, after *users.User, which []string, passwordChanged bool) []activitydb.FieldChange { + if before == nil || after == nil { + return nil + } + fieldNames := normalizeUserWhich(which) + changes := make([]activitydb.FieldChange, 0, len(fieldNames)) + for _, jsonTag := range fieldNames { + tag := strings.TrimSpace(jsonTag) + if tag == "" { + continue + } + if strings.EqualFold(tag, "password") { + if passwordChanged { + changes = append(changes, activitydb.FieldChange{ + Field: "password", + From: "[redacted]", + To: "[changed]", + }) + } + continue + } + if _, skip := userActivitySkipJSONTags[strings.ToLower(tag)]; skip { + continue + } + if strings.EqualFold(tag, "scopes") { + changes = append(changes, scopeFieldChanges(before, after)...) + continue + } + if strings.EqualFold(tag, "backendSourcePermissions") { + changes = append(changes, backendSourcePermissionsFieldChanges(before, after)...) + continue + } + if strings.EqualFold(tag, "sidebarLinks") { + if change, ok := sidebarLinksFieldChange(before, after); ok { + changes = append(changes, change) + } + continue + } + changes = append(changes, structFieldChanges(reflect.ValueOf(before).Elem(), reflect.ValueOf(after).Elem(), reflect.TypeOf(users.User{}), tag)...) + } + sort.Slice(changes, func(i, j int) bool { return changes[i].Field < changes[j].Field }) + return changes +} + +func ShareUpdateChanges(before, after *share.Share) []activitydb.FieldChange { + if before == nil || after == nil { + return nil + } + tags := collectJSONTags(reflect.TypeOf(share.Share{}), shareActivitySkipJSONTags) + changes := make([]activitydb.FieldChange, 0, len(tags)) + for _, tag := range tags { + changes = append(changes, structFieldChanges(reflect.ValueOf(before).Elem(), reflect.ValueOf(after).Elem(), reflect.TypeOf(share.Share{}), tag)...) + } + if before.HasPassword() != after.HasPassword() { + changes = append(changes, activitydb.FieldChange{ + Field: "hasPassword", + From: formatActivityValue(reflect.ValueOf(before.HasPassword())), + To: formatActivityValue(reflect.ValueOf(after.HasPassword())), + }) + } + sort.Slice(changes, func(i, j int) bool { return changes[i].Field < changes[j].Field }) + return changes +} + +func normalizeUserWhich(which []string) []string { + return which +} + +func scopeFieldChanges(before, after *users.User) []activitydb.FieldChange { + return frontendScopeListChanges(before.GetFrontendScopes(), after.GetFrontendScopes(), "scopes") +} + +func frontendScopeListChanges(before, after []users.FrontendScope, prefix string) []activitydb.FieldChange { + beforeByName := make(map[string]users.FrontendScope, len(before)) + for _, scope := range before { + beforeByName[scope.Name] = scope + } + afterByName := make(map[string]users.FrontendScope, len(after)) + for _, scope := range after { + afterByName[scope.Name] = scope + } + names := sortedMapKeys(beforeByName, afterByName) + + changes := make([]activitydb.FieldChange, 0, len(names)) + for _, name := range names { + bScope, bOk := beforeByName[name] + aScope, aOk := afterByName[name] + subPrefix := prefix + "." + name + if !bOk { + changes = append(changes, valueFieldChanges(reflect.Value{}, reflect.ValueOf(aScope), subPrefix)...) + continue + } + if !aOk { + changes = append(changes, valueFieldChanges(reflect.ValueOf(bScope), reflect.Value{}, subPrefix)...) + continue + } + if bScope.Scope != aScope.Scope { + changes = append(changes, activitydb.FieldChange{ + Field: subPrefix + ".scope", + From: bScope.Scope, + To: aScope.Scope, + }) + } + changes = append(changes, valueFieldChanges( + reflect.ValueOf(bScope.Permissions), + reflect.ValueOf(aScope.Permissions), + subPrefix+".permissions", + )...) + } + return changes +} + +func backendSourcePermissionsFieldChanges(before, after *users.User) []activitydb.FieldChange { + if users.SourceConfigLoaded() { + return sourcePermissionsMapChanges( + before.GetFrontendSourcePermissions(), + after.GetFrontendSourcePermissions(), + "backendSourcePermissions", + ) + } + return sourcePermissionsMapChanges( + before.BackendSourcePermissions, + after.BackendSourcePermissions, + "backendSourcePermissions", + ) +} + +func sourcePermissionsMapChanges(before, after map[string]users.SourceFilePermissions, prefix string) []activitydb.FieldChange { + if len(before) == 0 && len(after) == 0 { + return nil + } + names := sortedMapKeys(before, after) + + changes := make([]activitydb.FieldChange, 0, len(names)) + for _, name := range names { + bPerms, bOk := before[name] + aPerms, aOk := after[name] + subPrefix := prefix + "." + name + if !bOk { + changes = append(changes, valueFieldChanges(reflect.Value{}, reflect.ValueOf(aPerms), subPrefix)...) + continue + } + if !aOk { + changes = append(changes, valueFieldChanges(reflect.ValueOf(bPerms), reflect.Value{}, subPrefix)...) + continue + } + changes = append(changes, valueFieldChanges(reflect.ValueOf(bPerms), reflect.ValueOf(aPerms), subPrefix)...) + } + return changes +} + +func sortedMapKeys[K comparable, V any](before, after map[K]V) []K { + seen := make(map[K]struct{}, len(before)+len(after)) + for key := range before { + seen[key] = struct{}{} + } + for key := range after { + seen[key] = struct{}{} + } + keys := make([]K, 0, len(seen)) + for key := range seen { + keys = append(keys, key) + } + sort.Slice(keys, func(i, j int) bool { + return fmt.Sprintf("%v", keys[i]) < fmt.Sprintf("%v", keys[j]) + }) + return keys +} + +func sidebarLinksFieldChange(before, after *users.User) (activitydb.FieldChange, bool) { + from := formatActivityValue(reflect.ValueOf(usersidebar.FrontendLinks(before.SidebarLinks, before.ShowToolsInSidebar))) + to := formatActivityValue(reflect.ValueOf(usersidebar.FrontendLinks(after.SidebarLinks, after.ShowToolsInSidebar))) + if from == to { + return activitydb.FieldChange{}, false + } + return activitydb.FieldChange{Field: "sidebarLinks", From: from, To: to}, true +} + +func structFieldChanges(beforeVal, afterVal reflect.Value, rootType reflect.Type, jsonTag string) []activitydb.FieldChange { + fieldIndex, ok := fieldIndexByJSONTag(rootType, jsonTag) + if !ok { + return nil + } + beforeField := beforeVal.FieldByIndex(fieldIndex) + afterField := afterVal.FieldByIndex(fieldIndex) + return valueFieldChanges(beforeField, afterField, jsonTag) +} + +func valueFieldChanges(before, after reflect.Value, fieldPrefix string) []activitydb.FieldChange { + fromVal, toVal := before, after + before = reflect.Indirect(before) + after = reflect.Indirect(after) + if !before.IsValid() && !after.IsValid() { + return nil + } + if !before.IsValid() || !after.IsValid() { + return []activitydb.FieldChange{{ + Field: fieldPrefix, + From: formatActivityValue(fromVal), + To: formatActivityValue(toVal), + }} + } + if reflect.DeepEqual(before.Interface(), after.Interface()) { + return nil + } + if before.Kind() == reflect.Map && after.Kind() == reflect.Map && before.Type().Key().Kind() == reflect.String { + return mapFieldChanges(before, after, fieldPrefix) + } + if before.Kind() == reflect.Struct && after.Kind() == reflect.Struct { + changes := make([]activitydb.FieldChange, 0, before.Type().NumField()) + for i := 0; i < before.Type().NumField(); i++ { + sf := before.Type().Field(i) + if sf.PkgPath != "" { + continue + } + tagName := strings.Split(sf.Tag.Get("json"), ",")[0] + if tagName == "" || tagName == "-" { + continue + } + if _, skip := activitySkipStructJSONTags[strings.ToLower(tagName)]; skip { + continue + } + subPrefix := tagName + if fieldPrefix != "" { + subPrefix = fieldPrefix + "." + tagName + } + changes = append(changes, valueFieldChanges(before.Field(i), after.Field(i), subPrefix)...) + } + if len(changes) > 0 { + return changes + } + } + return []activitydb.FieldChange{{ + Field: fieldPrefix, + From: formatActivityValue(before), + To: formatActivityValue(after), + }} +} + +func mapFieldChanges(before, after reflect.Value, fieldPrefix string) []activitydb.FieldChange { + if before.IsNil() && after.IsNil() { + return nil + } + if before.IsNil() { + before = reflect.MakeMap(after.Type()) + } + if after.IsNil() { + after = reflect.MakeMap(before.Type()) + } + + keys := make(map[string]reflect.Value) + for _, key := range before.MapKeys() { + keys[key.String()] = key + } + for _, key := range after.MapKeys() { + keys[key.String()] = key + } + keyNames := make([]string, 0, len(keys)) + for keyName := range keys { + keyNames = append(keyNames, keyName) + } + sort.Strings(keyNames) + + changes := make([]activitydb.FieldChange, 0, len(keyNames)) + for _, keyName := range keyNames { + key := keys[keyName] + bVal := before.MapIndex(key) + aVal := after.MapIndex(key) + subPrefix := fieldPrefix + "." + keyName + if !bVal.IsValid() { + changes = append(changes, valueFieldChanges(reflect.Value{}, aVal, subPrefix)...) + continue + } + if !aVal.IsValid() { + changes = append(changes, valueFieldChanges(bVal, reflect.Value{}, subPrefix)...) + continue + } + changes = append(changes, valueFieldChanges(bVal, aVal, subPrefix)...) + } + return changes +} + +func fieldIndexByJSONTag(t reflect.Type, jsonTag string) ([]int, bool) { + target := strings.ToLower(strings.TrimSpace(jsonTag)) + if target == "" { + return nil, false + } + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + if field.Anonymous && field.Type.Kind() == reflect.Struct { + if idx, ok := fieldIndexByJSONTag(field.Type, jsonTag); ok { + return append([]int{i}, idx...), true + } + continue + } + tagName := strings.Split(field.Tag.Get("json"), ",")[0] + if tagName == "" || tagName == "-" { + continue + } + if strings.EqualFold(tagName, target) { + return []int{i}, true + } + } + return nil, false +} + +func collectJSONTags(t reflect.Type, skip map[string]struct{}) []string { + tags := make([]string, 0, t.NumField()) + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + if field.Anonymous && field.Type.Kind() == reflect.Struct { + tags = append(tags, collectJSONTags(field.Type, skip)...) + continue + } + tagName := strings.Split(field.Tag.Get("json"), ",")[0] + if tagName == "" || tagName == "-" { + continue + } + if _, ok := skip[strings.ToLower(tagName)]; ok { + continue + } + tags = append(tags, tagName) + } + sort.Strings(tags) + return tags +} + +func formatActivityValue(v reflect.Value) string { + if !v.IsValid() { + return "" + } + if v.Kind() == reflect.Pointer && v.IsNil() { + return "null" + } + switch v.Kind() { + case reflect.String: + return v.String() + case reflect.Bool: + return fmt.Sprintf("%t", v.Bool()) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return fmt.Sprintf("%d", v.Int()) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return fmt.Sprintf("%d", v.Uint()) + case reflect.Float32, reflect.Float64: + return fmt.Sprintf("%g", v.Float()) + default: + b, err := json.Marshal(v.Interface()) + if err != nil { + return fmt.Sprintf("%v", v.Interface()) + } + return string(b) + } +} diff --git a/backend/internal/activity/diff_test.go b/backend/internal/activity/diff_test.go new file mode 100644 index 0000000000..6ef85b3a7e --- /dev/null +++ b/backend/internal/activity/diff_test.go @@ -0,0 +1,410 @@ +package activity + +import ( + "reflect" + "strings" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func TestUserUpdateChangesSkipsSensitiveFields(t *testing.T) { + before := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "alice", + NonAdminEditable: users.NonAdminEditable{ + DarkMode: true, + }, + }, + TOTPSecret: "secret-value", + } + after := *before + after.DarkMode = false + after.TOTPSecret = "new-secret" + + changes := UserUpdateChanges(before, &after, []string{"totpSecret", "darkMode"}, false) + for _, c := range changes { + if c.Field == "totpSecret" { + t.Fatalf("totpSecret must not appear in activity changes: %#v", changes) + } + } +} + +func TestUserUpdateChangesFiltersUnchangedFields(t *testing.T) { + before := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "akadmin", + NonAdminEditable: users.NonAdminEditable{ + DarkMode: true, + StickySidebar: true, + Locale: "en", + SingleClick: false, + ThemeColor: "var(--blue)", + QuickDownload: false, + DeleteAfterArchive: true, + }, + }, + } + after := *before + after.DarkMode = false + after.Sorting = users.Sorting{By: "name", Asc: true} + + which := []string{ + "preview", "stickySidebar", "darkMode", "locale", "singleClick", "sorting", + "showHidden", "dateFormat", "themeColor", "quickDownload", "fileLoading", + "sidebarLinks", "deleteAfterArchive", "preferEditorForMarkdown", "showFirstLogin", + } + + changes := UserUpdateChanges(before, &after, which, false) + if len(changes) != 3 { + t.Fatalf("expected 3 changes, got %d: %#v", len(changes), changes) + } + if changes[0].Field != "darkMode" || changes[0].From != "true" || changes[0].To != "false" { + t.Fatalf("unexpected darkMode change: %#v", changes[0]) + } + if changes[1].Field != "sorting.asc" || changes[1].From != "false" || changes[1].To != "true" { + t.Fatalf("unexpected sorting.asc change: %#v", changes[1]) + } + if changes[2].Field != "sorting.by" || changes[2].From != "" || changes[2].To != "name" { + t.Fatalf("unexpected sorting.by change: %#v", changes[2]) + } +} + +func TestValueFieldChangesPointerTransitions(t *testing.T) { + perms := users.MarkSourceFilePermissionsConfigured(users.SourceFilePermissions{View: true}) + + t.Run("nil and nil", func(t *testing.T) { + var before, after *users.SourceFilePermissions + changes := valueFieldChanges(reflect.ValueOf(before), reflect.ValueOf(after), "permissions") + if len(changes) != 0 { + t.Fatalf("expected no changes, got %#v", changes) + } + }) + + t.Run("nil to value", func(t *testing.T) { + var before *users.SourceFilePermissions + changes := valueFieldChanges(reflect.ValueOf(before), reflect.ValueOf(perms), "permissions") + if len(changes) != 1 { + t.Fatalf("expected 1 change, got %#v", changes) + } + if changes[0].Field != "permissions" { + t.Fatalf("unexpected field: %#v", changes[0]) + } + if changes[0].From != "null" { + t.Fatalf("expected From null, got %q", changes[0].From) + } + if changes[0].To == "" || changes[0].To == "null" { + t.Fatalf("expected permissions JSON in To, got %q", changes[0].To) + } + }) + + t.Run("value to nil", func(t *testing.T) { + var after *users.SourceFilePermissions + changes := valueFieldChanges(reflect.ValueOf(perms), reflect.ValueOf(after), "permissions") + if len(changes) != 1 { + t.Fatalf("expected 1 change, got %#v", changes) + } + if changes[0].Field != "permissions" { + t.Fatalf("unexpected field: %#v", changes[0]) + } + if changes[0].To != "null" { + t.Fatalf("expected To null, got %q", changes[0].To) + } + if changes[0].From == "" || changes[0].From == "null" { + t.Fatalf("expected permissions JSON in From, got %q", changes[0].From) + } + }) +} + +func TestUserUpdateChangesExpandsNestedStructFields(t *testing.T) { + before := &users.User{ + FrontendUser: users.FrontendUser{ + NonAdminEditable: users.NonAdminEditable{ + Preview: users.Preview{ + AutoplayMedia: false, + Image: true, + Video: true, + }, + }, + }, + } + after := *before + after.Preview.AutoplayMedia = true + + changes := UserUpdateChanges(before, &after, []string{"preview"}, false) + if len(changes) != 1 { + t.Fatalf("expected 1 change, got %d: %#v", len(changes), changes) + } + if changes[0].Field != "preview.autoplayMedia" || changes[0].From != "false" || changes[0].To != "true" { + t.Fatalf("unexpected preview.autoplayMedia change: %#v", changes[0]) + } +} + +type activityChangePair struct { + from string + to string +} + +func testDownloadsSourceConfig() *users.SourceConfigProvider { + return &users.SourceConfigProvider{ + GetSourceByPath: func(path string) (users.SourceInfo, bool) { + switch path { + case "/Users/steffag/Downloads": + return users.SourceInfo{Path: path, Name: "Downloads"}, true + case "/Users/steffag/git/personal/filebrowser/frontend/tests/playwright-files": + return users.SourceInfo{Path: path, Name: "access"}, true + default: + return users.SourceInfo{}, false + } + }, + } +} + +func withTestSourceConfig(t *testing.T, provider *users.SourceConfigProvider) { + t.Helper() + previous := users.GetSourceConfig() + users.SetSourceConfig(provider) + t.Cleanup(func() { + users.SetSourceConfig(previous) + }) +} + +func TestUserUpdateChangesExpandsPreviewBulkToggle(t *testing.T) { + before := &users.User{ + FrontendUser: users.FrontendUser{ + NonAdminEditable: users.NonAdminEditable{ + Preview: users.Preview{ + DisableHideSidebar: false, + Image: true, + Video: true, + Audio: true, + MotionVideoPreview: true, + Office: true, + PopUp: true, + AutoplayMedia: true, + Folder: true, + Models: true, + }, + }, + }, + } + after := *before + after.Preview.DisableHideSidebar = true + after.Preview.Image = false + after.Preview.Video = false + after.Preview.Audio = false + after.Preview.MotionVideoPreview = false + after.Preview.Office = false + after.Preview.PopUp = false + after.Preview.AutoplayMedia = false + after.Preview.Folder = false + after.Preview.Models = false + + changes := UserUpdateChanges(before, &after, []string{"preview"}, false) + if len(changes) != 10 { + t.Fatalf("expected 10 preview field changes, got %d: %#v", len(changes), changes) + } + foundDisableHide := false + for _, c := range changes { + if !strings.HasPrefix(c.Field, "preview.") { + t.Fatalf("expected preview.* field, got %q", c.Field) + } + if c.Field == "preview.disableHideSidebar" { + foundDisableHide = true + if c.From != "false" || c.To != "true" { + t.Fatalf("unexpected preview.disableHideSidebar change: %#v", c) + } + continue + } + if c.From != "true" || c.To != "false" { + t.Fatalf("expected true -> false, got %#v", c) + } + } + if !foundDisableHide { + t.Fatal("expected preview.disableHideSidebar change") + } +} + +func TestUserUpdateChangesExpandsBackendSourcePermissions(t *testing.T) { + withTestSourceConfig(t, testDownloadsSourceConfig()) + + downloadsPath := "/Users/steffag/Downloads" + accessPath := "/Users/steffag/git/personal/filebrowser/frontend/tests/playwright-files" + beforePerms := users.MarkSourceFilePermissionsConfigured(users.SourceFilePermissions{ + View: true, Download: true, + }) + afterDownloadsPerms := users.MarkSourceFilePermissionsConfigured(users.SourceFilePermissions{ + View: true, Download: true, Modify: true, Delete: true, Create: true, + }) + afterAccessPerms := beforePerms + + before := &users.User{ + BackendSourcePermissions: map[string]users.SourceFilePermissions{ + downloadsPath: beforePerms, + accessPath: beforePerms, + }, + } + after := &users.User{ + BackendSourcePermissions: map[string]users.SourceFilePermissions{ + downloadsPath: afterDownloadsPerms, + accessPath: afterAccessPerms, + }, + } + + changes := UserUpdateChanges(before, after, []string{"backendSourcePermissions"}, false) + if len(changes) != 3 { + t.Fatalf("expected 3 permission changes for Downloads only, got %d: %#v", len(changes), changes) + } + found := map[string]activityChangePair{} + for _, c := range changes { + found[c.Field] = activityChangePair{from: c.From, to: c.To} + } + for _, field := range []string{ + "backendSourcePermissions.Downloads.modify", + "backendSourcePermissions.Downloads.delete", + "backendSourcePermissions.Downloads.create", + } { + if pair, ok := found[field]; !ok || pair.from != "false" || pair.to != "true" { + t.Fatalf("missing or unexpected change for %s: %#v", field, found) + } + } +} + +func TestUserUpdateChangesExpandsScopePermissions(t *testing.T) { + withTestSourceConfig(t, testDownloadsSourceConfig()) + + downloadsPath := "/Users/steffag/Downloads" + accessPath := "/Users/steffag/git/personal/filebrowser/frontend/tests/playwright-files" + basePerms := users.MarkSourceFilePermissionsConfigured(users.SourceFilePermissions{ + View: true, Download: true, + }) + downloadsPerms := users.MarkSourceFilePermissionsConfigured(users.SourceFilePermissions{ + View: true, Download: true, Modify: true, Delete: true, Create: true, + }) + + before := &users.User{ + BackendScopes: []users.BackendScope{ + {Path: downloadsPath, Scope: "/", Permissions: basePerms}, + {Path: accessPath, Scope: "/", Permissions: basePerms}, + }, + } + after := &users.User{ + BackendScopes: []users.BackendScope{ + {Path: downloadsPath, Scope: "/", Permissions: downloadsPerms}, + {Path: accessPath, Scope: "/", Permissions: basePerms}, + }, + } + + changes := UserUpdateChanges(before, after, []string{"scopes"}, false) + if len(changes) != 3 { + t.Fatalf("expected 3 scope permission changes for Downloads only, got %d: %#v", len(changes), changes) + } + for _, c := range changes { + if !strings.HasPrefix(c.Field, "scopes.Downloads.permissions.") { + t.Fatalf("unexpected scope field %q", c.Field) + } + if c.From != "false" || c.To != "true" { + t.Fatalf("expected false -> true, got %#v", c) + } + } +} + +func TestShareUpdateChangesLogsChangedAttributes(t *testing.T) { + before := &share.Share{ + ShareSettings: share.ShareSettings{ + FrontendShareInfo: share.FrontendShareInfo{ + ShareTheme: "light", + Title: "before", + }, + ShareLimits: share.ShareLimits{ + DownloadsLimit: 5, + }, + }, + } + after := *before + after.ShareTheme = "dark" + after.Title = "after" + after.DownloadsLimit = 10 + + changes := ShareUpdateChanges(before, &after) + if len(changes) < 3 { + t.Fatalf("expected at least 3 changes, got %d: %#v", len(changes), changes) + } + found := map[string]activityChangePair{} + for _, c := range changes { + found[c.Field] = activityChangePair{from: c.From, to: c.To} + } + if pair, ok := found["shareTheme"]; !ok || pair.to != "dark" { + t.Fatalf("missing shareTheme change: %#v", found) + } + if pair, ok := found["title"]; !ok || pair.to != "after" { + t.Fatalf("missing title change: %#v", found) + } + if pair, ok := found["downloadsLimit"]; !ok || pair.from != "5" || pair.to != "10" { + t.Fatalf("missing downloadsLimit change: %#v", found) + } + if _, ok := found["hash"]; ok { + t.Fatalf("hash must not appear in share update changes: %#v", found) + } +} + +func TestSidebarLinksFieldChangeIgnoresPathVsName(t *testing.T) { + withTestSourceConfig(t, &users.SourceConfigProvider{ + GetSourceByPath: func(path string) (users.SourceInfo, bool) { + switch path { + case "/Users/steffag/Downloads": + return users.SourceInfo{Path: path, Name: "Downloads"}, true + case "/Users/steffag/git/personal/filebrowser/frontend/tests/playwright-files": + return users.SourceInfo{Path: path, Name: "access"}, true + default: + return users.SourceInfo{}, false + } + }, + GetSourceByName: func(name string) (users.SourceInfo, bool) { + switch name { + case "Downloads": + return users.SourceInfo{Path: "/Users/steffag/Downloads", Name: "Downloads"}, true + case "access": + return users.SourceInfo{Path: "/Users/steffag/git/personal/filebrowser/frontend/tests/playwright-files", Name: "access"}, true + default: + return users.SourceInfo{}, false + } + }, + }) + + toolsLink := users.SidebarLink{Name: "Tools", Category: "tool", Target: "/tools", Icon: "build"} + before := &users.User{ + FrontendUser: users.FrontendUser{ + NonAdminEditable: users.NonAdminEditable{ + ShowToolsInSidebar: true, + SidebarLinks: []users.SidebarLink{ + toolsLink, + {Name: "Downloads", Category: "source", Target: "/", SourceName: "/Users/steffag/Downloads"}, + {Name: "access", Category: "source", Target: "/", SourceName: "/Users/steffag/git/personal/filebrowser/frontend/tests/playwright-files"}, + }, + }, + }, + } + after := &users.User{ + FrontendUser: users.FrontendUser{ + NonAdminEditable: users.NonAdminEditable{ + ShowToolsInSidebar: true, + SidebarLinks: []users.SidebarLink{ + toolsLink, + {Name: "Downloads", Category: "source", Target: "/", SourceName: "Downloads"}, + {Name: "access", Category: "source", Target: "/", SourceName: "access"}, + }, + }, + }, + } + + if _, ok := sidebarLinksFieldChange(before, after); ok { + t.Fatal("expected sidebarLinks to be unchanged when only sourceName representation differs") + } + + changes := UserUpdateChanges(before, after, []string{"sidebarLinks"}, false) + if len(changes) != 0 { + t.Fatalf("expected no sidebarLinks change in user update, got %#v", changes) + } +} diff --git a/backend/internal/activity/export.go b/backend/internal/activity/export.go new file mode 100644 index 0000000000..50b2d548d2 --- /dev/null +++ b/backend/internal/activity/export.go @@ -0,0 +1,88 @@ +package activity + +import ( + "fmt" + "strings" + + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" +) + +var activityOptionalExportColumns = map[string]struct{}{ + "source": {}, + "path": {}, + "shareHash": {}, + "tokenName": {}, +} + +func ParseExportRows(raw string) ([]string, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return nil, nil + } + parts := strings.Split(raw, ",") + out := make([]string, 0, len(parts)) + seen := make(map[string]struct{}, len(parts)) + for _, part := range parts { + key := strings.TrimSpace(part) + if key == "" { + continue + } + if _, ok := activityOptionalExportColumns[key]; !ok { + return nil, fmt.Errorf("invalid rows column: %s (allowed: source, path, shareHash, tokenName)", key) + } + if _, dup := seen[key]; dup { + continue + } + seen[key] = struct{}{} + out = append(out, key) + } + return out, nil +} + +func ExportHeader(includeDetails bool, optional []string) []string { + header := []string{"id", "createdAt", "username", "eventType"} + header = append(header, optional...) + header = append(header, "ipAddress") + if includeDetails { + header = append(header, "details") + } + return header +} + +func SanitizeCSVCell(v string) string { + if v == "" { + return v + } + switch v[0] { + case '=', '+', '-', '@': + return "'" + v + default: + return v + } +} + +func ExportRowValues(item activitydb.FrontendEntry, optional []string, includeDetails bool, detailsJSON string) []string { + row := []string{ + fmt.Sprintf("%d", item.ID), + fmt.Sprintf("%d", item.CreatedAt), + SanitizeCSVCell(item.Username), + string(item.EventType), + } + for _, col := range optional { + switch col { + case "source": + row = append(row, SanitizeCSVCell(item.Source)) + case "path": + row = append(row, SanitizeCSVCell(item.Path)) + case "shareHash": + row = append(row, SanitizeCSVCell(item.ShareHash)) + case "tokenName": + row = append(row, SanitizeCSVCell(item.TokenName)) + } + } + row = append(row, SanitizeCSVCell(item.IPAddress)) + if includeDetails { + row = append(row, SanitizeCSVCell(detailsJSON)) + } + return row +} diff --git a/backend/internal/activity/export_test.go b/backend/internal/activity/export_test.go new file mode 100644 index 0000000000..932d3e2151 --- /dev/null +++ b/backend/internal/activity/export_test.go @@ -0,0 +1,50 @@ +package activity + +import "testing" + +func TestParseActivityExportRows(t *testing.T) { + cols, err := ParseExportRows("source,path,tokenName") + if err != nil { + t.Fatal(err) + } + if len(cols) != 3 { + t.Fatalf("expected 3 columns, got %v", cols) + } + + _, err = ParseExportRows("badColumn") + if err == nil { + t.Fatal("expected error for invalid column") + } +} + +func TestActivityExportHeader(t *testing.T) { + header := ExportHeader(true, []string{"source", "tokenName"}) + want := []string{"id", "createdAt", "username", "eventType", "source", "tokenName", "ipAddress", "details"} + if len(header) != len(want) { + t.Fatalf("header len %d != %d: %v", len(header), len(want), header) + } + for i, w := range want { + if header[i] != w { + t.Fatalf("header[%d]=%q want %q", i, header[i], w) + } + } +} + +func TestSanitizeCSVCell(t *testing.T) { + tests := []struct { + in string + want string + }{ + {"", ""}, + {"alice", "alice"}, + {"=1+1", "'=1+1"}, + {"+1234", "'+1234"}, + {"-1234", "'-1234"}, + {"@SUM(A1)", "'@SUM(A1)"}, + } + for _, tc := range tests { + if got := SanitizeCSVCell(tc.in); got != tc.want { + t.Fatalf("SanitizeCSVCell(%q) = %q, want %q", tc.in, got, tc.want) + } + } +} diff --git a/backend/internal/activity/filter.go b/backend/internal/activity/filter.go new file mode 100644 index 0000000000..6ee87e5056 --- /dev/null +++ b/backend/internal/activity/filter.go @@ -0,0 +1,203 @@ +package activity + +import ( + "fmt" + "net/http" + "strconv" + "strings" + "time" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" +) + +const ( + maxExportRows = 100000 + maxChartDays = 90 + maxMinuteRangeSecs = 2 * 86400 // 48 hours +) + +// MaxExportRows is the CSV export row cap. +const MaxExportRows = maxExportRows + +// ClampListPaging normalizes page/limit before database queries. +func ClampListPaging(filter *activitydb.QueryFilter) { + limit := filter.Limit + if limit <= 0 { + limit = 100 + } + filter.Limit = utils.Clamp(limit, 1, 500) + if filter.Page < 1 { + filter.Page = 1 + } +} + +// ParseFilter builds a query filter from HTTP params and actor context. +func ParseFilter(r *http.Request, actor *Actor) (activitydb.QueryFilter, int, error) { + if status, err := EnforceScope(r, actor); err != nil { + return activitydb.QueryFilter{}, status, err + } + if status, err := EnforcePathGlobFilter(r, actor); err != nil { + return activitydb.QueryFilter{}, status, err + } + + q := r.URL.Query() + now := time.Now().Unix() + + from := parseInt64Default(q.Get("from"), now-7*86400) + to := parseInt64Default(q.Get("to"), now) + if to < from { + return activitydb.QueryFilter{}, http.StatusBadRequest, fmt.Errorf("to must be >= from") + } + + filter := activitydb.QueryFilter{ + From: from, + To: to, + Source: strings.TrimSpace(q.Get("source")), + PathPrefix: strings.TrimSpace(q.Get("path")), + PathGlob: strings.TrimSpace(q.Get("pathGlob")), + ShareHash: strings.TrimSpace(q.Get("shareHash")), + Page: parseIntDefault(q.Get("page"), 1), + Limit: parseIntDefault(q.Get("limit"), 100), + Interval: strings.TrimSpace(q.Get("interval")), + SplitBy: strings.TrimSpace(q.Get("splitBy")), + GroupBy: strings.TrimSpace(q.Get("groupBy")), + } + + if et := q.Get("eventType"); et != "" { + for _, part := range strings.Split(et, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + ev := activitydb.EventType(part) + if !ev.Valid() { + return activitydb.QueryFilter{}, http.StatusBadRequest, fmt.Errorf("invalid eventType: %s", part) + } + filter.EventTypes = append(filter.EventTypes, ev) + } + } + + if actor.User.Permissions.Admin { + if username := strings.TrimSpace(q.Get("username")); username != "" { + if username == users.AnonymousUserName { + filter.UserID = 0 + filter.UserFilter = true + } else { + uID, err := users.ResolveUsernameToID(username) + if err != nil { + return activitydb.QueryFilter{}, http.StatusBadRequest, fmt.Errorf("user not found: %s", username) + } + filter.UserID = uID + filter.UserFilter = true + } + } + } else { + filter.UserID = actor.User.ID + filter.UserFilter = true + } + + scope := strings.TrimSpace(q.Get("scope")) + if scope == "" { + scope = "all" + } + filter.Scope = scope + + if status, err := ResolveShareAccess(actor, &filter); err != nil { + return activitydb.QueryFilter{}, status, err + } + + resolvedTypes, err := activitydb.ResolveScopeEventTypes(scope, filter.EventTypes) + if err != nil { + return activitydb.QueryFilter{}, http.StatusBadRequest, err + } + filter.EventTypes = resolvedTypes + + if status, err := ResolvePathFilters(actor, &filter); err != nil { + return activitydb.QueryFilter{}, status, err + } + + return filter, 0, nil +} + +// EnforceScope rejects non-admin attempts to scope activity to another user. +func EnforceScope(r *http.Request, actor *Actor) (int, error) { + if actor == nil || actor.User == nil || actor.User.ID == 0 { + return http.StatusUnauthorized, fmt.Errorf("authentication required") + } + if actor.User.Permissions.Admin { + return 0, nil + } + + q := r.URL.Query() + if userIDParam := strings.TrimSpace(q.Get("userId")); userIDParam != "" { + requestedID, err := strconv.ParseUint(userIDParam, 10, 64) + if err != nil || requestedID != actor.User.ID { + return http.StatusForbidden, fmt.Errorf("forbidden: cannot query activity for another user") + } + } + if username := strings.TrimSpace(q.Get("username")); username != "" && username != actor.User.Username { + return http.StatusForbidden, fmt.Errorf("forbidden: cannot query activity for another user") + } + return 0, nil +} + +// ValidateChartParams checks grouped/chart query parameters. +func ValidateChartParams(filter activitydb.QueryFilter) error { + interval := filter.Interval + if interval == "" { + switch filter.GroupBy { + case "day": + interval = "day" + case "none": + interval = "none" + case "hour", "": + interval = "hour" + default: + return fmt.Errorf("groupBy must be none, hour, or day (use interval instead)") + } + } + if interval != "minute" && interval != "hour" && interval != "day" && interval != "none" { + return fmt.Errorf("interval must be minute, hour, day, or none") + } + + splitBy := filter.SplitBy + if splitBy == "" { + splitBy = "eventType" + } + if splitBy != "eventType" && splitBy != "user" && splitBy != "none" { + return fmt.Errorf("splitBy must be eventType, user, or none") + } + + rangeSecs := filter.To - filter.From + if interval == "minute" && rangeSecs > maxMinuteRangeSecs { + return fmt.Errorf("minute interval supports at most 48 hours; use hour or day for longer ranges") + } + if interval != "none" && rangeSecs > int64(maxChartDays)*86400 { + return fmt.Errorf("time range exceeds %d days for chart queries", maxChartDays) + } + return nil +} + +func parseInt64Default(s string, def int64) int64 { + if s == "" { + return def + } + v, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return def + } + return v +} + +func parseIntDefault(s string, def int) int { + if s == "" { + return def + } + v, err := strconv.Atoi(s) + if err != nil { + return def + } + return v +} diff --git a/backend/internal/activity/query.go b/backend/internal/activity/query.go new file mode 100644 index 0000000000..fb4a0d8fb7 --- /dev/null +++ b/backend/internal/activity/query.go @@ -0,0 +1,162 @@ +package activity + +import ( + "fmt" + "net/http" + "strings" + + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +// resolveActivityPathFilters validates source/path filters and scopes paths to the actor's access. +func ResolvePathFilters(actor *Actor, filter *activitydb.QueryFilter) (int, error) { + if filter.Source == "" && filter.PathPrefix == "" && filter.PathGlob == "" { + return 0, nil + } + if filter.PathPrefix != "" && filter.PathGlob != "" { + return http.StatusBadRequest, fmt.Errorf("use path or pathGlob, not both") + } + if filter.Source == "" && (filter.PathPrefix != "" || filter.PathGlob != "") { + return http.StatusBadRequest, fmt.Errorf("source is required when filtering by path") + } + + sourceInfo, ok := settings.Config.Server.NameToSource[filter.Source] + if !ok { + return http.StatusBadRequest, fmt.Errorf("invalid source: %s", filter.Source) + } + if _, err := actor.User.GetScopeForSourceName(filter.Source); err != nil { + return http.StatusForbidden, err + } + if filter.PathPrefix == "" && filter.PathGlob == "" { + return 0, nil + } + idx := indexing.GetIndex(sourceInfo.Name) + if idx == nil { + return http.StatusBadRequest, fmt.Errorf("index not found for source: %s", filter.Source) + } + + userScope, err := actor.User.GetScopeForSourceName(filter.Source) + if err != nil { + return http.StatusForbidden, err + } + + if filter.PathPrefix != "" { + indexPath, status, err := resolveActivityIndexPath(actor, idx, userScope, filter.PathPrefix) + if err != nil { + return status, err + } + filter.PathPrefix = indexPath + } + if filter.PathGlob != "" { + scopedGlob, status, err := resolveActivityPathGlob(actor, idx, userScope, filter.PathGlob) + if err != nil { + return status, err + } + filter.PathGlob = scopedGlob + } + return 0, nil +} + +func resolveActivityIndexPath(actor *Actor, idx *indexing.Index, userScope, clientPath string) (string, int, error) { + clientPath = strings.TrimSpace(clientPath) + if clientPath == "" { + return "", http.StatusBadRequest, fmt.Errorf("path is empty") + } + cleanPath, err := utils.SanitizePath(clientPath) + if err != nil { + return "", http.StatusBadRequest, err + } + clientPath = cleanPath + if !strings.HasPrefix(clientPath, "/") { + clientPath = "/" + clientPath + } + + userScope = strings.TrimRight(userScope, "/") + fullIndexPath := clientPath + if userScope != "" && userScope != "/" { + if !strings.HasPrefix(clientPath, userScope+"/") && clientPath != userScope { + fullIndexPath = utils.JoinPathAsUnix(userScope, strings.TrimPrefix(clientPath, "/")) + } + } + + isDir := strings.HasSuffix(fullIndexPath, "/") + fullPath := idx.MakeIndexPath(fullIndexPath, isDir) + if !accessPermitted(idx.Path, fullPath, actor.User.Username) { + return "", http.StatusForbidden, fmt.Errorf("user is not allowed to access this location") + } + return strings.TrimSuffix(fullIndexPath, "/"), 0, nil +} + +func resolveActivityPathGlob(actor *Actor, idx *indexing.Index, userScope, glob string) (string, int, error) { + glob = strings.TrimSpace(glob) + if glob == "" { + return "", http.StatusBadRequest, fmt.Errorf("pathGlob is empty") + } + cleanGlob, err := utils.SanitizePath(glob) + if err != nil { + return "", http.StatusBadRequest, err + } + glob = cleanGlob + + userScope = strings.TrimRight(userScope, "/") + var scoped string + if strings.HasPrefix(glob, "/") { + scoped = glob + } else if userScope != "" && userScope != "/" { + scoped = userScope + "/" + glob + } else { + scoped = "/" + glob + } + + if userScope != "" && userScope != "/" && !strings.HasPrefix(scoped, userScope) { + return "", http.StatusForbidden, fmt.Errorf("glob pattern outside user scope") + } + + rootPath := userScope + if rootPath == "" { + rootPath = "/" + } + fullPath := idx.MakeIndexPath(rootPath, true) + if !accessPermitted(idx.Path, fullPath, actor.User.Username) { + return "", http.StatusForbidden, fmt.Errorf("user is not allowed to access this location") + } + return scoped, 0, nil +} + +// enforceActivityPathGlobFilter restricts path glob queries to admins. +func EnforcePathGlobFilter(r *http.Request, actor *Actor) (int, error) { + if actor.User.Permissions.Admin { + return 0, nil + } + if strings.TrimSpace(r.URL.Query().Get("pathGlob")) != "" { + return http.StatusForbidden, fmt.Errorf("forbidden: pathGlob requires admin") + } + return 0, nil +} + +// resolveActivityShareAccess validates share hash filters and configures share-owner scoping for non-admins. +func ResolveShareAccess(actor *Actor, filter *activitydb.QueryFilter) (int, error) { + if filter.ShareHash != "" { + sh, err := getShare(filter.ShareHash) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("share not found") + } + if !actor.User.Permissions.Admin && sh.UserID != actor.User.ID { + return http.StatusForbidden, fmt.Errorf("forbidden: not your share") + } + } + + if actor.User.Permissions.Admin { + return 0, nil + } + + if filter.Scope == "shares" || filter.ShareHash != "" { + filter.UserFilter = false + filter.ShareOwnerUserID = actor.User.ID + filter.ShareOwnerFilter = true + } + return 0, nil +} diff --git a/backend/internal/activity/query_test.go b/backend/internal/activity/query_test.go new file mode 100644 index 0000000000..14c5388300 --- /dev/null +++ b/backend/internal/activity/query_test.go @@ -0,0 +1,17 @@ +package activity + +import ( + "net/http" + "strings" + "testing" +) + +func TestResolveActivityPathGlobRejectsTraversal(t *testing.T) { + _, status, err := resolveActivityPathGlob(&Actor{}, nil, "/docs", "../secret/*") + if status != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", status) + } + if err == nil || !strings.Contains(err.Error(), "path traversal") { + t.Fatalf("expected path traversal error, got %v", err) + } +} diff --git a/backend/internal/activity/record.go b/backend/internal/activity/record.go new file mode 100644 index 0000000000..5b8ba9a78f --- /dev/null +++ b/backend/internal/activity/record.go @@ -0,0 +1,393 @@ +package activity + +import ( + "net/http" + "strconv" + "strings" + "time" + + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// MoveCopyItem identifies a single move/copy/rename for activity logging. +type MoveCopyItem struct { + FromSource string + FromPath string + ToPath string +} + +// BulkDeleteItem identifies a deleted path for activity logging. +type BulkDeleteItem struct { + Source string + Path string +} + +type activityActorPolicy int + +const ( + activityActorUser activityActorPolicy = iota + activityActorAny + activityActorShareOwner +) + +func recordEntry(entry activitydb.Entry) { + Record(entry) +} + +func finalizeActivityEntry(r *http.Request, actor *Actor, entry activitydb.Entry, policy activityActorPolicy) { + switch policy { + case activityActorUser: + if actor == nil || actor.User == nil || actor.User.ID == 0 { + return + } + if entry.UserID == 0 { + entry.UserID = actor.User.ID + } + case activityActorAny: + if actor == nil { + return + } + if actor.User != nil && entry.UserID == 0 { + entry.UserID = actor.User.ID + } + case activityActorShareOwner: + if actor == nil || actor.Share.Hash == "" || actor.Share.UserID == 0 { + return + } + entry.UserID = actor.Share.UserID + entry.Details.ShareHash = actor.Share.Hash + entry.Details.ShareOwnerUserID = actor.Share.UserID + } + + if entry.CreatedAt == 0 { + entry.CreatedAt = time.Now().Unix() + } + if entry.IPAddress == "" && r != nil { + entry.IPAddress = remoteIP(r) + } + applyActivityAuthContext(actor, &entry) + recordEntry(entry) +} + +func applyActivityAuthContext(actor *Actor, entry *activitydb.Entry) { + if actor == nil || actor.Token == "" { + return + } + if actor.User != nil { + if name, ok := users.TokenNameByRaw(actor.User.Tokens, actor.Token); ok { + entry.Details.TokenName = name + if strings.HasPrefix(name, "WEB_TOKEN") { + entry.Details.AuthMethod = "webToken" + } else { + entry.Details.AuthMethod = "apiKey" + } + return + } + } + entry.Details.AuthMethod = "webToken" +} + +func RecordUser(r *http.Request, actor *Actor, entry activitydb.Entry) { + finalizeActivityEntry(r, actor, entry, activityActorUser) +} + +func RecordActor(r *http.Request, actor *Actor, entry activitydb.Entry) { + finalizeActivityEntry(r, actor, entry, activityActorAny) +} + +func RecordShareOwner(r *http.Request, actor *Actor, entry activitydb.Entry) { + finalizeActivityEntry(r, actor, entry, activityActorShareOwner) +} + +func RecordWebDAVUser(r *http.Request, user *users.User, entry activitydb.Entry) { + if user == nil || user.ID == 0 { + return + } + actor := &Actor{User: user} + if entry.UserID == 0 { + entry.UserID = user.ID + } + finalizeActivityEntry(r, actor, entry, activityActorUser) +} + +// RecordDownload appends an audit log row for a file or folder download. +// Share download counters and per-user limits use state.IncrementShareDownloadCount separately. +func RecordDownload(r *http.Request, actor *Actor, source string, fileList []string) { + details := activitydb.Details{ + Source: source, + FileCount: len(fileList), + Paths: append([]string(nil), fileList...), + } + details.CapPaths() + if len(fileList) == 1 { + details.Path = fileList[0] + } + entry := activitydb.Entry{ + EventType: activitydb.EventDownload, + Source: source, + Details: details, + } + if len(fileList) == 1 { + entry.Path = fileList[0] + } + if actor != nil && actor.Share.Hash != "" { + entry.Details.ShareHash = actor.Share.Hash + entry.Details.ShareOwnerUserID = actor.Share.UserID + } + RecordActor(r, actor, entry) +} + +func RecordPatchItem(r *http.Request, actor *Actor, action string, item MoveCopyItem) { + eventType, ok := activitydb.EventTypeFromAction(action) + if !ok { + return + } + details := activitydb.Details{ + Source: item.FromSource, + Path: item.FromPath, + TargetPath: item.ToPath, + } + entry := activitydb.Entry{ + EventType: eventType, + Source: item.FromSource, + Path: item.FromPath, + TargetPath: item.ToPath, + Details: details, + } + if actor != nil && actor.Share.Hash != "" { + RecordShareOwner(r, actor, entry) + return + } + RecordUser(r, actor, entry) +} + +func RecordDelete(r *http.Request, actor *Actor, source, path string) { + RecordUser(r, actor, activitydb.Entry{ + EventType: activitydb.EventDelete, + Source: source, + Path: path, + Details: activitydb.Details{ + Source: source, + Path: path, + }, + }) +} + +func RecordBulkDelete(r *http.Request, actor *Actor, succeeded []BulkDeleteItem) { + if len(succeeded) == 0 { + return + } + paths := make([]string, 0, len(succeeded)) + for _, item := range succeeded { + paths = append(paths, item.Path) + } + details := activitydb.Details{ + FileCount: len(succeeded), + Paths: paths, + } + details.CapPaths() + entry := activitydb.Entry{ + EventType: activitydb.EventBulkDelete, + Details: details, + } + if len(succeeded) == 1 { + entry.Source = succeeded[0].Source + entry.Path = succeeded[0].Path + entry.Details.Source = succeeded[0].Source + entry.Details.Path = succeeded[0].Path + } + RecordUser(r, actor, entry) +} + +func RecordUpload(r *http.Request, actor *Actor, source, path string, isDir bool) { + pathLabel := path + if isDir { + pathLabel = path + "/" + } + details := activitydb.Details{ + Source: source, + Path: pathLabel, + } + RecordUser(r, actor, activitydb.Entry{ + EventType: activitydb.EventUpload, + Source: source, + Path: pathLabel, + Details: details, + }) +} + +func RecordShareMutation(r *http.Request, actor *Actor, eventType activitydb.EventType, hash, sourceName, path string, changes []activitydb.FieldChange) { + details := activitydb.Details{ + Source: sourceName, + Path: path, + ShareHash: hash, + Changes: changes, + } + RecordUser(r, actor, activitydb.Entry{ + EventType: eventType, + Source: sourceName, + Path: path, + Details: details, + }) +} + +func RecordArchive(r *http.Request, actor *Actor, eventType activitydb.EventType, source, path string, paths []string) { + details := activitydb.Details{ + Source: source, + Path: path, + FileCount: len(paths), + Paths: append([]string(nil), paths...), + } + details.CapPaths() + RecordUser(r, actor, activitydb.Entry{ + EventType: eventType, + Source: source, + Path: path, + Details: details, + }) +} + +func RecordAccessCreate(r *http.Request, actor *Actor, source, path string, changes []activitydb.FieldChange) { + RecordUser(r, actor, activitydb.Entry{ + EventType: activitydb.EventAccessCreate, + Source: source, + Path: path, + Details: activitydb.Details{ + Source: source, + Path: path, + Changes: changes, + }, + }) +} + +func RecordAccessUpdate(r *http.Request, actor *Actor, source, path string, changes []activitydb.FieldChange) { + RecordUser(r, actor, activitydb.Entry{ + EventType: activitydb.EventAccessUpdate, + Source: source, + Path: path, + Details: activitydb.Details{ + Source: source, + Path: path, + Changes: changes, + }, + }) +} + +func RecordAccessDelete(r *http.Request, actor *Actor, source, path string, changes []activitydb.FieldChange) { + RecordUser(r, actor, activitydb.Entry{ + EventType: activitydb.EventAccessDelete, + Source: source, + Path: path, + Details: activitydb.Details{ + Source: source, + Path: path, + Changes: changes, + }, + }) +} + +func AccessRuleCreateChanges(allow bool, ruleCategory, value string) []activitydb.FieldChange { + ruleType := "deny" + if allow { + ruleType = "allow" + } + changes := []activitydb.FieldChange{ + {Field: "ruleType", To: ruleType}, + {Field: "ruleCategory", To: ruleCategory}, + } + if value != "" { + changes = append(changes, activitydb.FieldChange{Field: "value", To: value}) + } + return changes +} + +func AccessRuleDeleteChanges(ruleType, ruleCategory, value string, cascade bool, count int) []activitydb.FieldChange { + changes := []activitydb.FieldChange{ + {Field: "ruleType", To: ruleType}, + {Field: "ruleCategory", To: ruleCategory}, + } + if value != "" { + changes = append(changes, activitydb.FieldChange{Field: "value", To: value}) + } + if cascade { + changes = append(changes, activitydb.FieldChange{Field: "cascade", To: "true"}) + if count > 0 { + changes = append(changes, activitydb.FieldChange{Field: "count", To: strconv.Itoa(count)}) + } + } + return changes +} + +func scopesToActivityDetails(target *users.User) []activitydb.ScopeDetail { + if target == nil { + return nil + } + frontend := target.GetFrontendScopes() + out := make([]activitydb.ScopeDetail, 0, len(frontend)) + for _, s := range frontend { + out = append(out, activitydb.ScopeDetail{ + Source: s.Name, + Path: s.Scope, + }) + } + return out +} + +func RecordUserMutation(r *http.Request, actor *Actor, eventType activitydb.EventType, target *users.User, changes []activitydb.FieldChange) { + if actor == nil || actor.User == nil || target == nil { + return + } + details := activitydb.Details{ + TargetUsername: target.Username, + Changes: changes, + } + if eventType == activitydb.EventUserCreate { + details.Scopes = scopesToActivityDetails(target) + } + RecordUser(r, actor, activitydb.Entry{ + EventType: eventType, + Details: details, + }) +} + +func RecordTokenMutation(r *http.Request, actor *Actor, eventType activitydb.EventType, affectedTokenName string) { + RecordUser(r, actor, activitydb.Entry{ + EventType: eventType, + Details: activitydb.Details{ + AffectedTokenName: affectedTokenName, + }, + }) +} + +func RecordAuth(r *http.Request, user *users.User, eventType activitydb.EventType, details activitydb.Details) { + if user == nil || user.ID == 0 { + return + } + entry := activitydb.Entry{ + UserID: user.ID, + EventType: eventType, + Details: details, + CreatedAt: time.Now().Unix(), + } + if r != nil { + entry.IPAddress = remoteIP(r) + } + recordEntry(entry) +} + +func RecordLogin(r *http.Request, user *users.User) { + if user == nil { + return + } + RecordAuth(r, user, activitydb.EventLogin, activitydb.Details{ + LoginMethod: string(user.LoginMethod), + }) +} + +func RecordTool(r *http.Request, actor *Actor, eventType activitydb.EventType, details activitydb.Details) { + RecordUser(r, actor, activitydb.Entry{ + EventType: eventType, + Details: details, + }) +} diff --git a/backend/internal/activity/record_test.go b/backend/internal/activity/record_test.go new file mode 100644 index 0000000000..4d4fe2e5e2 --- /dev/null +++ b/backend/internal/activity/record_test.go @@ -0,0 +1,37 @@ +package activity + +import ( + "testing" + + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" +) + +func TestAccessRuleCreateChanges(t *testing.T) { + changes := AccessRuleCreateChanges(false, "user", "admin") + if len(changes) != 3 { + t.Fatalf("expected 3 changes, got %d", len(changes)) + } + assertFieldChange(t, changes[0], "ruleType", "", "deny") + assertFieldChange(t, changes[1], "ruleCategory", "", "user") + assertFieldChange(t, changes[2], "value", "", "admin") +} + +func TestAccessRuleDeleteChanges(t *testing.T) { + changes := AccessRuleDeleteChanges("deny", "user", "admin", true, 3) + if len(changes) != 5 { + t.Fatalf("expected 5 changes, got %d", len(changes)) + } + assertFieldChange(t, changes[0], "ruleType", "", "deny") + assertFieldChange(t, changes[1], "ruleCategory", "", "user") + assertFieldChange(t, changes[2], "value", "", "admin") + assertFieldChange(t, changes[3], "cascade", "", "true") + assertFieldChange(t, changes[4], "count", "", "3") +} + +func assertFieldChange(t *testing.T, change activitydb.FieldChange, field, from, to string) { + t.Helper() + if change.Field != field || change.From != from || change.To != to { + t.Fatalf("unexpected change: got {field:%q from:%q to:%q}, want {field:%q from:%q to:%q}", + change.Field, change.From, change.To, field, from, to) + } +} diff --git a/backend/internal/activity/recorder.go b/backend/internal/activity/recorder.go new file mode 100644 index 0000000000..5a3f727135 --- /dev/null +++ b/backend/internal/activity/recorder.go @@ -0,0 +1,226 @@ +package activity + +import ( + "sync" + "time" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/sqldb" + "github.com/gtsteffaniak/go-logger/logger" +) + +// Store persists buffered activity entries. +type Store interface { + BulkInsertActivity(entries []activitydb.Entry) error + PurgeActivityBefore(cutoffUnix int64) (int64, error) +} + +// Recorder buffers activity entries and flushes them to SQLite in batches. +type Recorder struct { + store Store + + mu sync.Mutex + buffer []activitydb.Entry + + flushCh chan struct{} + stopCh chan struct{} + doneCh chan struct{} + + maxBuffer int + flushInterval time.Duration + retentionDays int + enabled bool + stopped bool +} + +var ( + globalRecorder *Recorder + globalMu sync.RWMutex +) + +// Initialize starts the global activity recorder. +func Initialize(store *sqldb.SQLStore, cfg settings.Database) { + globalMu.Lock() + defer globalMu.Unlock() + + if globalRecorder != nil { + globalRecorder.Stop() + } + + act := cfg.Activity + maxBuffer := act.MaxBufferSize + if maxBuffer <= 0 { + maxBuffer = 10000 + } + flushSeconds := act.FlushIntervalSeconds + if flushSeconds <= 0 { + flushSeconds = 10 + } + retentionDays := act.RetentionDays + if retentionDays <= 0 { + retentionDays = 30 + } + + r := &Recorder{ + store: store, + buffer: make([]activitydb.Entry, 0, 256), + flushCh: make(chan struct{}, 1), + stopCh: make(chan struct{}), + doneCh: make(chan struct{}), + maxBuffer: maxBuffer, + flushInterval: time.Duration(flushSeconds) * time.Second, + retentionDays: retentionDays, + enabled: !act.Disabled, + } + globalRecorder = r + go r.loop() + + if r.enabled { + if n, err := r.purgeExpired(); err != nil { + logger.Warningf("activity retention purge on startup failed: %v", err) + } else if n > 0 { + logger.Infof("activity retention purge removed %d rows on startup", n) + } + } +} + +// Record appends an activity entry to the buffer (non-blocking). +func Record(entry activitydb.Entry) { + globalMu.RLock() + r := globalRecorder + globalMu.RUnlock() + if r == nil || !r.enabled { + return + } + if entry.CreatedAt == 0 { + entry.CreatedAt = time.Now().Unix() + } + if !entry.EventType.Valid() { + return + } + + r.mu.Lock() + if r.stopped { + r.mu.Unlock() + return + } + r.buffer = append(r.buffer, entry) + shouldFlush := len(r.buffer) >= r.maxBuffer + r.mu.Unlock() + + if shouldFlush { + r.signalFlush() + } +} + +// Stop flushes pending entries and stops the background loop. +func Stop() { + globalMu.Lock() + r := globalRecorder + globalRecorder = nil + globalMu.Unlock() + if r != nil { + r.Stop() + } +} + +// Stop flushes and shuts down the recorder instance. +func (r *Recorder) Stop() { + close(r.stopCh) + <-r.doneCh + r.mu.Lock() + r.stopped = true + r.mu.Unlock() + r.flush() +} + +func (r *Recorder) loop() { + defer close(r.doneCh) + ticker := time.NewTicker(r.flushInterval) + defer ticker.Stop() + + purgeTicker := time.NewTicker(24 * time.Hour) + defer purgeTicker.Stop() + + for { + select { + case <-r.stopCh: + return + case <-ticker.C: + r.flush() + case <-r.flushCh: + r.flush() + case <-purgeTicker.C: + if r.enabled { + if n, err := r.purgeExpired(); err != nil { + logger.Warningf("activity retention purge failed: %v", err) + } else if n > 0 { + logger.Debugf("activity retention purge removed %d rows", n) + } + } + } + } +} + +func (r *Recorder) signalFlush() { + select { + case r.flushCh <- struct{}{}: + default: + } +} + +func (r *Recorder) flush() { + r.mu.Lock() + if len(r.buffer) == 0 { + r.mu.Unlock() + return + } + batch := r.buffer + r.buffer = make([]activitydb.Entry, 0, 256) + r.mu.Unlock() + + if err := r.store.BulkInsertActivity(batch); err != nil { + logger.Errorf("activity flush failed (%d entries): %v", len(batch), err) + time.Sleep(100 * time.Millisecond) + if retryErr := r.store.BulkInsertActivity(batch); retryErr == nil { + return + } + r.mu.Lock() + // Re-queue at front, cap to avoid unbounded growth on persistent failure. + combined := append(batch, r.buffer...) + if len(combined) > r.maxBuffer { + combined = combined[len(combined)-r.maxBuffer:] + } + r.buffer = combined + r.mu.Unlock() + } +} + +func (r *Recorder) purgeExpired() (int64, error) { + cutoff := time.Now().Add(-time.Duration(r.retentionDays) * 24 * time.Hour).Unix() + return r.store.PurgeActivityBefore(cutoff) +} + +// FlushNow forces a flush (for tests). +func FlushNow() { + globalMu.RLock() + r := globalRecorder + globalMu.RUnlock() + if r != nil { + r.flush() + } +} + +// BufferLen returns current buffer size (for tests). +func BufferLen() int { + globalMu.RLock() + r := globalRecorder + globalMu.RUnlock() + if r == nil { + return 0 + } + r.mu.Lock() + defer r.mu.Unlock() + return len(r.buffer) +} diff --git a/backend/internal/activity/recorder_test.go b/backend/internal/activity/recorder_test.go new file mode 100644 index 0000000000..17e5139fb3 --- /dev/null +++ b/backend/internal/activity/recorder_test.go @@ -0,0 +1,249 @@ +package activity + +import ( + "sync" + "testing" + "time" + + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +type mockActivityStore struct { + mu sync.Mutex + inserts [][]activitydb.Entry +} + +func (m *mockActivityStore) BulkInsertActivity(entries []activitydb.Entry) error { + m.mu.Lock() + defer m.mu.Unlock() + copied := append([]activitydb.Entry(nil), entries...) + m.inserts = append(m.inserts, copied) + return nil +} + +func (m *mockActivityStore) PurgeActivityBefore(cutoffUnix int64) (int64, error) { + return 0, nil +} + +func (m *mockActivityStore) batchCount() int { + m.mu.Lock() + defer m.mu.Unlock() + total := 0 + for _, b := range m.inserts { + total += len(b) + } + return total +} + +func TestRecorderFlushesOnMaxBuffer(t *testing.T) { + store := &mockActivityStore{} + globalMu.Lock() + old := globalRecorder + globalMu.Unlock() + defer func() { + globalMu.Lock() + globalRecorder = old + globalMu.Unlock() + }() + + r := &Recorder{ + store: store, + buffer: make([]activitydb.Entry, 0, 4), + flushCh: make(chan struct{}, 1), + stopCh: make(chan struct{}), + doneCh: make(chan struct{}), + maxBuffer: 3, + flushInterval: time.Hour, + enabled: true, + } + globalMu.Lock() + globalRecorder = r + globalMu.Unlock() + go r.loop() + + for i := 0; i < 3; i++ { + Record(activitydb.Entry{ + UserID: 1, + EventType: activitydb.EventDownload, + CreatedAt: time.Now().Unix(), + }) + } + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if store.batchCount() >= 3 { + break + } + time.Sleep(10 * time.Millisecond) + } + r.Stop() + + if store.batchCount() < 3 { + t.Fatalf("expected at least 3 flushed rows, got %d", store.batchCount()) + } +} + +func TestRecorderTimerFlush(t *testing.T) { + store := &mockActivityStore{} + globalMu.Lock() + old := globalRecorder + globalMu.Unlock() + defer func() { + globalMu.Lock() + globalRecorder = old + globalMu.Unlock() + }() + + r := &Recorder{ + store: store, + buffer: make([]activitydb.Entry, 0, 4), + flushCh: make(chan struct{}, 1), + stopCh: make(chan struct{}), + doneCh: make(chan struct{}), + maxBuffer: 10000, + flushInterval: 50 * time.Millisecond, + enabled: true, + } + globalMu.Lock() + globalRecorder = r + globalMu.Unlock() + go r.loop() + + Record(activitydb.Entry{ + UserID: 2, + EventType: activitydb.EventUpload, + CreatedAt: time.Now().Unix(), + }) + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if store.batchCount() >= 1 { + break + } + time.Sleep(10 * time.Millisecond) + } + r.Stop() + + if store.batchCount() < 1 { + t.Fatal("expected timer flush to persist entry") + } +} + +func TestRecorderAcceptsAnonymousUserID(t *testing.T) { + store := &mockActivityStore{} + globalMu.Lock() + old := globalRecorder + globalMu.Unlock() + defer func() { + globalMu.Lock() + globalRecorder = old + globalMu.Unlock() + }() + + r := &Recorder{ + store: store, + buffer: make([]activitydb.Entry, 0, 4), + flushCh: make(chan struct{}, 1), + stopCh: make(chan struct{}), + doneCh: make(chan struct{}), + maxBuffer: 10000, + flushInterval: 50 * time.Millisecond, + enabled: true, + } + globalMu.Lock() + globalRecorder = r + globalMu.Unlock() + go r.loop() + + Record(activitydb.Entry{ + UserID: 0, + EventType: activitydb.EventDownload, + CreatedAt: time.Now().Unix(), + Details: activitydb.Details{ShareHash: "legacy-test"}, + }) + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if store.batchCount() >= 1 { + break + } + time.Sleep(10 * time.Millisecond) + } + r.Stop() + + if store.batchCount() < 1 { + t.Fatal("expected anonymous (user_id 0) entry to be recorded") + } +} + +func TestInitializeDisabledNoOp(t *testing.T) { + Initialize(nil, settings.Database{Activity: settings.ActivityConfig{Disabled: true}}) + if BufferLen() != 0 { + t.Fatalf("expected disabled recorder buffer len 0") + } + Stop() +} + +func TestRecorderRecordStopRace(t *testing.T) { + store := &mockActivityStore{} + globalMu.Lock() + old := globalRecorder + globalMu.Unlock() + defer func() { + globalMu.Lock() + globalRecorder = old + globalMu.Unlock() + }() + + r := &Recorder{ + store: store, + buffer: make([]activitydb.Entry, 0, 512), + flushCh: make(chan struct{}, 1), + stopCh: make(chan struct{}), + doneCh: make(chan struct{}), + maxBuffer: 10000, + flushInterval: time.Hour, + enabled: true, + } + globalMu.Lock() + globalRecorder = r + globalMu.Unlock() + go r.loop() + + // Seed one valid entry so the flush assertion is deterministic. + Record(activitydb.Entry{ + UserID: 1, + EventType: activitydb.EventDownload, + CreatedAt: time.Now().Unix(), + }) + + stopDone := make(chan struct{}) + go func() { + defer close(stopDone) + Stop() + }() + + const total = 200 + var wg sync.WaitGroup + wg.Add(total) + for i := 0; i < total; i++ { + go func() { + defer wg.Done() + Record(activitydb.Entry{ + UserID: 1, + EventType: activitydb.EventDownload, + CreatedAt: time.Now().Unix(), + }) + }() + } + wg.Wait() + <-stopDone + + if BufferLen() != 0 { + t.Fatalf("expected empty buffer after shutdown, got %d stranded entries", BufferLen()) + } + if got := store.batchCount(); got == 0 { + t.Fatal("expected flushed rows after Record/Stop race, got none") + } +} diff --git a/backend/internal/activity/remote.go b/backend/internal/activity/remote.go new file mode 100644 index 0000000000..91bd35d137 --- /dev/null +++ b/backend/internal/activity/remote.go @@ -0,0 +1,27 @@ +package activity + +import ( + "net" + "net/http" + "strings" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func remoteIP(r *http.Request) string { + cfg := &settings.Config + + xff := r.Header.Get("X-Forwarded-For") + if cfg.Http.TrustProxyHeaders && xff != "" { + ips := strings.Split(xff, ",") + return strings.TrimSpace(ips[0]) + } + + xri := r.Header.Get("X-Real-IP") + if cfg.Http.TrustProxyHeaders && xri != "" { + return xri + } + + ip, _, _ := net.SplitHostPort(r.RemoteAddr) + return ip +} diff --git a/backend/internal/activity/viewer.go b/backend/internal/activity/viewer.go new file mode 100644 index 0000000000..edff8b3bb3 --- /dev/null +++ b/backend/internal/activity/viewer.go @@ -0,0 +1,16 @@ +package activity + +import ( + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// PrepareItemsForViewer trims activity paths for non-admin viewers. +func PrepareItemsForViewer(items []activitydb.FrontendEntry, viewer *users.User) { + if viewer == nil || viewer.Permissions.Admin { + return + } + for i := range items { + items[i].TrimPathsForUser(viewer) + } +} diff --git a/backend/internal/activity/viewer_test.go b/backend/internal/activity/viewer_test.go new file mode 100644 index 0000000000..f0d43b4482 --- /dev/null +++ b/backend/internal/activity/viewer_test.go @@ -0,0 +1,54 @@ +package activity + +import ( + "testing" + + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func TestPrepareItemsForViewerTrimsNonAdminPaths(t *testing.T) { + viewer := &users.User{ + ID: 2, + FrontendUser: users.FrontendUser{ + Permissions: users.Permissions{Admin: false}, + }, + BackendScopes: []users.BackendScope{ + {Path: "/source", Scope: "/source/users/graham"}, + }, + } + items := []activitydb.FrontendEntry{{ + Source: "/source", + Path: "/source/users/graham/path/to/file", + Details: activitydb.FrontendDetails{ + Source: "/source", + Paths: []string{"/source/users/graham/path/to/file"}, + }, + }} + + PrepareItemsForViewer(items, viewer) + + if items[0].Path != "/path/to/file" { + t.Fatalf("Path = %q, want /path/to/file", items[0].Path) + } + if items[0].Details.Paths[0] != "/path/to/file" { + t.Fatalf("Details.Paths[0] = %q, want /path/to/file", items[0].Details.Paths[0]) + } +} + +func TestPrepareItemsForViewerSkipsAdmin(t *testing.T) { + admin := &users.User{ + ID: 1, + FrontendUser: users.FrontendUser{ + Permissions: users.Permissions{Admin: true}, + }, + } + items := []activitydb.FrontendEntry{{ + Source: "/source", + Path: "/source/users/graham/path/to/file", + }} + PrepareItemsForViewer(items, admin) + if items[0].Path != "/source/users/graham/path/to/file" { + t.Fatalf("admin path should remain untrimmed, got %q", items[0].Path) + } +} diff --git a/backend/adapters/fs/diskcache/cache.go b/backend/internal/adapters/fs/diskcache/cache.go similarity index 100% rename from backend/adapters/fs/diskcache/cache.go rename to backend/internal/adapters/fs/diskcache/cache.go diff --git a/backend/adapters/fs/diskcache/file_cache.go b/backend/internal/adapters/fs/diskcache/file_cache.go similarity index 98% rename from backend/adapters/fs/diskcache/file_cache.go rename to backend/internal/adapters/fs/diskcache/file_cache.go index 3ec2107f73..d34ae2fe83 100644 --- a/backend/adapters/fs/diskcache/file_cache.go +++ b/backend/internal/adapters/fs/diskcache/file_cache.go @@ -11,7 +11,7 @@ import ( "path/filepath" "sync" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" "github.com/gtsteffaniak/go-logger/logger" ) diff --git a/backend/adapters/fs/diskcache/file_cache_test.go b/backend/internal/adapters/fs/diskcache/file_cache_test.go similarity index 96% rename from backend/adapters/fs/diskcache/file_cache_test.go rename to backend/internal/adapters/fs/diskcache/file_cache_test.go index 3d2a01a158..235015c155 100644 --- a/backend/adapters/fs/diskcache/file_cache_test.go +++ b/backend/internal/adapters/fs/diskcache/file_cache_test.go @@ -6,7 +6,7 @@ import ( "path/filepath" "testing" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" "github.com/stretchr/testify/require" ) diff --git a/backend/adapters/fs/diskcache/noop_cache.go b/backend/internal/adapters/fs/diskcache/noop_cache.go similarity index 100% rename from backend/adapters/fs/diskcache/noop_cache.go rename to backend/internal/adapters/fs/diskcache/noop_cache.go diff --git a/backend/adapters/fs/files/content_test.go b/backend/internal/adapters/fs/files/content_test.go similarity index 100% rename from backend/adapters/fs/files/content_test.go rename to backend/internal/adapters/fs/files/content_test.go diff --git a/backend/adapters/fs/files/file_test.go b/backend/internal/adapters/fs/files/file_test.go similarity index 97% rename from backend/adapters/fs/files/file_test.go rename to backend/internal/adapters/fs/files/file_test.go index 02ad0ea16c..f1847c80c9 100644 --- a/backend/adapters/fs/files/file_test.go +++ b/backend/internal/adapters/fs/files/file_test.go @@ -11,12 +11,12 @@ import ( "testing" "time" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - liberrors "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - dbsql "github.com/gtsteffaniak/filebrowser/backend/database/sql" - "github.com/gtsteffaniak/filebrowser/backend/indexing" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + liberrors "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + dbsql "github.com/gtsteffaniak/filebrowser/backend/internal/database/sql" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" ) func Test_GetRealPath(t *testing.T) { @@ -600,7 +600,11 @@ func TestDeleteFilesRootProtection(t *testing.T) { // accidentally delete the root. // Regression test for path handling bug where /srv/srv could be mistaken for /srv. func TestDeleteFilesSubfolderWithRootName(t *testing.T) { - for iter := 1; iter <= raceStressIterations; iter++ { + iters := raceStressIterations + if testing.Short() { + iters = 1 + } + for iter := 1; iter <= iters; iter++ { iter := iter t.Run(fmt.Sprintf("stress-iter-%d", iter), func(t *testing.T) { runDeleteFilesSubfolderWithRaceStress(t, iter) diff --git a/backend/internal/adapters/fs/files/fileinfo_listing_test.go b/backend/internal/adapters/fs/files/fileinfo_listing_test.go new file mode 100644 index 0000000000..d7c4d16fef --- /dev/null +++ b/backend/internal/adapters/fs/files/fileinfo_listing_test.go @@ -0,0 +1,52 @@ +package files + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" +) + +func TestNormalizeFileInfoListing_fileOmitsChildren(t *testing.T) { + info := &iteminfo.ExtendedFileInfo{ + FileInfo: iteminfo.FileInfo{ + ItemInfo: iteminfo.ItemInfo{ + Name: "readme.txt", + Type: "text/plain; charset=utf-8", + }, + Files: []iteminfo.ExtendedItemInfo{{}}, + Folders: []iteminfo.ItemInfo{{Name: "docs", Type: "directory"}}, + }, + } + normalizeFileInfoListing(info) + if info.Files != nil || info.Folders != nil { + t.Fatalf("expected nil files/folders for non-directory, got files=%v folders=%v", info.Files, info.Folders) + } + raw, err := json.Marshal(info) + if err != nil { + t.Fatalf("marshal: %v", err) + } + body := string(raw) + if strings.Contains(body, `"files"`) || strings.Contains(body, `"folders"`) { + t.Fatalf("expected files/folders omitted for file response, got %s", body) + } +} + +func TestNormalizeFileInfoListing_directoryUsesEmptySlicesNotNull(t *testing.T) { + info := &iteminfo.ExtendedFileInfo{ + FileInfo: iteminfo.FileInfo{ + ItemInfo: iteminfo.ItemInfo{ + Name: "docs", + Type: "directory", + }, + }, + } + normalizeFileInfoListing(info) + if info.Files == nil || info.Folders == nil { + t.Fatal("expected non-nil empty slices for directory") + } + if len(info.Files) != 0 || len(info.Folders) != 0 { + t.Fatalf("expected empty slices, got files=%d folders=%d", len(info.Files), len(info.Folders)) + } +} diff --git a/backend/adapters/fs/files/files.go b/backend/internal/adapters/fs/files/files.go similarity index 85% rename from backend/adapters/fs/files/files.go rename to backend/internal/adapters/fs/files/files.go index a7c1651dc3..3f34d480c7 100644 --- a/backend/adapters/fs/files/files.go +++ b/backend/internal/adapters/fs/files/files.go @@ -14,28 +14,28 @@ import ( "time" "github.com/dhowden/tag" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/access" - "github.com/gtsteffaniak/filebrowser/backend/database/share" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/filebrowser/backend/ffmpeg" - "github.com/gtsteffaniak/filebrowser/backend/indexing" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + "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/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/ffmpeg" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" "github.com/gtsteffaniak/go-logger/logger" ) var reDuration = regexp.MustCompile(`^\[(?:(\d{1,2}):)?(\d{1,2}):(\d{1,2})\.(\d+)\](.*)`) // CheckPermissionsFunc allows tests to override CheckPermissions behavior -var CheckPermissionsFunc = checkPermissionsImpl +var CheckPermissionsFunc = func(opts utils.FileOptions, user *users.User) (string, string, error) { + return checkPermissionsImpl(opts, user, svc()) +} // addMetadataToChildren runs concurrent ffmpeg/tag extraction for audio/video children. // Each goroutine is registered on wg. Caller must invoke wg.Wait() after scheduling. func addMetadataToChildren(response *iteminfo.ExtendedFileInfo, opts utils.FileOptions, wg *sync.WaitGroup) { - sharedFFmpegService := ffmpeg.NewFFmpegService(10, false, "") + sharedFFmpegService := ffmpeg.Get() if sharedFFmpegService == nil { return } @@ -76,7 +76,7 @@ func processDirectoryMetadata(response *iteminfo.ExtendedFileInfo, idx *indexing var wg sync.WaitGroup wg.Go(func() { - indexPath := idx.MakeIndexPath(response.Path, true) + indexPath := idx.MakeIndexPath(response.Path, true).String() err := idx.RefreshDirectory(indexPath, false) if err != nil { logger.Debugf("Failed to refresh directory for folder size update: %v", err) @@ -105,16 +105,28 @@ func finalizeResponse(response *iteminfo.ExtendedFileInfo, info *iteminfo.FileIn } } +// normalizeFileInfoListing shapes files/folders for FileInfoFaster JSON: +// non-directories omit children (nil + omitempty); directories use empty slices instead of null. +func normalizeFileInfoListing(info *iteminfo.ExtendedFileInfo) { + if info == nil { + return + } + if info.Type == "directory" { + info.Files = utils.NonNilSlice(info.Files) + info.Folders = utils.NonNilSlice(info.Folders) + return + } + info.Files = nil + info.Folders = nil +} + // CheckPermissions validates user access and returns the resolved index path and user scope -func CheckPermissions(opts utils.FileOptions, access *access.Storage, user *users.User) (string, string, error) { - return CheckPermissionsFunc(opts, access, user) +func CheckPermissions(opts utils.FileOptions, user *users.User) (string, string, error) { + return CheckPermissionsFunc(opts, user) } // checkPermissionsImpl is the actual implementation of CheckPermissions -func checkPermissionsImpl(opts utils.FileOptions, access *access.Storage, user *users.User) (string, string, error) { - if access == nil { - return "", "", fmt.Errorf("access not provided") - } +func checkPermissionsImpl(opts utils.FileOptions, user *users.User, s *Service) (string, string, error) { if user == nil { return "", "", fmt.Errorf("user not provided") } @@ -137,16 +149,17 @@ func checkPermissionsImpl(opts utils.FileOptions, access *access.Storage, user * return "", "", fmt.Errorf("user has no access to source: %v", opts.Source) } - safePath, err := utils.SanitizeUserPath(opts.Path) + safePath, err := utils.SanitizePath(opts.Path) if err != nil { return "", "", errors.ErrAccessDenied } - // Combine scope + sanitized path indexPath := utils.JoinPathAsUnix(userScope, safePath) - // Layer 1: USER ACCESS CONTROL - // Quick check: Does THIS user have permission? - if !access.Permitted(idx.Path, indexPath, user.Username) { + parsedPath, err := utils.ParseSanitizedIndexPath(indexPath, true) + if err != nil { + return "", "", errors.ErrAccessDenied + } + if !s.accessPermitted(idx.Path, parsedPath, user.Username) { return indexPath, "", errors.ErrAccessDenied } return indexPath, userScope, nil @@ -171,9 +184,13 @@ func filterFilesByExt(files []iteminfo.ExtendedItemInfo, hideFileExt string) []i return filtered } -func GetDirItems(opts utils.FileOptions, access *access.Storage, user *users.User) (Items, error) { +func GetDirItems(opts utils.FileOptions, user *users.User) (Items, error) { + return getDirItemsImpl(opts, user, svc()) +} + +func getDirItemsImpl(opts utils.FileOptions, user *users.User, s *Service) (Items, error) { items := Items{} - indexPath, _, topLevelErr := CheckPermissions(opts, access, user) + indexPath, _, topLevelErr := checkPermissionsImpl(opts, user, s) accessRulesErr := topLevelErr != nil && topLevelErr == errors.ErrAccessDenied && indexPath != "" if topLevelErr != nil && !accessRulesErr { return items, topLevelErr @@ -197,7 +214,7 @@ func GetDirItems(opts utils.FileOptions, access *access.Storage, user *users.Use if info.Type != "directory" { return items, fmt.Errorf("path is not a directory: %v ", indexPath) } - if err := access.CheckChildItemAccess(info, idx, user.Username); err != nil { + if err := s.checkChildItemAccess(info, idx, user.Username); err != nil { return items, err } hasAccessibleItems := len(info.Files) > 0 || len(info.Folders) > 0 @@ -221,16 +238,18 @@ func GetDirItems(opts utils.FileOptions, access *access.Storage, user *users.Use } // FileInfoFasterFunc is a variable that can be mocked in tests -var FileInfoFasterFunc = fileInfoFasterImpl +var FileInfoFasterFunc = func(opts utils.FileOptions, user *users.User) (*iteminfo.ExtendedFileInfo, error) { + return fileInfoFasterImpl(opts, user, svc()) +} -func FileInfoFaster(opts utils.FileOptions, access *access.Storage, user *users.User, shareStore *share.Storage) (*iteminfo.ExtendedFileInfo, error) { - return FileInfoFasterFunc(opts, access, user, shareStore) +func FileInfoFaster(opts utils.FileOptions, user *users.User) (*iteminfo.ExtendedFileInfo, error) { + return FileInfoFasterFunc(opts, user) } // fileInfoFasterImpl is the actual implementation of FileInfoFaster -func fileInfoFasterImpl(opts utils.FileOptions, access *access.Storage, user *users.User, shareStore *share.Storage) (*iteminfo.ExtendedFileInfo, error) { +func fileInfoFasterImpl(opts utils.FileOptions, user *users.User, s *Service) (*iteminfo.ExtendedFileInfo, error) { response := &iteminfo.ExtendedFileInfo{} - indexPath, userScope, topLevelErr := CheckPermissions(opts, access, user) + indexPath, userScope, topLevelErr := checkPermissionsImpl(opts, user, s) accessRulesErr := topLevelErr != nil && topLevelErr == errors.ErrAccessDenied && indexPath != "" if topLevelErr != nil && !accessRulesErr { return response, topLevelErr @@ -255,7 +274,7 @@ func fileInfoFasterImpl(opts utils.FileOptions, access *access.Storage, user *us } // otherwise response keeps unfiltered Folders/Files while CheckChildItemAccess only mutates info. if info.Type == "directory" { - if err := access.CheckChildItemAccess(info, idx, user.Username); err != nil { + if err := s.checkChildItemAccess(info, idx, user.Username); err != nil { return response, err } } @@ -268,20 +287,20 @@ func fileInfoFasterImpl(opts utils.FileOptions, access *access.Storage, user *us response.FileInfo = *info response.RealPath = filepath.Join(idx.Path, indexPath) response.Source = opts.Source - if shareStore != nil && user.Permissions.Share && opts.ShowSharedAttr { + if user.Permissions.Share && opts.ShowSharedAttr { for i := range response.Files { file := &response.Files[i] - file.IsShared = shareStore.IsShared(response.Path+file.Name, idx.Path, user.ID) + file.IsShared = s.pathIsShared(response.Path+file.Name, idx.Path, user.ID) } for i := range response.Folders { folder := &response.Folders[i] - folder.IsShared = shareStore.IsShared(response.Path+folder.Name, idx.Path, user.ID) + folder.IsShared = s.pathIsShared(response.Path+folder.Name, idx.Path, user.ID) } - response.IsShared = shareStore.IsShared(response.Path, idx.Path, user.ID) + response.IsShared = s.pathIsShared(response.Path, idx.Path, user.ID) } if info.Type == "directory" && opts.ShowPinnedItems { - if opts.ShareHash != "" && shareStore != nil { - if link, err := shareStore.GetByHash(opts.ShareHash); err == nil { + if opts.ShareHash != "" { + if link, ok := s.shareByHash(opts.ShareHash); ok { if shareRelDir, err := link.ShareRelativeDir(response.Path); err == nil { response.PinnedItems = link.PinnedItems.NamesForDirectory(shareRelDir) } @@ -291,7 +310,10 @@ func fileInfoFasterImpl(opts utils.FileOptions, access *access.Storage, user *us } } - defer finalizeResponse(response, info, response.RealPath, user, userScope) + defer func() { + finalizeResponse(response, info, response.RealPath, user, userScope) + normalizeFileInfoListing(response) + }() if opts.SkipExtendedAttrs { if info.Type == "directory" && opts.HideFileExt != "" { response.Files = filterFilesByExt(response.Files, opts.HideFileExt) @@ -502,10 +524,9 @@ func extractAudioMetadata(ctx context.Context, item *iteminfo.ExtendedItemInfo, // Extract duration ONLY if explicitly requested using the ffmpeg VideoService // This respects concurrency limits and gracefully handles missing ffmpeg if getDuration { - // Use provided service or create a new one for backward compatibility service := ffmpegService if service == nil { - service = ffmpeg.NewFFmpegService(5, false, "") + service = ffmpeg.Get() } if service != nil { if duration, err := service.GetMediaDuration(ctx, realPath); err == nil { @@ -562,26 +583,45 @@ func ExtractLyrics(realPath string) ([]iteminfo.Lyric, error) { return lyrics, nil } -// extractVideoMetadata extracts duration from video files using ffprobe +// extractVideoMetadata extracts duration and codec info from video files using ffprobe. // If ffmpegService is nil, a new service will be created (for backward compatibility) func extractVideoMetadata(ctx context.Context, item *iteminfo.ExtendedItemInfo, realPath string, ffmpegService *ffmpeg.FFmpegService) error { - // Use provided service or create a new one for backward compatibility service := ffmpegService if service == nil { - service = ffmpeg.NewFFmpegService(10, false, "") + service = ffmpeg.Get() } - if service != nil { - duration, err := service.GetMediaDuration(ctx, realPath) - if err != nil { + if service == nil { + return nil + } + + info, err := service.ProbeFile(ctx, realPath) + if err != nil { + duration, durErr := service.GetMediaDuration(ctx, realPath) + if durErr != nil { return err } if duration > 0 { - item.Metadata = &iteminfo.MediaMetadata{ - Duration: int(duration), - } + item.Metadata = &iteminfo.MediaMetadata{Duration: int(duration)} } return nil } + + meta := &iteminfo.MediaMetadata{} + if info.Duration > 0 { + meta.Duration = int(info.Duration) + } + if info.VideoCodec != "" { + meta.VideoCodec = info.VideoCodec + } + if info.AudioCodec != "" { + meta.AudioCodec = info.AudioCodec + } + if info.FormatName != "" { + meta.Container = info.FormatName + } + if meta.Duration > 0 || meta.VideoCodec != "" || meta.AudioCodec != "" || meta.Container != "" { + item.Metadata = meta + } return nil } @@ -597,7 +637,7 @@ func DeleteFiles(source, absPath string, isDir bool) error { } if !index.Config.ResolvedRules.IndexingDisabled { - indexPath := index.MakeIndexPath(absPath, isDir) + indexPath := index.MakeIndexPath(absPath, isDir).String() // Perform the physical deletion err := os.RemoveAll(absPath) @@ -617,7 +657,7 @@ func DeleteFiles(source, absPath string, isDir bool) error { // Refresh the parent directory to recalculate sizes and update counts refreshConfig := utils.FileOptions{ - Path: index.MakeIndexPath(filepath.Dir(absPath), true), + Path: index.MakeIndexPath(filepath.Dir(absPath), true).String(), IsDir: true, } err = index.RefreshFileInfo(refreshConfig) @@ -637,7 +677,7 @@ func RefreshIndex(source string, path string, isDir bool, recursive bool) error return nil } // Always normalize path using MakeIndexPath - path = idx.MakeIndexPath(path, isDir) + path = idx.MakeIndexPath(path, isDir).String() // Check if path is a symlink realPath, _, _ := idx.GetRealPath(path) @@ -708,7 +748,11 @@ func validateMoveDestination(src, dst string, isSrcDir bool) error { return nil } -func MoveResource(isSrcDir bool, sourceIndex, destIndex, realsrc, realdst string, s *share.Storage, a *access.Storage) error { +func MoveResource(isSrcDir bool, sourceIndex, destIndex, realsrc, realdst string) error { + return moveResourceImpl(isSrcDir, sourceIndex, destIndex, realsrc, realdst, svc()) +} + +func moveResourceImpl(isSrcDir bool, sourceIndex, destIndex, realsrc, realdst string, s *Service) error { // Check if source and destination are the same file if realsrc == realdst { return fmt.Errorf("cannot move a file to itself: %s", realsrc) @@ -730,7 +774,7 @@ func MoveResource(isSrcDir bool, sourceIndex, destIndex, realsrc, realdst string } // Prepare paths for index operations - srcIndexPath := srcIdx.MakeIndexPath(realsrc, isSrcDir) + srcIndexPath := srcIdx.MakeIndexPath(realsrc, isSrcDir).String() srcParentPath := filepath.Dir(realsrc) // Perform the physical move @@ -778,16 +822,15 @@ func MoveResource(isSrcDir bool, sourceIndex, destIndex, realsrc, realdst string } } - // Use backend source paths to match how shares are stored - go s.UpdateShares(srcIdx.Path, srcIdx.MakeIndexPath(realsrc, isSrcDir), dstIdx.Path, dstIdx.MakeIndexPath(realdst, isSrcDir)) //nolint:errcheck + // Share path reconciliation is handled by state.UpdateSharesForMovedResource (see http/resource.go). // Update access rules for the moved path - if a != nil { - // If moving within the same source, update the rules - if srcIdx.Path == dstIdx.Path { - go a.UpdateRules(srcIdx.Path, srcIdx.MakeIndexPath(realsrc, isSrcDir), dstIdx.MakeIndexPath(realdst, isSrcDir)) //nolint:errcheck - } - // Cross-source moves don't preserve access rules (they're source-specific) + if srcIdx.Path == dstIdx.Path { + go s.updateAccessRulesOnMove( + srcIdx.Path, + srcIdx.MakeIndexPath(realsrc, isSrcDir), + dstIdx.MakeIndexPath(realdst, isSrcDir), + ) } return nil diff --git a/backend/internal/adapters/fs/files/items_test.go b/backend/internal/adapters/fs/files/items_test.go new file mode 100644 index 0000000000..134aa1dd23 --- /dev/null +++ b/backend/internal/adapters/fs/files/items_test.go @@ -0,0 +1,51 @@ +package files + +import ( + "encoding/json" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" +) + +func TestItemsJSON_omitsEmptySlices(t *testing.T) { + items := Items{ + Files: utils.NonNilSlice([]string(nil)), + Folders: utils.NonNilSlice([]string(nil)), + } + raw, err := json.Marshal(items) + if err != nil { + t.Fatalf("marshal items: %v", err) + } + if string(raw) != "{}" { + t.Fatalf("JSON = %s, want {}", string(raw)) + } +} + +func TestItemsJSON_omitsEmptyFilesWhenFoldersPresent(t *testing.T) { + items := Items{ + Folders: []string{"docs"}, + } + raw, err := json.Marshal(items) + if err != nil { + t.Fatalf("marshal items: %v", err) + } + const want = `{"folders":["docs"]}` + if string(raw) != want { + t.Fatalf("JSON = %s, want %s", string(raw), want) + } +} + +func TestItemsJSON_marshalsPopulatedSlices(t *testing.T) { + items := Items{ + Files: []string{"a.txt"}, + Folders: []string{"docs"}, + } + raw, err := json.Marshal(items) + if err != nil { + t.Fatalf("marshal items: %v", err) + } + const want = `{"files":["a.txt"],"folders":["docs"]}` + if string(raw) != want { + t.Fatalf("JSON = %s, want %s", string(raw), want) + } +} diff --git a/backend/adapters/fs/files/mime.go b/backend/internal/adapters/fs/files/mime.go similarity index 100% rename from backend/adapters/fs/files/mime.go rename to backend/internal/adapters/fs/files/mime.go diff --git a/backend/internal/adapters/fs/files/service.go b/backend/internal/adapters/fs/files/service.go new file mode 100644 index 0000000000..dea3c3b7d2 --- /dev/null +++ b/backend/internal/adapters/fs/files/service.go @@ -0,0 +1,100 @@ +package files + +import ( + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/ports" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" +) + +// ChildAccessChecker filters directory listings by access rules. +type ChildAccessChecker interface { + CheckChildItemAccess(response *iteminfo.FileInfo, idx *indexing.Index, username string) error +} + +// Service performs filesystem operations with injected access and share dependencies. +type Service struct { + access ports.AccessGate + child ChildAccessChecker + shares ports.ShareReader +} + +var defaultService *Service + +// New constructs a file service with the given port implementations. +func New(access ports.AccessGate, child ChildAccessChecker, shares ports.ShareReader) *Service { + return &Service{access: access, child: child, shares: shares} +} + +// SetDefault registers the process-wide file service (called from app.WireServices). +func SetDefault(s *Service) { + defaultService = s +} + +func svc() *Service { + if defaultService != nil { + return defaultService + } + return &Service{} +} + +func (s *Service) accessPermitted(sourcePath string, indexPath utils.IndexPath, username string) bool { + if s.access == nil { + return true + } + return s.access.AccessPermitted(sourcePath, indexPath, username) +} + +func (s *Service) checkChildItemAccess(response *iteminfo.FileInfo, idx *indexing.Index, username string) error { + if s.child == nil { + return nil + } + return s.child.CheckChildItemAccess(response, idx, username) +} + +func (s *Service) pathIsShared(path, source string, userID uint64) bool { + if s.shares == nil { + return false + } + return s.shares.IsShared(source, path, userID) +} + +func (s *Service) shareByHash(hash string) (share.Share, bool) { + if s.shares == nil || hash == "" { + return share.Share{}, false + } + sh, err := s.shares.GetShare(hash) + if err != nil { + return share.Share{}, false + } + return sh, true +} + +func (s *Service) updateAccessRulesOnMove(sourcePath string, oldPath, newPath utils.IndexPath) { + if s.access == nil { + return + } + _, _ = s.access.UpdateAccessRulesOnMove(sourcePath, oldPath, newPath) +} + +// CheckPermissions validates user access and returns the resolved index path and user scope. +func (s *Service) CheckPermissions(opts utils.FileOptions, user *users.User) (string, string, error) { + return checkPermissionsImpl(opts, user, s) +} + +// FileInfoFaster returns extended file info with access filtering applied. +func (s *Service) FileInfoFaster(opts utils.FileOptions, user *users.User) (*iteminfo.ExtendedFileInfo, error) { + return fileInfoFasterImpl(opts, user, s) +} + +// GetDirItems lists directory entries visible to the user. +func (s *Service) GetDirItems(opts utils.FileOptions, user *users.User) (Items, error) { + return getDirItemsImpl(opts, user, s) +} + +// MoveResource moves a file or directory and updates access rules when needed. +func (s *Service) MoveResource(isSrcDir bool, sourceIndex, destIndex, realsrc, realdst string) error { + return moveResourceImpl(isSrcDir, sourceIndex, destIndex, realsrc, realdst, s) +} diff --git a/backend/adapters/fs/files/user.go b/backend/internal/adapters/fs/files/user.go similarity index 65% rename from backend/adapters/fs/files/user.go rename to backend/internal/adapters/fs/files/user.go index 7a0faac71f..5b7563f056 100644 --- a/backend/adapters/fs/files/user.go +++ b/backend/internal/adapters/fs/files/user.go @@ -5,9 +5,8 @@ import ( "os" "path/filepath" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" "github.com/gtsteffaniak/go-logger/logger" ) @@ -24,22 +23,15 @@ func MakeUserDirs(u *users.User, createDir bool) error { if cleanedUserName == "" || cleanedUserName == "-" || cleanedUserName == "." { return fmt.Errorf("MakeUserDirs: invalid user for home dir creation: [%s]", u.Username) } - for i, scope := range u.Scopes { - info, ok := users.ResolveSourceKey(scope.Name) + settings.ExpandBackendScopesForCreateUserDir(u) + for i, scope := range u.BackendScopes { + source, ok := settings.Config.Server.SourceMap[scope.Path] if !ok { - return fmt.Errorf("MakeUserDirs: source not found: %s", scope.Name) - } - source, ok := settings.Config.Server.SourceMap[info.Path] - if !ok { - return fmt.Errorf("MakeUserDirs: source not found: %s", scope.Name) + return fmt.Errorf("MakeUserDirs: source not found: %s", scope.Path) } fullPath := filepath.Join(source.Path, scope.Scope) parentDir := filepath.Dir(fullPath) if createDir { - if source.Config.CreateUserDir && filepath.Base(scope.Scope) != cleanedUserName { - scope.Scope = utils.JoinPathAsUnix(scope.Scope, cleanedUserName) - fullPath = filepath.Join(fullPath, cleanedUserName) - } if !Exists(parentDir) { if err := MakeUserDir(parentDir); err != nil { logger.Errorf("MakeUserDirs: failed to create parent scope directory: %s - %v", scope.Scope, err) @@ -55,8 +47,7 @@ func MakeUserDirs(u *users.User, createDir bool) error { return fmt.Errorf("MakeUserDirs: scope folder does not exist: %s", fullPath) } } - - u.Scopes[i] = scope + u.BackendScopes[i] = scope } return nil } diff --git a/backend/adapters/fs/fileutils/assets.go b/backend/internal/adapters/fs/fileutils/assets.go similarity index 83% rename from backend/adapters/fs/fileutils/assets.go rename to backend/internal/adapters/fs/fileutils/assets.go index 5b321e7cef..c1f125dd32 100644 --- a/backend/adapters/fs/fileutils/assets.go +++ b/backend/internal/adapters/fs/fileutils/assets.go @@ -1,36 +1,36 @@ -package fileutils - -import ( - "io/fs" - "net/http" -) - -var ( - assetFs fs.FS -) - -// Custom dirFS to handle both embedded and non-embedded file systems -type dirFS struct { - http.Dir -} - -// Implement the Open method for dirFS, which wraps http.Dir -func (d dirFS) Open(name string) (fs.File, error) { - return d.Dir.Open(name) -} - -// InitAssetFS initializes the asset filesystem for the application -// This should be called once during startup before http or preview services start -func InitAssetFS(embeddedAssets fs.FS, useEmbedded bool) { - if useEmbedded { - assetFs = embeddedAssets - } else { - // Dev mode: Serve files from http/dist directory - assetFs = dirFS{Dir: http.Dir("http/dist")} - } -} - -// GetAssetFS returns the initialized asset filesystem -func GetAssetFS() fs.FS { - return assetFs -} +package fileutils + +import ( + "io/fs" + "net/http" +) + +var ( + assetFs fs.FS +) + +// Custom dirFS to handle both embedded and non-embedded file systems +type dirFS struct { + http.Dir +} + +// Implement the Open method for dirFS, which wraps http.Dir +func (d dirFS) Open(name string) (fs.File, error) { + return d.Dir.Open(name) +} + +// InitAssetFS initializes the asset filesystem for the application +// This should be called once during startup before http or preview services start +func InitAssetFS(embeddedAssets fs.FS, useEmbedded bool) { + if useEmbedded { + assetFs = embeddedAssets + } else { + // Dev mode: Serve files from internal/web/dist directory + assetFs = dirFS{Dir: http.Dir("internal/web/dist")} + } +} + +// GetAssetFS returns the initialized asset filesystem +func GetAssetFS() fs.FS { + return assetFs +} diff --git a/backend/adapters/fs/fileutils/copy.go b/backend/internal/adapters/fs/fileutils/copy.go similarity index 100% rename from backend/adapters/fs/fileutils/copy.go rename to backend/internal/adapters/fs/fileutils/copy.go diff --git a/backend/adapters/fs/fileutils/dir.go b/backend/internal/adapters/fs/fileutils/dir.go similarity index 89% rename from backend/adapters/fs/fileutils/dir.go rename to backend/internal/adapters/fs/fileutils/dir.go index a939d872d4..8937f616a1 100644 --- a/backend/adapters/fs/fileutils/dir.go +++ b/backend/internal/adapters/fs/fileutils/dir.go @@ -53,6 +53,10 @@ func CopyDir(source, dest string) error { } } } + // Preserve directory mod times + if err := os.Chtimes(dest, srcinfo.ModTime(), srcinfo.ModTime()); err != nil { + errs = append(errs, err) + } var errString string for _, err := range errs { diff --git a/backend/adapters/fs/fileutils/file.go b/backend/internal/adapters/fs/fileutils/file.go similarity index 81% rename from backend/adapters/fs/fileutils/file.go rename to backend/internal/adapters/fs/fileutils/file.go index c8f137f94f..037cd957b3 100644 --- a/backend/adapters/fs/fileutils/file.go +++ b/backend/internal/adapters/fs/fileutils/file.go @@ -113,7 +113,7 @@ func copySingleFile(source, dest string) error { defer src.Close() // Create the destination directory if needed. - err = os.MkdirAll(filepath.Dir(dest), PermDir) + err = os.MkdirAll(filepath.Dir(dest), EffectiveDirPerm()) if err != nil { return err } @@ -139,14 +139,21 @@ func copySingleFile(source, dest string) error { // The file was copied successfully, so we continue logger.Debugf("Could not set file permissions for %s (this may be expected in restricted environments): %v", dest, err) } - + // Preserve source file mod time + if err := os.Chtimes(dest, srcInfo.ModTime(), srcInfo.ModTime()); err != nil { + logger.Debugf("Could not preserve modification time for %s: %v", dest, err) + } return nil } // copyDirectory handles copying directories recursively. func copyDirectory(source, dest string) error { + srcInfo, err := os.Stat(source) + if err != nil { + return err + } // Create the destination directory. - err := os.MkdirAll(dest, PermDir) + err = os.MkdirAll(dest, EffectiveDirPerm()) if err != nil { return err } @@ -176,8 +183,40 @@ func copyDirectory(source, dest string) error { } } } + return os.Chtimes(dest, srcInfo.ModTime(), srcInfo.ModTime()) +} - return nil +// PreserveModTimes copies the mod times from src onto dst, this is used by the webdav COPY handler +func PreserveModTimes(src, dst string) error { + info, err := os.Lstat(src) + if err != nil { + return err + } + if !info.IsDir() { + return os.Chtimes(dst, info.ModTime(), info.ModTime()) + } + return filepath.WalkDir(src, func(p string, d os.DirEntry, err error) error { + if err != nil { + logger.Debugf("Error accessing %s to set mod time: %v", p, err) + return nil + } + if d.IsDir() { + return nil + } + rel, err := filepath.Rel(src, p) + if err != nil { + return nil + } + info, err := d.Info() + if err != nil { + logger.Debugf("Error getting info for %s: %v", p, err) + return nil + } + if err := os.Chtimes(filepath.Join(dst, rel), info.ModTime(), info.ModTime()); err != nil { + logger.Debugf("Could not preserve modification time for %s: %v", filepath.Join(dst, rel), err) + } + return nil + }) } // CommonPrefix returns the common directory path of provided files. diff --git a/backend/internal/adapters/fs/fileutils/file_test.go b/backend/internal/adapters/fs/fileutils/file_test.go new file mode 100644 index 0000000000..36700ed65f --- /dev/null +++ b/backend/internal/adapters/fs/fileutils/file_test.go @@ -0,0 +1,119 @@ +package fileutils + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +func TestUnixModeToFileMode_setgid(t *testing.T) { + m := unixModeToFileMode(0o2770) + if got := m.Perm(); got != 0o770 { + t.Fatalf("Perm() = %#o, want 0770", got) + } + if m&os.ModeSetgid == 0 { + t.Fatal("expected ModeSetgid") + } + if m&os.ModeSetuid != 0 || m&os.ModeSticky != 0 { + t.Fatalf("unexpected special bits: %#o", m) + } +} + +func TestCommonPrefix(t *testing.T) { + testCases := map[string]struct { + paths []string + want string + }{ + "same lvl": { + paths: []string{ + "/home/user/file1", + "/home/user/file2", + }, + want: "/home/user", + }, + "sub folder": { + paths: []string{ + "/home/user/folder", + "/home/user/folder/file", + }, + want: "/home/user/folder", + }, + "relative path": { + paths: []string{ + "/home/user/folder", + "/home/user/folder/../folder2", + }, + want: "/home/user", + }, + "no common path": { + paths: []string{ + "/home/user/folder", + "/etc/file", + }, + want: "", + }, + } + for name, tt := range testCases { + t.Run(name, func(t *testing.T) { + if got := CommonPrefix('/', tt.paths...); got != tt.want { + t.Errorf("CommonPrefix() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestCopyFilePreservesModTime(t *testing.T) { + fileTime := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + dirTime := time.Date(2026, 6, 7, 8, 9, 0, 0, time.UTC) + testCases := map[string]struct { + isDir bool + checkPath map[string]time.Time + }{ + "file": {checkPath: map[string]time.Time{"": fileTime}}, + "directory": {isDir: true, checkPath: map[string]time.Time{"": dirTime, "nested.txt": fileTime}}, + } + for name, tt := range testCases { + t.Run(name, func(t *testing.T) { + src := t.TempDir() + dst := filepath.Join(t.TempDir(), "dst") + srcPath := src + if tt.isDir { + nested := filepath.Join(src, "nested.txt") + if err := os.WriteFile(nested, []byte("hi"), 0644); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(nested, fileTime, fileTime); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(src, dirTime, dirTime); err != nil { + t.Fatal(err) + } + } else { + srcPath = filepath.Join(src, "file.txt") + if err := os.WriteFile(srcPath, []byte("hi"), 0644); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(srcPath, fileTime, fileTime); err != nil { + t.Fatal(err) + } + } + if err := CopyFile(srcPath, dst); err != nil { + t.Fatal(err) + } + for rel, want := range tt.checkPath { + p := dst + if rel != "" { + p = filepath.Join(dst, rel) + } + got, err := os.Stat(p) + if err != nil { + t.Fatal(err) + } + if !got.ModTime().Equal(want) { + t.Errorf("%s: got mtime = %v, want %v", p, got.ModTime(), want) + } + } + }) + } +} diff --git a/backend/adapters/fs/fileutils/partition_unix.go b/backend/internal/adapters/fs/fileutils/partition_unix.go similarity index 100% rename from backend/adapters/fs/fileutils/partition_unix.go rename to backend/internal/adapters/fs/fileutils/partition_unix.go diff --git a/backend/adapters/fs/fileutils/partition_windows.go b/backend/internal/adapters/fs/fileutils/partition_windows.go similarity index 100% rename from backend/adapters/fs/fileutils/partition_windows.go rename to backend/internal/adapters/fs/fileutils/partition_windows.go diff --git a/backend/internal/analytics/collector.go b/backend/internal/analytics/collector.go new file mode 100644 index 0000000000..e1736fbce9 --- /dev/null +++ b/backend/internal/analytics/collector.go @@ -0,0 +1,90 @@ +package analytics + +import ( + "fmt" + "sync" + + "github.com/gtsteffaniak/go-logger/logger" +) + +var ( + cacheMu sync.RWMutex + cachedEnvelope []byte +) + +// Ready reports whether a snapshot is cached and available to preview or publish. +func Ready() bool { + cacheMu.RLock() + defer cacheMu.RUnlock() + return len(cachedEnvelope) > 0 +} + +// RefreshSnapshot rebuilds the cached snapshot from current server state. +func RefreshSnapshot() { + cacheMu.Lock() + defer cacheMu.Unlock() + rebuildSnapshotLocked(false) +} + +func rebuildSnapshotLocked(publishable bool) bool { + envelope, err := buildSnapshot(publishable) + if err != nil { + logger.Debugf("analytics snapshot build skipped: %v", err) + return false + } + + cachedEnvelope = envelope + return true +} + +func cachedSnapshotCopy() ([]byte, error) { + cacheMu.RLock() + defer cacheMu.RUnlock() + if len(cachedEnvelope) == 0 { + return nil, fmt.Errorf("analytics snapshot not cached yet; preview builds on demand") + } + out := make([]byte, len(cachedEnvelope)) + copy(out, cachedEnvelope) + return out, nil +} + +func invalidateSnapshotCache() { + cacheMu.Lock() + defer cacheMu.Unlock() + cachedEnvelope = nil +} + +// InvalidateCache clears the in-memory snapshot (e.g. when analytics is disabled). +func InvalidateCache() { + invalidateSnapshotCache() +} + +// PreviewSnapshot returns the cached JSON envelope, building it on demand when needed. +func PreviewSnapshot() ([]byte, error) { + if body, err := cachedSnapshotCopy(); err == nil { + return body, nil + } + RefreshSnapshot() + return cachedSnapshotCopy() +} + +// PublishSnapshot returns a snapshot suitable for publishing to the analytics API. +func PublishSnapshot() ([]byte, error) { + if _, err := snapshotVersion(true); err == nil { + if body, err := cachedSnapshotCopy(); err == nil { + return body, nil + } + } + + cacheMu.Lock() + defer cacheMu.Unlock() + + envelope, err := buildSnapshot(true) + if err != nil { + return nil, err + } + cachedEnvelope = envelope + out := make([]byte, len(envelope)) + copy(out, envelope) + return out, nil +} diff --git a/backend/internal/analytics/collector_test.go b/backend/internal/analytics/collector_test.go new file mode 100644 index 0000000000..df9bc6a283 --- /dev/null +++ b/backend/internal/analytics/collector_test.go @@ -0,0 +1,128 @@ +package analytics + +import ( + "path/filepath" + "sync" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func resetCacheForTest(t *testing.T) { + t.Helper() + InvalidateCache() + if Ready() { + t.Fatal("cache should be empty after InvalidateCache") + } +} + +func setCachedEnvelopeForTest(data []byte) { + cacheMu.Lock() + cachedEnvelope = append([]byte(nil), data...) + cacheMu.Unlock() +} + +func setupAnalyticsTest(t *testing.T) { + t.Helper() + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize("../../../_docker/src/noauth/backend/config.yaml") + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + if _, err := state.Initialize(dbPath); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = state.Close() }) + resetCacheForTest(t) +} + +func TestReadyReflectsCacheState(t *testing.T) { + resetCacheForTest(t) + if Ready() { + t.Fatal("expected Ready() false for empty cache") + } + + setCachedEnvelopeForTest([]byte(`{"cached":true}`)) + if !Ready() { + t.Fatal("expected Ready() true after cache populated") + } +} + +func TestInvalidateCacheClearsSnapshot(t *testing.T) { + setCachedEnvelopeForTest([]byte(`{"cached":true}`)) + InvalidateCache() + if Ready() { + t.Fatal("expected Ready() false after InvalidateCache") + } + if _, err := cachedSnapshotCopy(); err == nil { + t.Fatal("expected cachedSnapshotCopy error after invalidation") + } +} + +func TestPreviewSnapshotUsesCachedCopy(t *testing.T) { + resetCacheForTest(t) + want := []byte(`{"preview":"cached"}`) + setCachedEnvelopeForTest(want) + + got, err := PreviewSnapshot() + if err != nil { + t.Fatalf("PreviewSnapshot: %v", err) + } + if string(got) != string(want) { + t.Fatalf("PreviewSnapshot = %q, want %q", got, want) + } + + // Mutating the returned slice must not affect the cache. + got[0] = 'X' + fresh, err := PreviewSnapshot() + if err != nil { + t.Fatalf("PreviewSnapshot second call: %v", err) + } + if string(fresh) != string(want) { + t.Fatal("PreviewSnapshot should return independent copy of cached envelope") + } +} + +func TestRefreshSnapshotBuildsCache(t *testing.T) { + setupAnalyticsTest(t) + RefreshSnapshot() + if !Ready() { + t.Fatal("expected Ready() true after RefreshSnapshot") + } + + body, err := PreviewSnapshot() + if err != nil { + t.Fatalf("PreviewSnapshot after refresh: %v", err) + } + if len(body) == 0 { + t.Fatal("expected non-empty preview body") + } +} + +func TestCacheConcurrency(t *testing.T) { + setupAnalyticsTest(t) + setCachedEnvelopeForTest([]byte(`{"concurrent":true}`)) + + const workers = 32 + var wg sync.WaitGroup + wg.Add(workers * 3) + + for i := 0; i < workers; i++ { + go func() { + defer wg.Done() + _ = Ready() + }() + go func() { + defer wg.Done() + InvalidateCache() + }() + go func() { + defer wg.Done() + setCachedEnvelopeForTest([]byte(`{"concurrent":true}`)) + _, _ = cachedSnapshotCopy() + }() + } + + wg.Wait() +} diff --git a/backend/internal/analytics/memory_darwin.go b/backend/internal/analytics/memory_darwin.go new file mode 100644 index 0000000000..b8cdd070aa --- /dev/null +++ b/backend/internal/analytics/memory_darwin.go @@ -0,0 +1,13 @@ +//go:build darwin + +package analytics + +import "golang.org/x/sys/unix" + +func systemTotalMemoryMB() int { + mem, err := unix.SysctlUint64("hw.memsize") + if err != nil { + return 0 + } + return int(mem / (1024 * 1024)) +} diff --git a/backend/internal/analytics/memory_linux.go b/backend/internal/analytics/memory_linux.go new file mode 100644 index 0000000000..39707d055b --- /dev/null +++ b/backend/internal/analytics/memory_linux.go @@ -0,0 +1,36 @@ +//go:build linux + +package analytics + +import ( + "bufio" + "os" + "strconv" + "strings" +) + +func systemTotalMemoryMB() int { + file, err := os.Open("/proc/meminfo") + if err != nil { + return 0 + } + defer file.Close() + + scanner := bufio.NewScanner(file) + for scanner.Scan() { + line := scanner.Text() + if !strings.HasPrefix(line, "MemTotal:") { + continue + } + fields := strings.Fields(line) + if len(fields) < 2 { + return 0 + } + kb, err := strconv.Atoi(fields[1]) + if err != nil { + return 0 + } + return kb / 1024 + } + return 0 +} diff --git a/backend/internal/analytics/memory_other.go b/backend/internal/analytics/memory_other.go new file mode 100644 index 0000000000..50e025d15d --- /dev/null +++ b/backend/internal/analytics/memory_other.go @@ -0,0 +1,7 @@ +//go:build !linux && !darwin && !windows + +package analytics + +func systemTotalMemoryMB() int { + return 0 +} diff --git a/backend/internal/analytics/memory_windows.go b/backend/internal/analytics/memory_windows.go new file mode 100644 index 0000000000..9bf182eaa4 --- /dev/null +++ b/backend/internal/analytics/memory_windows.go @@ -0,0 +1,32 @@ +//go:build windows + +package analytics + +import ( + "syscall" + "unsafe" +) + +type memoryStatusEx struct { + length uint32 + memoryLoad uint32 + totalPhys uint64 + availPhys uint64 + totalPageFile uint64 + availPageFile uint64 + totalVirtual uint64 + availVirtual uint64 + availExtendedVirtual uint64 +} + +var procGlobalMemoryStatusEx = syscall.NewLazyDLL("kernel32.dll").NewProc("GlobalMemoryStatusEx") + +func systemTotalMemoryMB() int { + var status memoryStatusEx + status.length = uint32(unsafe.Sizeof(status)) + ret, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&status))) + if ret == 0 { + return 0 + } + return int(status.totalPhys / (1024 * 1024)) +} diff --git a/backend/internal/analytics/publish.go b/backend/internal/analytics/publish.go new file mode 100644 index 0000000000..f315cfddef --- /dev/null +++ b/backend/internal/analytics/publish.go @@ -0,0 +1,166 @@ +//go:build analytics + +package analytics + +import ( + "bytes" + "context" + "io" + "net/http" + "sync" + "time" + + "github.com/gtsteffaniak/go-logger/logger" +) + +const ( + time24h = 24 * time.Hour + time30d = 30 * time24h + initialSendDelay = time24h + recurringSendPeriod = time30d + analyticsURL = "https://api.filebrowserquantum.com/v1/events" +) + +var ( + reporterMu sync.Mutex + reporterCancel context.CancelFunc +) + +// PublishSupported reports whether this build can enable and send analytics. +func PublishSupported() bool { + return true +} + +// StartReporter schedules the first send 24 hours after startup when analytics is enabled, +// then sends monthly while the server keeps running. +func StartReporter() { + if !PublishSupported() { + return + } + scheduleReporter(time.Now()) +} + +// NotifyAnalyticsEnabled resets the reporter to send 24 hours from now, then monthly. +func NotifyAnalyticsEnabled() { + if !PublishSupported() { + return + } + scheduleReporter(time.Now()) +} + +// NotifyAnalyticsDisabled stops any pending or recurring analytics sends. +func NotifyAnalyticsDisabled() { + reporterMu.Lock() + defer reporterMu.Unlock() + if reporterCancel != nil { + reporterCancel() + reporterCancel = nil + } +} + +func scheduleReporter(anchor time.Time) { + reporterMu.Lock() + defer reporterMu.Unlock() + + if reporterCancel != nil { + reporterCancel() + reporterCancel = nil + } + + if !Enabled() { + return + } + + ctx, cancel := context.WithCancel(context.Background()) + reporterCancel = cancel + + go runReporter(ctx, anchor) +} + +func runReporter(ctx context.Context, anchor time.Time) { + if !waitUntil(ctx, anchor.Add(initialSendDelay)) { + return + } + sendSnapshot() + + for { + if !waitFor(ctx, recurringSendPeriod) { + return + } + sendSnapshot() + } +} + +func waitUntil(ctx context.Context, deadline time.Time) bool { + delay := time.Until(deadline) + if delay <= 0 { + select { + case <-ctx.Done(): + return false + default: + return true + } + } + + timer := time.NewTimer(delay) + defer timer.Stop() + + select { + case <-ctx.Done(): + return false + case <-timer.C: + return true + } +} + +func waitFor(ctx context.Context, duration time.Duration) bool { + timer := time.NewTimer(duration) + defer timer.Stop() + + select { + case <-ctx.Done(): + return false + case <-timer.C: + return true + } +} + +func sendSnapshot() { + if !Enabled() || !PublishSupported() { + return + } + body, err := PublishSnapshot() + if err != nil { + logger.Debugf("analytics snapshot send skipped: %v", err) + return + } + + req, err := http.NewRequest(http.MethodPost, analyticsURL, bytes.NewReader(body)) + if err != nil { + logger.Debugf("analytics request failed: %v", err) + return + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", userAgent) + req.Header.Set("X-App", xApp) + + client := &http.Client{Timeout: 60 * time.Second} + resp, err := client.Do(req) + if err != nil { + logger.Debugf("analytics send failed: %v", err) + return + } + defer resp.Body.Close() + + respBody, readErr := io.ReadAll(io.LimitReader(resp.Body, 4096)) + if readErr != nil { + logger.Debugf("analytics send returned status %d (failed to read body: %v)", resp.StatusCode, readErr) + return + } + + if resp.StatusCode != http.StatusCreated { + logger.Debugf("analytics send returned status %d: %s", resp.StatusCode, bytes.TrimSpace(respBody)) + return + } + logger.Debug("analytics deployment snapshot sent") +} diff --git a/backend/internal/analytics/publish_stub.go b/backend/internal/analytics/publish_stub.go new file mode 100644 index 0000000000..4a7678dddc --- /dev/null +++ b/backend/internal/analytics/publish_stub.go @@ -0,0 +1,14 @@ +//go:build !analytics + +package analytics + +// PublishSupported reports whether this build can enable and send analytics. +func PublishSupported() bool { + return false +} + +func StartReporter() {} + +func NotifyAnalyticsEnabled() {} + +func NotifyAnalyticsDisabled() {} diff --git a/backend/internal/analytics/publish_test.go b/backend/internal/analytics/publish_test.go new file mode 100644 index 0000000000..e7255f4a5d --- /dev/null +++ b/backend/internal/analytics/publish_test.go @@ -0,0 +1,125 @@ +//go:build analytics + +package analytics + +import ( + "context" + "path/filepath" + "testing" + "time" + + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func TestWaitUntilPastDeadline(t *testing.T) { + ctx := context.Background() + if !waitUntil(ctx, time.Now().Add(-time.Second)) { + t.Fatal("expected waitUntil to succeed for past deadline") + } +} + +func TestWaitUntilCancelled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + if waitUntil(ctx, time.Now().Add(time.Hour)) { + t.Fatal("expected waitUntil to fail when context is cancelled") + } +} + +func TestWaitUntilFutureDeadline(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + done := make(chan bool, 1) + go func() { + done <- waitUntil(ctx, time.Now().Add(20*time.Millisecond)) + }() + + select { + case ok := <-done: + if !ok { + t.Fatal("expected waitUntil to succeed before timeout") + } + case <-time.After(time.Second): + t.Fatal("waitUntil did not return in time") + } +} + +func TestWaitForDuration(t *testing.T) { + ctx := context.Background() + start := time.Now() + if !waitFor(ctx, 15*time.Millisecond) { + t.Fatal("expected waitFor to succeed") + } + if time.Since(start) < 10*time.Millisecond { + t.Fatal("waitFor returned too early") + } +} + +func TestWaitForCancelled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + if waitFor(ctx, time.Hour) { + t.Fatal("expected waitFor to fail when context is cancelled") + } +} + +func setupPublishTest(t *testing.T) { + t.Helper() + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize("../../../_docker/src/noauth/backend/config.yaml") + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + if _, err := state.Initialize(dbPath); err != nil { + t.Fatal(err) + } + if err := state.SetAnalyticsEnabled(true); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + NotifyAnalyticsDisabled() + _ = state.Close() + }) +} + +func TestNotifyAnalyticsDisabledCancelsReporter(t *testing.T) { + setupPublishTest(t) + + NotifyAnalyticsEnabled() + + reporterMu.Lock() + cancel := reporterCancel + reporterMu.Unlock() + if cancel == nil { + t.Fatal("expected reporter cancel function after NotifyAnalyticsEnabled") + } + + NotifyAnalyticsDisabled() + + reporterMu.Lock() + cancelAfter := reporterCancel + reporterMu.Unlock() + if cancelAfter != nil { + t.Fatal("expected reporter cancel cleared after NotifyAnalyticsDisabled") + } +} + +func TestScheduleReporterSkipsWhenDisabled(t *testing.T) { + setupPublishTest(t) + if err := state.SetAnalyticsEnabled(false); err != nil { + t.Fatal(err) + } + + scheduleReporter(time.Now()) + + reporterMu.Lock() + cancel := reporterCancel + reporterMu.Unlock() + if cancel != nil { + t.Fatal("expected no reporter when analytics is disabled") + } +} diff --git a/backend/internal/analytics/snapshot.go b/backend/internal/analytics/snapshot.go new file mode 100644 index 0000000000..28f14700a1 --- /dev/null +++ b/backend/internal/analytics/snapshot.go @@ -0,0 +1,330 @@ +package analytics + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + "time" + + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/internal/version" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +const ( + schemaVersion = "1" + eventTypeDeploymentSnapshot = "deployment_snapshot" + userAgent = "filebrowser-analytics" + xApp = "filebrowser" +) + +type envelope struct { + SchemaVersion string `json:"schema_version"` + EventType string `json:"event_type"` + InstallationID string `json:"installation_id"` + ID string `json:"id"` + Payload json.RawMessage `json:"payload"` +} + +type snapshotPayload struct { + App appPayload `json:"app"` + System systemPayload `json:"system"` + Counts countsPayload `json:"counts"` + Auth authPayload `json:"auth"` + Integrations integrationsPayload `json:"integrations"` + Features featuresPayload `json:"features"` + Indexing indexingPayload `json:"indexing"` + Storage storagePayload `json:"storage"` +} + +type appPayload struct { + Version string `json:"version"` + CommitSHA string `json:"commit_sha"` +} + +type systemPayload struct { + OS string `json:"os"` + Arch string `json:"arch"` + CPUCores int `json:"cpu_cores"` + MemoryRSSMB int `json:"memory_rss_mb"` + MemoryTotalMB int `json:"memory_total_mb"` + Runtime string `json:"runtime"` +} + +type countsPayload struct { + SourcesEnabled int `json:"sources_enabled"` + SourcesReadOnly int `json:"sources_read_only"` + SourcesPrivate int `json:"sources_private"` + UsersTotal int `json:"users_total"` + AccessRulesTotal int `json:"access_rules_total"` + SharesActive int `json:"shares_active"` + CustomThemes int `json:"custom_themes"` +} + +type authPayload struct { + NoAuth bool `json:"noauth"` + PasswordEnabled bool `json:"password_enabled"` + PasswordSignup bool `json:"password_signup"` + PasswordEnforcedOTP bool `json:"password_enforced_otp"` + OidcEnabled bool `json:"oidc_enabled"` + LdapEnabled bool `json:"ldap_enabled"` + JwtEnabled bool `json:"jwt_enabled"` + ProxyEnabled bool `json:"proxy_enabled"` + PasskeyEnabled bool `json:"passkey_enabled"` +} + +type integrationsPayload struct { + OnlyOfficeConfigured bool `json:"onlyoffice_configured"` + OnlyOfficeViewOnly bool `json:"onlyoffice_view_only"` + MediaEnabled bool `json:"media_enabled"` + HardwareAcceleration bool `json:"hardware_acceleration"` +} + +type featuresPayload struct { + DisablePreviews bool `json:"disable_previews"` + DisableWebDAV bool `json:"disable_webdav"` + DisableUpdateCheck bool `json:"disable_update_check"` + ActivityLoggingEnabled bool `json:"activity_logging_enabled"` + TLSEnabled bool `json:"tls_enabled"` + RateLimitDisabled bool `json:"rate_limit_disabled"` + IndexWALMode bool `json:"index_wal_mode"` + CacheDirCleanup bool `json:"cache_dir_cleanup"` +} + +type indexingPayload struct { + AvgQuickScanSeconds int `json:"avg_quick_scan_seconds"` + AvgFullScanSeconds int `json:"avg_full_scan_seconds"` + TotalFiles int `json:"total_files"` + TotalDirs int `json:"total_dirs"` + SourcesIndexed int `json:"sources_indexed"` +} + +type storagePayload struct { + MainDBBytes int64 `json:"main_db_bytes"` + IndexDBBytes int64 `json:"index_db_bytes"` +} + +func Enabled() bool { + return state.IsAnalyticsEnabled() +} + +func buildSnapshot(publishable bool) ([]byte, error) { + versionLabel, err := snapshotVersion(publishable) + if err != nil { + return nil, err + } + + installationID, err := state.GetOrCreateInstallationID() + if err != nil { + return nil, err + } + + now := time.Now().UTC() + eventID := fmt.Sprintf("%s#%s#%s", installationID, eventTypeDeploymentSnapshot, now.Format("2006-01-02")) + + payload, err := collectPayload(versionLabel) + if err != nil { + return nil, err + } + payloadJSON, err := json.Marshal(payload) + if err != nil { + return nil, err + } + + event := envelope{ + SchemaVersion: schemaVersion, + EventType: eventTypeDeploymentSnapshot, + InstallationID: installationID, + ID: eventID, + Payload: payloadJSON, + } + return json.Marshal(event) +} + +func collectPayload(versionLabel string) (snapshotPayload, error) { + users, err := state.GetAllUsers() + if err != nil { + return snapshotPayload{}, err + } + shares, err := state.GetAllShares() + if err != nil { + return snapshotPayload{}, err + } + accessRules, err := state.CountAccessRules() + if err != nil { + return snapshotPayload{}, err + } + + sourceCounts := countSources() + indexStats := collectIndexStats() + + commitSHA := strings.ToLower(strings.TrimSpace(version.CommitSHA)) + if commitSHA == "untracked" { + commitSHA = "" + } + + return snapshotPayload{ + App: appPayload{ + Version: versionLabel, + CommitSHA: commitSHA, + }, + System: systemPayload{ + OS: mapSystemOS(runtime.GOOS), + Arch: mapSystemArch(runtime.GOARCH), + CPUCores: runtime.NumCPU(), + MemoryRSSMB: memoryRSSMB(), + MemoryTotalMB: systemTotalMemoryMB(), + Runtime: detectRuntime(), + }, + Counts: countsPayload{ + SourcesEnabled: sourceCounts.enabled, + SourcesReadOnly: sourceCounts.readOnly, + SourcesPrivate: sourceCounts.private, + UsersTotal: len(users), + AccessRulesTotal: accessRules, + SharesActive: len(shares), + CustomThemes: len(settings.Config.Frontend.Styling.CustomThemes), + }, + Auth: authPayload{ + NoAuth: settings.Config.Auth.Methods.NoAuth, + PasswordEnabled: settings.Config.Auth.Methods.PasswordAuth.Enabled, + PasswordSignup: settings.Config.Auth.Methods.PasswordAuth.Signup, + PasswordEnforcedOTP: settings.Config.Auth.Methods.PasswordAuth.EnforcedOtp, + OidcEnabled: settings.Config.Auth.Methods.OidcAuth.Enabled, + LdapEnabled: settings.Config.Auth.Methods.LdapAuth.Enabled, + JwtEnabled: settings.Config.Auth.Methods.JwtAuth.Enabled, + ProxyEnabled: settings.Config.Auth.Methods.ProxyAuth.Enabled, + PasskeyEnabled: settings.Config.Auth.Methods.PasskeyAuth.Enabled, + }, + Integrations: integrationsPayload{ + OnlyOfficeConfigured: strings.TrimSpace(settings.Config.Integrations.OnlyOffice.Url) != "", + OnlyOfficeViewOnly: settings.Config.Integrations.OnlyOffice.ViewOnly, + MediaEnabled: settings.MediaEnabled(), + HardwareAcceleration: settings.Config.Integrations.Media.HardwareAcceleration, + }, + Features: featuresPayload{ + DisablePreviews: settings.Config.Server.DisablePreviews, + DisableWebDAV: settings.Config.Http.DisableWebDAV, + DisableUpdateCheck: settings.Config.Server.DisableUpdateCheck, + ActivityLoggingEnabled: !settings.Config.Server.DatabaseV2.Activity.Disabled, + TLSEnabled: strings.TrimSpace(settings.Config.Http.TLSCert) != "" && strings.TrimSpace(settings.Config.Http.TLSKey) != "", + RateLimitDisabled: settings.Config.Http.DisableRateLimit, + IndexWALMode: settings.Config.Server.IndexSqlConfig.WalMode, + CacheDirCleanup: settings.Config.Server.CacheDirCleanup, + }, + Indexing: indexStats, + Storage: storagePayload{ + MainDBBytes: fileSize(settings.Config.Server.DatabaseV2.Path), + IndexDBBytes: fileSize(filepath.Join(settings.Config.Server.CacheDir, "sql", "index_all.db")), + }, + }, nil +} + +func snapshotVersion(publishable bool) (string, error) { + versionLabel := strings.TrimSpace(version.Version) + if versionLabel == "" { + return "", fmt.Errorf("version not available") + } + if publishable && (versionLabel == "untracked" || versionLabel == "testing") { + return "", fmt.Errorf("version not reportable") + } + return versionLabel, nil +} + +type sourceCountSummary struct { + enabled int + readOnly int + private int +} + +func countSources() sourceCountSummary { + summary := sourceCountSummary{} + for _, src := range settings.Config.Server.Sources { + if src == nil { + continue + } + if !src.Config.Disabled { + summary.enabled++ + } + if src.Config.ReadOnly { + summary.readOnly++ + } + if src.Config.Private { + summary.private++ + } + } + return summary +} + +func collectIndexStats() indexingPayload { + stats := indexingPayload{} + var quickTotal int + var fullTotal int + + for _, src := range settings.Config.Server.Sources { + if src == nil || src.Config.Disabled { + continue + } + info, err := indexing.GetIndexInfo(src.Name, false) + if err != nil { + continue + } + stats.SourcesIndexed++ + stats.TotalFiles += int(info.NumFiles) + stats.TotalDirs += int(info.NumDirs) + quickTotal += info.QuickScanTime + fullTotal += info.FullScanTime + } + + if stats.SourcesIndexed > 0 { + stats.AvgQuickScanSeconds = quickTotal / stats.SourcesIndexed + stats.AvgFullScanSeconds = fullTotal / stats.SourcesIndexed + } + return stats +} + +func detectRuntime() string { + if os.Getenv("KUBERNETES_SERVICE_HOST") != "" { + return "kubernetes" + } + if _, err := os.Stat("/.dockerenv"); err == nil { + return "docker" + } + return "native" +} + +func mapSystemOS(goos string) string { + switch goos { + case "linux", "windows", "darwin": + return goos + default: + return "other" + } +} + +func mapSystemArch(goarch string) string { + switch goarch { + case "amd64", "arm64", "386", "arm": + return goarch + default: + return "other" + } +} + +func memoryRSSMB() int { + var mem runtime.MemStats + runtime.ReadMemStats(&mem) + return int(mem.Sys / (1024 * 1024)) +} + +func fileSize(path string) int64 { + info, err := os.Stat(path) + if err != nil { + return 0 + } + return info.Size() +} diff --git a/backend/internal/app/wire.go b/backend/internal/app/wire.go new file mode 100644 index 0000000000..89117e8946 --- /dev/null +++ b/backend/internal/app/wire.go @@ -0,0 +1,43 @@ +package app + +import ( + "github.com/gtsteffaniak/filebrowser/backend/internal/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/internal/auth" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" +) + +// App holds wired dependencies for the running process. +type App struct { + Store *state.Store + Files *files.Service + Auth *auth.Service +} + +// WireServices connects domain packages to the state store after Open. +func WireServices(store *state.Store) (*App, error) { + filesSvc := files.New(store, store, store) + authSvc := auth.New(store) + files.SetDefault(filesSvc) + auth.SetDefault(authSvc) + indexing.SetMetaStore(store) + activity.SetQueryDeps(store, store) + if err := auth.InitWebAuthn(store); err != nil { + return nil, err + } + return &App{ + Store: store, + Files: filesSvc, + Auth: authSvc, + }, nil +} + +// MustWireServices is for tests; panics on wiring failure. +func MustWireServices(store *state.Store) *App { + a, err := WireServices(store) + if err != nil { + panic(err) + } + return a +} diff --git a/backend/auth/auth.go b/backend/internal/auth/auth.go similarity index 88% rename from backend/auth/auth.go rename to backend/internal/auth/auth.go index f03f35ae9f..9b1498c2ba 100644 --- a/backend/auth/auth.go +++ b/backend/internal/auth/auth.go @@ -6,9 +6,9 @@ import ( "time" "github.com/golang-jwt/jwt/v4" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/database/access" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/access" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" ) // Auther is the authentication interface. @@ -52,7 +52,7 @@ func MakeSignedTokenAPI(user *users.User, name string, duration time.Duration, p }, } if !minimal { - claim.Permissions = perms + claim.Permissions = users.SanitizeTokenPermissions(perms) claim.BelongsTo = user.ID } signedClaims := jwt.Claims(claim) diff --git a/backend/internal/auth/json.go b/backend/internal/auth/json.go new file mode 100644 index 0000000000..3910acc8d9 --- /dev/null +++ b/backend/internal/auth/json.go @@ -0,0 +1,18 @@ +package auth + +import ( + "net/http" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// JSONAuth is a json implementation of an Auther. +type JSONAuth struct { + ReCaptcha bool `json:"recaptcha" yaml:"recaptcha"` + DisableOtp bool `json:"disableOtp" yaml:"disableOtp"` +} + +// 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) +} diff --git a/backend/auth/json_timing_test.go b/backend/internal/auth/json_timing_test.go similarity index 82% rename from backend/auth/json_timing_test.go rename to backend/internal/auth/json_timing_test.go index 7fe1c531f1..3af01412d3 100644 --- a/backend/auth/json_timing_test.go +++ b/backend/internal/auth/json_timing_test.go @@ -29,39 +29,45 @@ import ( "testing" "time" - "github.com/gtsteffaniak/filebrowser/backend/auth" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/auth" + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" ) // mockUserBackend is a simple in-memory user storage for testing. type mockUserBackend struct { usersByUsername map[string]*users.User - usersByID map[uint]*users.User + usersByID map[uint64]*users.User } func newMockUserBackend() *mockUserBackend { return &mockUserBackend{ usersByUsername: make(map[string]*users.User), - usersByID: make(map[uint]*users.User), + usersByID: make(map[uint64]*users.User), } } -func (m *mockUserBackend) GetBy(id interface{}) (*users.User, error) { - switch v := id.(type) { - case string: - if user, ok := m.usersByUsername[v]; ok { - return user, nil - } - return nil, fmt.Errorf("user not found: %s", v) - case uint: - if user, ok := m.usersByID[v]; ok { - return user, nil - } - return nil, fmt.Errorf("user not found: %d", v) - default: - return nil, fmt.Errorf("invalid id type") +func (m *mockUserBackend) GetBy(id uint64) (*users.User, error) { + if user, ok := m.usersByID[id]; ok { + return user, nil } + return nil, fmt.Errorf("user not found: %d", id) +} + +func (m *mockUserBackend) GetUserByID(id uint64) (users.User, error) { + u, err := m.GetBy(id) + if err != nil { + return users.User{}, err + } + return *u, nil +} + +func (m *mockUserBackend) GetUserByUsername(username string) (users.User, error) { + if user, ok := m.usersByUsername[username]; ok { + return *user, nil + } + return users.User{}, errors.ErrNotExist } func (m *mockUserBackend) Gets() ([]*users.User, error) { @@ -84,7 +90,7 @@ func (m *mockUserBackend) Update(u *users.User, adminActor bool, fields ...strin return nil } -func (m *mockUserBackend) DeleteByID(id uint) error { +func (m *mockUserBackend) DeleteByID(id uint64) error { if user, ok := m.usersByID[id]; ok { delete(m.usersByUsername, user.Username) delete(m.usersByID, id) @@ -93,17 +99,8 @@ func (m *mockUserBackend) DeleteByID(id uint) error { return fmt.Errorf("user not found: %d", id) } -func (m *mockUserBackend) DeleteByUsername(username string) error { - if user, ok := m.usersByUsername[username]; ok { - delete(m.usersByID, user.ID) - delete(m.usersByUsername, username) - return nil - } - return fmt.Errorf("user not found: %s", username) -} - -// setupTestUsers creates a user storage with 2 valid test users -func setupTestUsers(t *testing.T) *users.Storage { +// setupTestUsers creates mock user persistence for timing tests. +func setupTestUsers(t *testing.T) *mockUserBackend { t.Helper() // Reduce bcrypt cost for faster tests (default is 10, min is 4) @@ -122,7 +119,20 @@ func setupTestUsers(t *testing.T) *users.Storage { } backend := newMockUserBackend() - storage := users.NewStorage(backend) + authSvc := auth.New(backend) + auth.SetDefault(authSvc) + t.Cleanup(func() { + auth.SetDefault(nil) + }) + users.SetUsernameToID(func(username string) (uint64, error) { + if u, ok := backend.usersByUsername[username]; ok { + return u.ID, nil + } + return 0, errors.ErrNotExist + }) + t.Cleanup(func() { + users.SetUsernameToID(nil) + }) // Create two valid users with hashed passwords password1Hash, err := utils.HashPwd("password123") @@ -136,38 +146,42 @@ func setupTestUsers(t *testing.T) *users.Storage { } user1 := &users.User{ - ID: 1, - Username: "admin", - NonAdminEditable: users.NonAdminEditable{ - Password: password1Hash, + ID: 1, + FrontendUser: users.FrontendUser{ + Username: "admin", + NonAdminEditable: users.NonAdminEditable{ + Password: password1Hash, + }, + LoginMethod: users.LoginMethodPassword, }, - LoginMethod: users.LoginMethodPassword, } user2 := &users.User{ - ID: 2, - Username: "testuser", - NonAdminEditable: users.NonAdminEditable{ - Password: password2Hash, + ID: 2, + FrontendUser: users.FrontendUser{ + Username: "testuser", + NonAdminEditable: users.NonAdminEditable{ + Password: password2Hash, + }, + LoginMethod: users.LoginMethodPassword, }, - LoginMethod: users.LoginMethodPassword, } - err = storage.Save(user1, false, false) + err = backend.Save(user1, false, false) if err != nil { t.Fatalf("Failed to save user1: %v", err) } - err = storage.Save(user2, false, false) + err = backend.Save(user2, false, false) if err != nil { t.Fatalf("Failed to save user2: %v", err) } - return storage + return backend } // measureAuthTime measures the time taken to authenticate with given credentials -func measureAuthTime(t *testing.T, auther auth.JSONAuth, userStore *users.Storage, username, password string) time.Duration { +func measureAuthTime(t *testing.T, auther auth.JSONAuth, username, password string) time.Duration { t.Helper() // Create a mock HTTP request @@ -178,7 +192,7 @@ func measureAuthTime(t *testing.T, auther auth.JSONAuth, userStore *users.Storag req.Header.Set("X-Password", url.QueryEscape(password)) start := time.Now() - _, _ = auther.Auth(req, userStore) + _, _ = auther.Auth(req, nil) elapsed := time.Since(start) return elapsed @@ -186,10 +200,8 @@ func measureAuthTime(t *testing.T, auther auth.JSONAuth, userStore *users.Storag // TestJSONAuth_NoTimingAttack tests that authentication timing does not leak user existence func TestJSONAuth_NoTimingAttack(t *testing.T) { - storage := setupTestUsers(t) + setupTestUsers(t) auther := auth.JSONAuth{} - - // Test cases: mix of valid and invalid usernames testCases := []struct { username string isValid bool @@ -215,7 +227,7 @@ func TestJSONAuth_NoTimingAttack(t *testing.T) { for i := 0; i < samplesPerCase; i++ { // Randomize order to avoid cache effects for _, tc := range testCases { - elapsed := measureAuthTime(t, auther, storage, tc.username, "wrongpassword123") + elapsed := measureAuthTime(t, auther, tc.username, "wrongpassword123") measurements[tc.username] = append(measurements[tc.username], elapsed) } } diff --git a/backend/auth/jwt.go b/backend/internal/auth/jwt.go similarity index 98% rename from backend/auth/jwt.go rename to backend/internal/auth/jwt.go index b482e1bfc0..4777bf8ffa 100644 --- a/backend/auth/jwt.go +++ b/backend/internal/auth/jwt.go @@ -11,7 +11,7 @@ import ( "net/http" "github.com/golang-jwt/jwt/v4" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" "github.com/gtsteffaniak/go-logger/logger" ) diff --git a/backend/auth/jwt_test.go b/backend/internal/auth/jwt_test.go similarity index 99% rename from backend/auth/jwt_test.go rename to backend/internal/auth/jwt_test.go index 2b9cdffbff..417f2da245 100644 --- a/backend/auth/jwt_test.go +++ b/backend/internal/auth/jwt_test.go @@ -13,7 +13,7 @@ import ( "time" "github.com/golang-jwt/jwt/v4" - "github.com/gtsteffaniak/filebrowser/backend/auth" + "github.com/gtsteffaniak/filebrowser/backend/internal/auth" ) func TestVerifyExternalJWT_ValidToken(t *testing.T) { diff --git a/backend/internal/auth/none.go b/backend/internal/auth/none.go new file mode 100644 index 0000000000..98a7e81dda --- /dev/null +++ b/backend/internal/auth/none.go @@ -0,0 +1,32 @@ +package auth + +import ( + "net/http" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// MethodNoAuth is used to identify no auth. +const MethodNoAuth = "noauth" + +// NoAuth is no auth implementation of auther. +type NoAuth struct{} + +// AuthenticateNoAuth authenticates as the configured admin user with no credentials required. +func AuthenticateNoAuth(r *http.Request, user *users.Storage) (*users.User, error) { + admin := settings.Config.Auth.AdminUsername + if admin == "" { + admin = "admin" + } + id, err := users.ResolveUsernameToID(admin) + if err != nil { + return nil, err + } + return user.Get(id) +} + +// Auth uses authenticates as the configured admin user (legacy no-credentials mode). +func (a NoAuth) Auth(r *http.Request, user *users.Storage) (*users.User, error) { + return AuthenticateNoAuth(r, user) +} diff --git a/backend/internal/auth/proxy.go b/backend/internal/auth/proxy.go new file mode 100644 index 0000000000..7ac70fd724 --- /dev/null +++ b/backend/internal/auth/proxy.go @@ -0,0 +1,40 @@ +package auth + +import ( + "net/http" + "os" + + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// MethodProxyAuth is used to identify no auth. +const MethodProxyAuth = "proxy" + +// ProxyAuth is a proxy implementation of an auther. +type ProxyAuth struct { + Header string `json:"header"` +} + +// AuthenticateProxy authenticates the user via an HTTP header. +func AuthenticateProxy(r *http.Request, usr *users.Storage, headerName string) (*users.User, error) { + username := r.Header.Get(headerName) + id, err := users.ResolveUsernameToID(username) + if err == errors.ErrNotExist { + return nil, os.ErrPermission + } + if err != nil { + return nil, err + } + user, err := usr.Get(id) + if err == errors.ErrNotExist { + return nil, os.ErrPermission + } + + return user, err +} + +// Auth authenticates the user via an HTTP header (legacy method for compatibility). +func (a ProxyAuth) Auth(r *http.Request, usr *users.Storage) (*users.User, error) { + return AuthenticateProxy(r, usr, a.Header) +} diff --git a/backend/internal/auth/service.go b/backend/internal/auth/service.go new file mode 100644 index 0000000000..91297c0b96 --- /dev/null +++ b/backend/internal/auth/service.go @@ -0,0 +1,86 @@ +package auth + +import ( + "fmt" + "net/http" + "net/url" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/ports" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" +) + +// Service performs authentication using injected user reads. It never persists users. +type Service struct { + users ports.UserReader +} + +var defaultService *Service + +// New constructs an auth service with the given user reader. +func New(users ports.UserReader) *Service { + return &Service{users: users} +} + +// SetDefault registers the process-wide auth service (called from app.WireServices). +func SetDefault(s *Service) { + defaultService = s +} + +// AuthenticatePassword authenticates the user via password in request headers. +func (s *Service) AuthenticatePassword(r *http.Request, disableOtp bool) (*users.User, error) { + if s == nil || s.users == nil { + return nil, fmt.Errorf("auth service not configured") + } + username := r.URL.Query().Get("username") + password := r.Header.Get("X-Password") + totpCode := r.Header.Get("X-Secret") + password, err := url.QueryUnescape(password) + if err != nil { + return nil, fmt.Errorf("invalid password encoding: %v", err) + } + + id, resErr := users.ResolveUsernameToID(username) + var user users.User + var getErr error + if resErr != nil { + getErr = resErr + } else { + user, getErr = s.users.GetUserByID(id) + } + var passwordHash string + if getErr != nil { + passwordHash = utils.InvalidPasswordHash + } else { + passwordHash = user.Password + } + err = utils.CheckPwd(password, passwordHash) + if err != nil { + return nil, err + } + if getErr != nil { + return nil, fmt.Errorf("unable to get user from store: %v", err) + } + if user.TOTPSecret != "" && !disableOtp { + if totpCode == "" { + return nil, errors.ErrNoTotpProvided + } + err = VerifyTotpCode(&user, totpCode) + if err != nil { + return nil, err + } + } + if user.LoginMethod != users.LoginMethodPassword { + return nil, errors.ErrWrongLoginMethod + } + return &user, nil +} + +// AuthenticatePassword authenticates via the default service. +func AuthenticatePassword(r *http.Request, disableOtp bool) (*users.User, error) { + if defaultService != nil { + return defaultService.AuthenticatePassword(r, disableOtp) + } + return nil, fmt.Errorf("auth service not configured") +} diff --git a/backend/auth/storage.go b/backend/internal/auth/storage.go similarity index 80% rename from backend/auth/storage.go rename to backend/internal/auth/storage.go index 39d3a1cc4f..ed70d272d0 100644 --- a/backend/auth/storage.go +++ b/backend/internal/auth/storage.go @@ -5,8 +5,8 @@ import ( "crypto/sha256" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" "github.com/gtsteffaniak/go-logger/logger" "golang.org/x/crypto/pbkdf2" ) @@ -23,21 +23,8 @@ type Storage struct { users *users.Storage } -// NewStorage creates a auth storage from a backend. -func NewStorage(back StorageBackend, userStore *users.Storage) (*Storage, error) { - store := &Storage{back: back, users: userStore} - err := store.Save(&JSONAuth{}) - if err != nil { - return nil, err - } - err = store.Save(&ProxyAuth{}) - if err != nil { - return nil, err - } - err = store.Save(&NoAuth{}) - if err != nil { - return nil, err - } +// InitializeEncryption initializes the encryption key for TOTP from config +func InitializeEncryption() error { if settings.Config.Auth.TotpSecret != "" { key, err := base64.StdEncoding.DecodeString(settings.Config.Auth.TotpSecret) keyLen := len(key) @@ -52,6 +39,31 @@ func NewStorage(back StorageBackend, userStore *users.Storage) (*Storage, error) encryptionKey = pbkdf2.Key([]byte(settings.Config.Auth.TotpSecret), salt, 4096, 32, sha256.New) } } + return nil +} + +// NewStorage creates a auth storage from a backend. +func NewStorage(back StorageBackend, userStore *users.Storage) (*Storage, error) { + store := &Storage{back: back, users: userStore} + err := store.Save(&JSONAuth{DisableOtp: true}) + if err != nil { + return nil, err + } + err = store.Save(&ProxyAuth{}) + if err != nil { + return nil, err + } + err = store.Save(&NoAuth{}) + if err != nil { + return nil, err + } + + // Initialize encryption key + err = InitializeEncryption() + if err != nil { + return nil, err + } + return store, nil } diff --git a/backend/internal/auth/token_length_test.go b/backend/internal/auth/token_length_test.go new file mode 100644 index 0000000000..31e9f286ee --- /dev/null +++ b/backend/internal/auth/token_length_test.go @@ -0,0 +1,68 @@ +package auth + +import ( + "testing" + "time" + + "github.com/golang-jwt/jwt/v4" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +const webdavPasswordLimit = 256 + +func TestMinimalSignedTokenLengthUnder256(t *testing.T) { + origKey := settings.Config.Auth.Key + settings.Config.Auth.Key = "test-signing-key-for-length-check" + t.Cleanup(func() { settings.Config.Auth.Key = origKey }) + + user := &users.User{ID: 42, FrontendUser: users.FrontendUser{Username: "webdavuser"}} + tokenString, _, err := MakeSignedTokenAPI(user, "webdav", time.Hour*24*365*10, users.Permissions{}, true) + if err != nil { + t.Fatalf("MakeSignedTokenAPI: %v", err) + } + if len(tokenString) >= webdavPasswordLimit { + t.Fatalf("minimal token length %d must stay under %d for WebDAV clients", len(tokenString), webdavPasswordLimit) + } + assertMinimalJWTClaims(t, tokenString) +} + +func TestCustomizedTokenEmbedsPermissionsAndIsLonger(t *testing.T) { + origKey := settings.Config.Auth.Key + settings.Config.Auth.Key = "test-signing-key-for-length-check" + t.Cleanup(func() { settings.Config.Auth.Key = origKey }) + + user := &users.User{ID: 42, FrontendUser: users.FrontendUser{Username: "webdavuser"}} + minimal, _, err := MakeSignedTokenAPI(user, "min", time.Hour*24*365, users.Permissions{}, true) + if err != nil { + t.Fatal(err) + } + custom, _, err := MakeSignedTokenAPI(user, "custom", time.Hour*24*365, users.Permissions{Api: true}, false) + if err != nil { + t.Fatal(err) + } + if len(custom) <= len(minimal) { + t.Fatalf("custom token should be longer than minimal: custom=%d minimal=%d", len(custom), len(minimal)) + } + + claims := jwt.MapClaims{} + if _, _, err := jwt.NewParser().ParseUnverified(custom, claims); err != nil { + t.Fatalf("parse custom token: %v", err) + } + if _, ok := claims["Permissions"]; !ok { + t.Fatal("custom token payload should include Permissions claim") + } +} + +func assertMinimalJWTClaims(t *testing.T, tokenString string) { + t.Helper() + claims := jwt.MapClaims{} + if _, _, err := jwt.NewParser().ParseUnverified(tokenString, claims); err != nil { + t.Fatalf("parse token: %v", err) + } + for _, key := range []string{"Permissions", "permissions", "belongsTo", "username", "name"} { + if _, ok := claims[key]; ok { + t.Fatalf("minimal token must not include %q claim; got %v", key, claims) + } + } +} diff --git a/backend/auth/totp.go b/backend/internal/auth/totp.go similarity index 88% rename from backend/auth/totp.go rename to backend/internal/auth/totp.go index 0d28e600ca..23a05b0497 100644 --- a/backend/auth/totp.go +++ b/backend/internal/auth/totp.go @@ -10,8 +10,8 @@ import ( "strings" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" "github.com/gtsteffaniak/go-cache/cache" "github.com/gtsteffaniak/go-logger/logger" "github.com/pquerna/otp" @@ -51,7 +51,7 @@ var ( TotpCache = cache.NewCache[string](5 * time.Minute) ) -func GenerateOtpForUser(user *users.User, userStore *users.Storage) (string, error) { +func GenerateOtpForUser(user *users.User) (string, error) { // Generate a new TOTP key using the defined constants. key, err := totp.Generate(totp.GenerateOpts{ Issuer: IssuerName, @@ -145,7 +145,7 @@ func decryptSecret(b64Ciphertext, b64Nonce string) (string, error) { return string(plaintext), nil } -func VerifyTotpCode(user *users.User, code string, userStore *users.Storage) error { +func VerifyTotpCode(user *users.User, code string) error { cachedSecret, found := TotpCache.Get(user.Username) if !found && user.TOTPSecret == "" { return fmt.Errorf("OTP token not found in cache, please generate a new one") @@ -188,14 +188,9 @@ func VerifyTotpCode(user *users.User, code string, userStore *users.Storage) err return fmt.Errorf("invalid OTP token") } if totpSecret != "" || !user.OtpEnabled { - user.TOTPSecret = totpSecret // The encrypted or plaintext secret - user.TOTPNonce = totpNonce // The nonce if encrypted, or empty if plaintext - user.OtpEnabled = true // Enable OTP for the user - // save user - if err := userStore.Update(user, true, "TOTPSecret", "TOTPNonce", "OtpEnabled"); err != nil { - logger.Error("error updating user with OTP token:", err) - return fmt.Errorf("error updating user with OTP token: %w", err) - } + user.TOTPSecret = totpSecret + user.TOTPNonce = totpNonce + user.OtpEnabled = true TotpCache.Delete(user.Username) } else { return fmt.Errorf("opt secret is empty, cannot enable TOTP") diff --git a/backend/auth/webauthn.go b/backend/internal/auth/webauthn.go similarity index 74% rename from backend/auth/webauthn.go rename to backend/internal/auth/webauthn.go index d916be15ae..b66f142e7a 100644 --- a/backend/auth/webauthn.go +++ b/backend/internal/auth/webauthn.go @@ -12,10 +12,11 @@ import ( "github.com/go-webauthn/webauthn/protocol" "github.com/go-webauthn/webauthn/webauthn" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/ports" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" ) type webAuthnSession struct { @@ -26,13 +27,15 @@ type webAuthnSession struct { type WebAuthnService struct { wa *webauthn.WebAuthn + users ports.UserReader sessions sync.Map stopCh chan struct{} + originMu sync.Mutex } var webAuthnInstance *WebAuthnService -func InitWebAuthn() error { +func InitWebAuthn(users ports.UserReader) error { cfg := &settings.Config.Auth.Methods.PasskeyAuth if !cfg.Enabled { webAuthnInstance = nil @@ -51,6 +54,7 @@ func InitWebAuthn() error { webAuthnInstance = &WebAuthnService{ wa: wa, + users: users, stopCh: make(chan struct{}), } go webAuthnInstance.cleanupExpiredSessions() @@ -65,15 +69,24 @@ func IsWebAuthnEnabled() bool { return webAuthnInstance != nil } -// ValidateOrigin checks if the given origin is in the configured whitelist. -// Returns true if the origin is allowed, false otherwise. -func (s *WebAuthnService) ValidateOrigin(origin string) bool { - for _, allowedOrigin := range s.wa.Config.RPOrigins { - if allowedOrigin == origin { - return true +// EnsureOrigin dynamically adds the given origin to the allowed RP origins list. +// This supports self-hosted deployments where the access domain may vary. +func (s *WebAuthnService) EnsureOrigin(origin string) { + s.originMu.Lock() + defer s.originMu.Unlock() + for _, o := range s.wa.Config.RPOrigins { + if o == origin { + return } } - return false + s.wa.Config.RPOrigins = append(s.wa.Config.RPOrigins, origin) +} + +// EnsureRPID dynamically updates the relying party ID to match the request host. +func (s *WebAuthnService) EnsureRPID(rpID string) { + s.originMu.Lock() + defer s.originMu.Unlock() + s.wa.Config.RPID = rpID } func generateSessionID() string { @@ -84,8 +97,23 @@ func generateSessionID() string { return hex.EncodeToString(b) } -func (s *WebAuthnService) BeginMFALogin(username, password string, rpID string, userStore *users.Storage) (sessionID string, assertion *protocol.CredentialAssertion, err error) { - user, getErr := userStore.Get(username) +func (s *WebAuthnService) userByID(id uint64) (*users.User, error) { + if s.users == nil { + return nil, errors.ErrNotExist + } + u, err := s.users.GetUserByID(id) + if err != nil { + return nil, err + } + return &u, nil +} + +func (s *WebAuthnService) BeginMFALogin(username, password string, rpID string) (sessionID string, assertion *protocol.CredentialAssertion, err error) { + id, resErr := users.ResolveUsernameToID(username) + if resErr != nil { + return "", nil, resErr + } + user, getErr := s.userByID(id) passwordHash := utils.InvalidPasswordHash if getErr == nil { passwordHash = user.Password @@ -114,14 +142,14 @@ func (s *WebAuthnService) BeginMFALogin(username, password string, rpID string, sessionID = generateSessionID() s.sessions.Store(sessionID, &webAuthnSession{ SessionData: sessionData, - UserID: user.ID, + UserID: uint(user.ID), ExpiresAt: time.Now().Add(5 * time.Minute), }) return sessionID, assertion, nil } -func (s *WebAuthnService) FinishMFALogin(sessionID string, r *http.Request, userStore *users.Storage) (*users.User, error) { +func (s *WebAuthnService) FinishMFALogin(sessionID string, r *http.Request) (*users.User, error) { sessionVal, ok := s.sessions.Load(sessionID) if !ok { return nil, errors.ErrPasskeyInvalidSession @@ -136,7 +164,7 @@ func (s *WebAuthnService) FinishMFALogin(sessionID string, r *http.Request, user return nil, errors.ErrPasskeyInvalidSession } - user, err := userStore.Get(sess.UserID) + user, err := s.userByID(uint64(sess.UserID)) if err != nil { return nil, fmt.Errorf("user not found: %w", err) } @@ -150,9 +178,6 @@ func (s *WebAuthnService) FinishMFALogin(sessionID string, r *http.Request, user for i := range user.PasskeyCredentials { if user.PasskeyCredentials[i].ID == credB64 { users.UpdateCredentialFromLibrary(&user.PasskeyCredentials[i], credential) - if err := userStore.Update(user, false, "PasskeyCredentials"); err != nil { - return nil, fmt.Errorf("failed to update credential: %w", err) - } return user, nil } } @@ -173,7 +198,7 @@ func (s *WebAuthnService) BeginRegistration(user *users.User, rpID string) (sess sessionID = generateSessionID() s.sessions.Store(sessionID, &webAuthnSession{ SessionData: sessionData, - UserID: user.ID, + UserID: uint(user.ID), ExpiresAt: time.Now().Add(5 * time.Minute), }) @@ -195,7 +220,7 @@ func (s *WebAuthnService) FinishRegistration(user *users.User, sessionID string, return errors.ErrPasskeyInvalidSession } - if sess.UserID != user.ID { + if sess.UserID != uint(user.ID) { return errors.ErrUnauthorized } @@ -253,8 +278,8 @@ func (s *WebAuthnService) cleanupExpiredSessions() { func deriveWebAuthnConfig(cfg *settings.PasskeyAuthConfig) (*webauthn.Config, error) { rpID := cfg.RPID if rpID == "" { - if settings.Config.Server.ExternalUrl != "" { - if u, err := url.Parse(settings.Config.Server.ExternalUrl); err == nil { + if settings.Config.Http.ExternalUrl != "" { + if u, err := url.Parse(settings.Config.Http.ExternalUrl); err == nil { rpID = u.Hostname() } } @@ -273,11 +298,11 @@ func deriveWebAuthnConfig(cfg *settings.PasskeyAuthConfig) (*webauthn.Config, er origins := cfg.RPOrigins if len(origins) == 0 { - if settings.Config.Server.ExternalUrl != "" { - origins = append(origins, settings.Config.Server.ExternalUrl) + if settings.Config.Http.ExternalUrl != "" { + origins = append(origins, settings.Config.Http.ExternalUrl) } - if settings.Config.Server.InternalUrl != "" && settings.Config.Server.InternalUrl != settings.Config.Server.ExternalUrl { - origins = append(origins, settings.Config.Server.InternalUrl) + if settings.Config.Http.InternalUrl != "" && settings.Config.Http.InternalUrl != settings.Config.Http.ExternalUrl { + origins = append(origins, settings.Config.Http.InternalUrl) } if len(origins) == 0 { origins = append(origins, "http://localhost") @@ -285,9 +310,9 @@ func deriveWebAuthnConfig(cfg *settings.PasskeyAuthConfig) (*webauthn.Config, er } return &webauthn.Config{ - RPID: rpID, - RPDisplayName: displayName, - RPOrigins: origins, + RPID: rpID, + RPDisplayName: displayName, + RPOrigins: origins, AttestationPreference: protocol.PreferNoAttestation, AuthenticatorSelection: protocol.AuthenticatorSelection{ UserVerification: protocol.VerificationPreferred, diff --git a/backend/database/access/access.go b/backend/internal/database/access/access.go similarity index 75% rename from backend/database/access/access.go rename to backend/internal/database/access/access.go index 399508ca9e..dc74dce41f 100644 --- a/backend/database/access/access.go +++ b/backend/internal/database/access/access.go @@ -1,7 +1,6 @@ package access import ( - "encoding/json" "fmt" "maps" "path/filepath" @@ -11,11 +10,10 @@ import ( "sync" "time" - "github.com/asdine/storm/v3" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" "github.com/gtsteffaniak/go-cache/cache" "github.com/gtsteffaniak/go-logger/logger" ) @@ -27,8 +25,6 @@ var ( rulesCache = cache.NewCache[map[string]FrontendAccessRule](1 * time.Minute) // for rules ) -const accessRulesBucket = "access_rules" -const accessRulesKey = "rules" const accessChangedKey = "newRule:" type RuleMap map[string]*AccessRule @@ -36,13 +32,6 @@ type SourceRuleMap map[string]RuleMap type StringSet map[string]struct{} -type dbStorage struct { - AllRules SourceRuleMap `json:"all_rules"` - Groups GroupMap `json:"groups"` - RevokedTokens map[string]struct{} `json:"revoked_tokens"` // set of revoked token hashes - HashedTokens map[string]uint `json:"hashed_tokens"` // maps token hash → user ID -} - // RuleSet groups users and groups for allow/deny lists. type RuleSet struct { Users StringSet @@ -78,90 +67,40 @@ type Storage struct { AllRules SourceRuleMap // AllRules[sourcePath][indexPath] - in-memory authoritative state Groups GroupMap // key: group name, value: set of usernames - in-memory authoritative state RevokedTokens map[string]struct{} // set of revoked token hashes - in-memory authoritative state - HashedTokens map[string]uint // maps token hash → user ID - in-memory authoritative state - DB *storm.DB // Optional: DB for persistence + HashedTokens map[string]uint64 // maps token hash → owner user id - in-memory authoritative state Users *users.Storage // Reference to users storage + sqlStore SQLPersister // SQL store for persistence } -// SaveToDB persists all rules to the DB if DB is set. -// IMPORTANT: Caller must hold s.mux lock (either read or write). -func (s *Storage) SaveToDB() error { - if s.DB == nil { - return nil - } - data, err := json.Marshal(&dbStorage{ - AllRules: s.AllRules, - Groups: s.Groups, - RevokedTokens: s.RevokedTokens, - HashedTokens: s.HashedTokens, - }) - if err != nil { - return err - } - return s.DB.Set(accessRulesBucket, accessRulesKey, data) +// SQLPersister interface for SQL persistence operations +type SQLPersister interface { + SaveAccessRule(source, path string, rule *AccessRule) error + DeleteAccessRule(source, path string) error + SaveGroup(name string, members StringSet) error + DeleteGroup(name string) error + SaveRevokedToken(tokenHash string) error + SaveHashedToken(tokenHash string, userID uint64) error + DeleteHashedToken(tokenHash string) error + DeleteHashedTokensByUserID(userID uint64) error } -// Flush persists the current in-memory state to the backing store. -// Call during graceful shutdown to ensure DB matches memory. +// SetSQLStore sets the SQL store for persistence operations +func (s *Storage) SetSQLStore(sqlStore SQLPersister) { + s.sqlStore = sqlStore +} + +// Flush is a no-op; access rule updates already write through sqlStore when configured. func (s *Storage) Flush() error { - s.mux.RLock() - defer s.mux.RUnlock() - return s.SaveToDB() -} - -// LoadFromDB loads all rules from the DB if DB is set. -func (s *Storage) LoadFromDB() error { - if s.DB == nil { - return nil - } - var data []byte - err := s.DB.Get(accessRulesBucket, accessRulesKey, &data) - if err != nil { - return err - } - var storage dbStorage - if err := json.Unmarshal(data, &storage); err != nil { - return err - } - s.mux.Lock() - s.AllRules = storage.AllRules - if s.AllRules == nil { - s.AllRules = make(SourceRuleMap) - } - s.Groups = storage.Groups - if s.Groups == nil { - s.Groups = make(GroupMap) - } - s.RevokedTokens = storage.RevokedTokens - if s.RevokedTokens == nil { - s.RevokedTokens = make(map[string]struct{}) - } - s.HashedTokens = storage.HashedTokens - if s.HashedTokens == nil { - s.HashedTokens = make(map[string]uint) - } - s.HashedTokens = storage.HashedTokens - if s.HashedTokens == nil { - s.HashedTokens = make(map[string]uint) - } - s.mux.Unlock() return nil } -// NewStorage creates a new Storage instance. Optionally pass a DB for persistence and users storage. -// After creating Storage with a DB, call LoadFromDB() to load rules from the database on startup. -// Example: -// -// store := NewStorage(db, usersStore) -// err := store.LoadFromDB() -// if err != nil { /* handle error */ } -func NewStorage(db *storm.DB, usersStore *users.Storage) *Storage { +// NewStorage creates a new Storage instance. +func NewStorage(usersStore *users.Storage) *Storage { var s = &Storage{ AllRules: make(SourceRuleMap), Groups: make(GroupMap), RevokedTokens: make(map[string]struct{}), - HashedTokens: make(map[string]uint), - DB: db, + HashedTokens: make(map[string]uint64), Users: usersStore, } return s @@ -184,8 +123,43 @@ func (s *Storage) clearAllCaches() { rulesCache.ClearAll() } -// RemoveRuleByPath removes a rule by its exact path from the internal storage -func (s *Storage) RemoveRuleByPath(sourcePath, indexPath string) { +func accessRuleHasPayload(rule *AccessRule) bool { + if rule == nil { + return false + } + return rule.DenyAll || + len(rule.Allow.Users) > 0 || len(rule.Allow.Groups) > 0 || + len(rule.Deny.Users) > 0 || len(rule.Deny.Groups) > 0 +} + +// persistRuleSQLNL upserts or deletes one access_rules row to match in-memory state. +// Caller must hold s.mux (write lock). normalizedPath must match rule map keys (see getOrCreateRuleNL). +func (s *Storage) persistRuleSQLNL(sourcePath, normalizedPath string) { + if s.sqlStore == nil { + return + } + var rule *AccessRule + if bySrc, ok := s.AllRules[sourcePath]; ok { + rule = bySrc[normalizedPath] + } + if !accessRuleHasPayload(rule) { + if err := s.sqlStore.DeleteAccessRule(sourcePath, normalizedPath); err != nil { + logger.Warningf("access rules SQL delete (source=%s path=%s): %v", sourcePath, normalizedPath, err) + } + return + } + if err := s.sqlStore.SaveAccessRule(sourcePath, normalizedPath, rule); err != nil { + logger.Warningf("access rules SQL save (source=%s path=%s): %v", sourcePath, normalizedPath, err) + } +} + +// RemoveRuleByPath removes a rule by normalized index path. +func (s *Storage) RemoveRuleByPath(sourcePath string, indexPath utils.IndexPath) { + s.RemoveRuleByPathKey(sourcePath, ruleKey(indexPath)) +} + +// RemoveRuleByPathKey removes a rule by its exact storage key (for legacy migration paths). +func (s *Storage) RemoveRuleByPathKey(sourcePath, pathKey string) { s.mux.Lock() defer s.mux.Unlock() @@ -194,26 +168,28 @@ func (s *Storage) RemoveRuleByPath(sourcePath, indexPath string) { return } - // Remove the rule by exact path match (don't normalize) - if _, exists := rulesBySource[indexPath]; exists { - delete(rulesBySource, indexPath) - // If no rules left for this source, remove the source entry - if len(rulesBySource) == 0 { - delete(s.AllRules, sourcePath) - } - s.clearAllCaches() - err := s.SaveToDB() - if err != nil { - logger.Errorf("error saving access rules to database: %v", err) + if _, exists := rulesBySource[pathKey]; !exists { + return + } + delete(rulesBySource, pathKey) + if len(rulesBySource) == 0 { + delete(s.AllRules, sourcePath) + } + s.clearAllCaches() + s.persistRuleSQLNL(sourcePath, pathKey) + if s.sqlStore != nil { + _ = s.sqlStore.DeleteAccessRule(sourcePath, pathKey) + normalized := utils.AddTrailingSlashIfNotExists(pathKey) + if normalized != pathKey { + _ = s.sqlStore.DeleteAccessRule(sourcePath, normalized) } } } // getOrCreateRuleNL ensures a rule exists for the given source and index path. // The caller must hold the lock. -func (s *Storage) getOrCreateRuleNL(sourcePath, indexPath string) *AccessRule { - // Normalize the path to ensure consistent rule storage - normalizedPath := utils.AddTrailingSlashIfNotExists(indexPath) +func (s *Storage) getOrCreateRuleNL(sourcePath string, indexPath utils.IndexPath) *AccessRule { + normalizedPath := ruleKey(indexPath) if _, ok := s.AllRules[sourcePath]; !ok { s.AllRules[sourcePath] = make(RuleMap) } @@ -229,13 +205,8 @@ func (s *Storage) getOrCreateRuleNL(sourcePath, indexPath string) *AccessRule { } // DenyUser adds a user to the deny list for a given source and index path. -func (s *Storage) DenyUser(sourcePath, indexPath, username string) error { - if s.Users != nil { - _, err := s.Users.Get(username) - if err != nil { - return fmt.Errorf("user '%s' does not exist: %w", username, err) - } - } +// Rules are keyed by login name (username), not user id. +func (s *Storage) DenyUser(sourcePath string, indexPath utils.IndexPath, username string) error { s.mux.Lock() defer s.mux.Unlock() rule := s.getOrCreateRuleNL(sourcePath, indexPath) @@ -244,17 +215,13 @@ func (s *Storage) DenyUser(sourcePath, indexPath, username string) error { } rule.Deny.Users[username] = struct{}{} s.clearAllCaches() - return s.SaveToDB() + s.persistRuleSQLNL(sourcePath, ruleKey(indexPath)) + return nil } // AllowUser adds a user to the allow list for a given source and index path. -func (s *Storage) AllowUser(sourcePath, indexPath, username string) error { - if s.Users != nil { - _, err := s.Users.Get(username) - if err != nil { - return fmt.Errorf("user '%s' does not exist: %w", username, err) - } - } +// Rules are keyed by login name (username), not user id. +func (s *Storage) AllowUser(sourcePath string, indexPath utils.IndexPath, username string) error { s.mux.Lock() defer s.mux.Unlock() rule := s.getOrCreateRuleNL(sourcePath, indexPath) @@ -263,11 +230,12 @@ func (s *Storage) AllowUser(sourcePath, indexPath, username string) error { } rule.Allow.Users[username] = struct{}{} s.clearAllCaches() - return s.SaveToDB() + s.persistRuleSQLNL(sourcePath, ruleKey(indexPath)) + return nil } // DenyGroup adds a group to the deny list for a given source and index path. -func (s *Storage) DenyGroup(sourcePath, indexPath, groupname string) error { +func (s *Storage) DenyGroup(sourcePath string, indexPath utils.IndexPath, groupname string) error { s.mux.Lock() defer s.mux.Unlock() _, ok := s.Groups[groupname] @@ -280,11 +248,12 @@ func (s *Storage) DenyGroup(sourcePath, indexPath, groupname string) error { } rule.Deny.Groups[groupname] = struct{}{} s.clearAllCaches() - return s.SaveToDB() + s.persistRuleSQLNL(sourcePath, ruleKey(indexPath)) + return nil } // AllowGroup adds a group to the allow list for a given source and index path. -func (s *Storage) AllowGroup(sourcePath, indexPath, groupname string) error { +func (s *Storage) AllowGroup(sourcePath string, indexPath utils.IndexPath, groupname string) error { s.mux.Lock() defer s.mux.Unlock() _, ok := s.Groups[groupname] @@ -297,11 +266,12 @@ func (s *Storage) AllowGroup(sourcePath, indexPath, groupname string) error { } rule.Allow.Groups[groupname] = struct{}{} s.clearAllCaches() - return s.SaveToDB() + s.persistRuleSQLNL(sourcePath, ruleKey(indexPath)) + return nil } // DenyAll sets a rule to deny all access for a given source and index path. -func (s *Storage) DenyAll(sourcePath, indexPath string) error { +func (s *Storage) DenyAll(sourcePath string, indexPath utils.IndexPath) error { s.mux.Lock() defer s.mux.Unlock() rule := s.getOrCreateRuleNL(sourcePath, indexPath) @@ -310,16 +280,14 @@ func (s *Storage) DenyAll(sourcePath, indexPath string) error { } rule.DenyAll = true s.clearAllCaches() - return s.SaveToDB() + s.persistRuleSQLNL(sourcePath, ruleKey(indexPath)) + return nil } // Permitted checks if a username is permitted for a given sourcePath and indexPath, recursively checking parent directories. -func (s *Storage) Permitted(sourcePath, indexPath, username string) bool { - // Ensure leading slash - if !strings.HasPrefix(indexPath, "/") { - indexPath = "/" + indexPath - } - indexPath = utils.AddTrailingSlashIfNotExists(indexPath) +func (s *Storage) Permitted(sourcePath string, indexPath utils.IndexPath, username string) bool { + indexPath = checkPath(indexPath) + pathStr := indexPath.String() // Get current version for the sourcePath versionKey := "version:" + sourcePath @@ -329,7 +297,7 @@ func (s *Storage) Permitted(sourcePath, indexPath, username string) bool { } // Check cache with versioned key - permKey := fmt.Sprintf("perm:%s:%d:%s:%s", sourcePath, version, indexPath, username) + permKey := fmt.Sprintf("perm:%s:%d:%s:%s", sourcePath, version, pathStr, username) if p, ok := permissionCache.Get(permKey); ok { return p } @@ -341,28 +309,19 @@ func (s *Storage) Permitted(sourcePath, indexPath, username string) bool { return result } -func (s *Storage) computePermitted(sourcePath, indexPath, username string) bool { +func (s *Storage) computePermitted(sourcePath string, indexPath utils.IndexPath, username string) bool { var rulesFound []*AccessRule - // Walk up the path hierarchy and collect all relevant rules - currentPath := indexPath - pathLevel := 0 + currentPath := checkPath(indexPath) for { rule, found := s.getRuleAtExactPath(sourcePath, currentPath) if found { rulesFound = append(rulesFound, rule) } - if currentPath == "/" || currentPath == "." || currentPath == "" { + if currentPath.IsRoot() { break } - oldPath := currentPath - currentPath = utils.GetParentDirectoryPath(currentPath) - - // Safety check to prevent infinite loops - if currentPath == oldPath { - break - } - pathLevel++ + currentPath = currentPath.Parent() } // Now evaluate the rules, starting from the most specific (indexPath) to the least specific (root) @@ -393,16 +352,14 @@ func (s *Storage) computePermitted(sourcePath, indexPath, username string) bool } // getRuleAtExactPath is a helper to get a rule without the recursive logic. -func (s *Storage) getRuleAtExactPath(sourcePath, indexPath string) (*AccessRule, bool) { +func (s *Storage) getRuleAtExactPath(sourcePath string, indexPath utils.IndexPath) (*AccessRule, bool) { s.mux.RLock() defer s.mux.RUnlock() rulesBySource, ok := s.AllRules[sourcePath] if !ok { return nil, false } - // Normalize the path to ensure consistent rule lookup - normalizedPath := utils.AddTrailingSlashIfNotExists(indexPath) - rule, ok := rulesBySource[normalizedPath] + rule, ok := rulesBySource[ruleKey(indexPath)] return rule, ok } @@ -449,7 +406,7 @@ func (s *Storage) isUserInGroup(username, group string) bool { } // GetRule retrieves a rule for a sourcePath and indexPath. -func (s *Storage) GetFrontendRules(sourcePath, indexPath string) (FrontendAccessRule, bool) { +func (s *Storage) GetFrontendRules(sourcePath string, indexPath utils.IndexPath) (FrontendAccessRule, bool) { s.mux.RLock() defer s.mux.RUnlock() @@ -461,7 +418,7 @@ func (s *Storage) GetFrontendRules(sourcePath, indexPath string) (FrontendAccess } // Check if path exists on filesystem - pathExists := utils.CheckPathExists(filepath.Join(sourcePath, indexPath)) + pathExists := utils.CheckPathExists(filepath.Join(sourcePath, indexPath.String())) frontendRules := FrontendAccessRule{ SourceDenyDefault: sourceDenyDefault, @@ -479,7 +436,7 @@ func (s *Storage) GetFrontendRules(sourcePath, indexPath string) (FrontendAccess if !ok { return frontendRules, false } - rule, ok := rulesBySource[indexPath] + rule, ok := rulesBySource[ruleKey(indexPath)] if !ok || rule == nil { return frontendRules, false } @@ -559,7 +516,7 @@ func (s *Storage) AddUserToGroup(group, username string) error { return nil } s.Groups[group][username] = struct{}{} - return s.SaveToDB() + return nil } // GetAllGroups returns all group names. @@ -623,7 +580,7 @@ func (s *Storage) SyncUserGroups(username string, newGroups []string) error { } } if changed { - return s.SaveToDB() + return nil } return nil } @@ -643,14 +600,14 @@ func (s *Storage) RemoveUserFromGroup(group, username string) error { if len(s.Groups[group]) == 0 { delete(s.Groups, group) } - return s.SaveToDB() + return nil } // RemoveAllowUser removes a user from the allow list for a given source and index path. -func (s *Storage) RemoveAllowUser(sourcePath, indexPath, username string) (bool, error) { +func (s *Storage) RemoveAllowUser(sourcePath string, indexPath utils.IndexPath, username string) (bool, error) { s.mux.Lock() defer s.mux.Unlock() - normalizedPath := utils.AddTrailingSlashIfNotExists(indexPath) + normalizedPath := ruleKey(indexPath) rule, ok := s.AllRules[sourcePath][normalizedPath] if !ok { return false, nil @@ -669,16 +626,17 @@ func (s *Storage) RemoveAllowUser(sourcePath, indexPath, username string) (bool, } if removed { s.clearAllCaches() - return exists, s.SaveToDB() + s.persistRuleSQLNL(sourcePath, normalizedPath) + return exists, nil } return false, nil } // RemoveAllowGroup removes a group from the allow list for a given source and index path. -func (s *Storage) RemoveAllowGroup(sourcePath, indexPath, groupname string) (bool, error) { +func (s *Storage) RemoveAllowGroup(sourcePath string, indexPath utils.IndexPath, groupname string) (bool, error) { s.mux.Lock() defer s.mux.Unlock() - normalizedPath := utils.AddTrailingSlashIfNotExists(indexPath) + normalizedPath := ruleKey(indexPath) rule, ok := s.AllRules[sourcePath][normalizedPath] if !ok { return false, nil @@ -697,16 +655,17 @@ func (s *Storage) RemoveAllowGroup(sourcePath, indexPath, groupname string) (boo } if removed { s.clearAllCaches() - return exists, s.SaveToDB() + s.persistRuleSQLNL(sourcePath, normalizedPath) + return exists, nil } - return exists, nil + return false, nil } // RemoveDenyUser removes a user from the deny list for a given source and index path. -func (s *Storage) RemoveDenyUser(sourcePath, indexPath, username string) (bool, error) { +func (s *Storage) RemoveDenyUser(sourcePath string, indexPath utils.IndexPath, username string) (bool, error) { s.mux.Lock() defer s.mux.Unlock() - normalizedPath := utils.AddTrailingSlashIfNotExists(indexPath) + normalizedPath := ruleKey(indexPath) rule, ok := s.AllRules[sourcePath][normalizedPath] if !ok { return false, nil @@ -725,16 +684,17 @@ func (s *Storage) RemoveDenyUser(sourcePath, indexPath, username string) (bool, } if removed { s.clearAllCaches() - return exists, s.SaveToDB() + s.persistRuleSQLNL(sourcePath, normalizedPath) + return exists, nil } return false, nil } // RemoveDenyGroup removes a group from the deny list for a given source and index path. -func (s *Storage) RemoveDenyGroup(sourcePath, indexPath, groupname string) (bool, error) { +func (s *Storage) RemoveDenyGroup(sourcePath string, indexPath utils.IndexPath, groupname string) (bool, error) { s.mux.Lock() defer s.mux.Unlock() - normalizedPath := utils.AddTrailingSlashIfNotExists(indexPath) + normalizedPath := ruleKey(indexPath) rule, ok := s.AllRules[sourcePath][normalizedPath] if !ok { return false, nil @@ -753,16 +713,17 @@ func (s *Storage) RemoveDenyGroup(sourcePath, indexPath, groupname string) (bool } if removed { s.clearAllCaches() - return exists, s.SaveToDB() + s.persistRuleSQLNL(sourcePath, normalizedPath) + return exists, nil } - return exists, nil + return false, nil } // RemoveDenyAll removes the deny all rule for a given source and index path. -func (s *Storage) RemoveDenyAll(sourcePath, indexPath string) (bool, error) { +func (s *Storage) RemoveDenyAll(sourcePath string, indexPath utils.IndexPath) (bool, error) { s.mux.Lock() defer s.mux.Unlock() - normalizedPath := utils.AddTrailingSlashIfNotExists(indexPath) + normalizedPath := ruleKey(indexPath) rule, ok := s.AllRules[sourcePath][normalizedPath] if !ok { return false, nil @@ -781,7 +742,8 @@ func (s *Storage) RemoveDenyAll(sourcePath, indexPath string) (bool, error) { } if removed { s.clearAllCaches() - return true, s.SaveToDB() + s.persistRuleSQLNL(sourcePath, normalizedPath) + return true, nil } return false, nil } @@ -791,17 +753,23 @@ func (s *Storage) RemoveAllRulesForUser(username string) error { s.mux.Lock() defer s.mux.Unlock() changed := false - changedSourcePaths := make(map[string]struct{}) + dirty := make(map[string]map[string]struct{}) + touch := func(sp, ip string) { + if dirty[sp] == nil { + dirty[sp] = make(map[string]struct{}) + } + dirty[sp][ip] = struct{}{} + } for sourcePath, rulesBySource := range s.AllRules { for indexPath, rule := range rulesBySource { if _, exists := rule.Allow.Users[username]; exists { delete(rule.Allow.Users, username) - changedSourcePaths[sourcePath] = struct{}{} + touch(sourcePath, indexPath) changed = true } if _, exists := rule.Deny.Users[username]; exists { delete(rule.Deny.Users, username) - changedSourcePaths[sourcePath] = struct{}{} + touch(sourcePath, indexPath) changed = true } if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 { @@ -809,12 +777,17 @@ func (s *Storage) RemoveAllRulesForUser(username string) error { if len(s.AllRules[sourcePath]) == 0 { delete(s.AllRules, sourcePath) } + touch(sourcePath, indexPath) } } } if changed { s.clearAllCaches() - return s.SaveToDB() + for sp, paths := range dirty { + for ip := range paths { + s.persistRuleSQLNL(sp, ip) + } + } } return nil } @@ -824,17 +797,23 @@ func (s *Storage) RemoveAllRulesForGroup(groupname string) error { s.mux.Lock() defer s.mux.Unlock() changed := false - changedSourcePaths := make(map[string]struct{}) + dirty := make(map[string]map[string]struct{}) + touch := func(sp, ip string) { + if dirty[sp] == nil { + dirty[sp] = make(map[string]struct{}) + } + dirty[sp][ip] = struct{}{} + } for sourcePath, rulesBySource := range s.AllRules { for indexPath, rule := range rulesBySource { if _, exists := rule.Allow.Groups[groupname]; exists { delete(rule.Allow.Groups, groupname) - changedSourcePaths[sourcePath] = struct{}{} + touch(sourcePath, indexPath) changed = true } if _, exists := rule.Deny.Groups[groupname]; exists { delete(rule.Deny.Groups, groupname) - changedSourcePaths[sourcePath] = struct{}{} + touch(sourcePath, indexPath) changed = true } if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 { @@ -842,12 +821,17 @@ func (s *Storage) RemoveAllRulesForGroup(groupname string) error { if len(s.AllRules[sourcePath]) == 0 { delete(s.AllRules, sourcePath) } + touch(sourcePath, indexPath) } } } if changed { s.clearAllCaches() - return s.SaveToDB() + for sp, paths := range dirty { + for ip := range paths { + s.persistRuleSQLNL(sp, ip) + } + } } return nil } @@ -1057,27 +1041,25 @@ func (s *Storage) GetAllRulesByGroups(sourcePath string) map[string]map[string]F // HasAnyVisibleItems checks if a user has access to any items in a given parent path. // This is used to determine if a user should see a folder's contents even when // they don't have direct access to the parent folder. -func (s *Storage) HasAnyVisibleItems(sourcePath, parentPath string, itemNames []string, username string) bool { - parentPath = utils.AddTrailingSlashIfNotExists(parentPath) - // Check if user has access to any of the items +func (s *Storage) HasAnyVisibleItems(sourcePath string, parentPath utils.IndexPath, itemNames []string, username string) bool { + parent := checkPath(parentPath) for _, itemName := range itemNames { - indexPath := parentPath + itemName - if s.Permitted(sourcePath, indexPath, username) { + child := parent.Join(itemName, true) + if s.Permitted(sourcePath, child, username) { return true } } - return false } // RemoveUserCascade removes a user from either the allow or deny list for a given path and all its subpaths. // This is used for cascade delete operations when deleting user access from a directory tree. // The allow parameter determines which list to remove from: true for allow list, false for deny list. -func (s *Storage) RemoveUserCascade(sourcePath, indexPath, username string, allow bool) (int, error) { +func (s *Storage) RemoveUserCascade(sourcePath string, indexPath utils.IndexPath, username string, allow bool) (int, error) { s.mux.Lock() defer s.mux.Unlock() - normalizedPath := utils.AddTrailingSlashIfNotExists(indexPath) + normalizedPath := ruleKey(indexPath) rulesBySource, ok := s.AllRules[sourcePath] if !ok { return 0, nil @@ -1085,17 +1067,20 @@ func (s *Storage) RemoveUserCascade(sourcePath, indexPath, username string, allo changed := false removedCount := 0 + touchedPaths := make(map[string]struct{}) // Iterate through all rules for this source for rulePath, rule := range rulesBySource { // Check if this rule path matches or is a subpath of the target path if rulePath == normalizedPath || strings.HasPrefix(rulePath, normalizedPath) { + pathChanged := false if allow { // Remove user from allow list only if _, exists := rule.Allow.Users[username]; exists { delete(rule.Allow.Users, username) changed = true removedCount++ + pathChanged = true } } else { // Remove user from deny list only @@ -1103,6 +1088,7 @@ func (s *Storage) RemoveUserCascade(sourcePath, indexPath, username string, allo delete(rule.Deny.Users, username) changed = true removedCount++ + pathChanged = true } } @@ -1110,6 +1096,10 @@ func (s *Storage) RemoveUserCascade(sourcePath, indexPath, username string, allo if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 && !rule.DenyAll { delete(s.AllRules[sourcePath], rulePath) + pathChanged = true + } + if pathChanged { + touchedPaths[rulePath] = struct{}{} } } } @@ -1121,7 +1111,10 @@ func (s *Storage) RemoveUserCascade(sourcePath, indexPath, username string, allo if changed { s.clearAllCaches() - return removedCount, s.SaveToDB() + for rp := range touchedPaths { + s.persistRuleSQLNL(sourcePath, rp) + } + return removedCount, nil } return 0, nil @@ -1130,11 +1123,11 @@ func (s *Storage) RemoveUserCascade(sourcePath, indexPath, username string, allo // RemoveGroupCascade removes a group from either the allow or deny list for a given path and all its subpaths. // This is used for cascade delete operations when deleting group access from a directory tree. // The allow parameter determines which list to remove from: true for allow list, false for deny list. -func (s *Storage) RemoveGroupCascade(sourcePath, indexPath, groupname string, allow bool) (int, error) { +func (s *Storage) RemoveGroupCascade(sourcePath string, indexPath utils.IndexPath, groupname string, allow bool) (int, error) { s.mux.Lock() defer s.mux.Unlock() - normalizedPath := utils.AddTrailingSlashIfNotExists(indexPath) + normalizedPath := ruleKey(indexPath) rulesBySource, ok := s.AllRules[sourcePath] if !ok { return 0, nil @@ -1142,17 +1135,20 @@ func (s *Storage) RemoveGroupCascade(sourcePath, indexPath, groupname string, al changed := false removedCount := 0 + touchedPaths := make(map[string]struct{}) // Iterate through all rules for this source for rulePath, rule := range rulesBySource { // Check if this rule path matches or is a subpath of the target path if rulePath == normalizedPath || strings.HasPrefix(rulePath, normalizedPath) { + pathChanged := false if allow { // Remove group from allow list only if _, exists := rule.Allow.Groups[groupname]; exists { delete(rule.Allow.Groups, groupname) changed = true removedCount++ + pathChanged = true } } else { // Remove group from deny list only @@ -1160,6 +1156,7 @@ func (s *Storage) RemoveGroupCascade(sourcePath, indexPath, groupname string, al delete(rule.Deny.Groups, groupname) changed = true removedCount++ + pathChanged = true } } @@ -1167,6 +1164,10 @@ func (s *Storage) RemoveGroupCascade(sourcePath, indexPath, groupname string, al if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 && !rule.DenyAll { delete(s.AllRules[sourcePath], rulePath) + pathChanged = true + } + if pathChanged { + touchedPaths[rulePath] = struct{}{} } } } @@ -1178,7 +1179,10 @@ func (s *Storage) RemoveGroupCascade(sourcePath, indexPath, groupname string, al if changed { s.clearAllCaches() - return removedCount, s.SaveToDB() + for rp := range touchedPaths { + s.persistRuleSQLNL(sourcePath, rp) + } + return removedCount, nil } return 0, nil @@ -1186,7 +1190,7 @@ func (s *Storage) RemoveGroupCascade(sourcePath, indexPath, groupname string, al // UpdateRules updates all access rules that match oldPath to point to newPath. // Handles both exact matches and subdirectories. Similar to share.Storage.UpdateShares. -func (s *Storage) UpdateRules(sourcePath, oldPath, newPath string) (int, error) { +func (s *Storage) UpdateRules(sourcePath string, oldPath, newPath utils.IndexPath) (int, error) { s.mux.Lock() defer s.mux.Unlock() @@ -1195,21 +1199,18 @@ func (s *Storage) UpdateRules(sourcePath, oldPath, newPath string) (int, error) return 0, nil // No rules for this source, not an error } - // Normalize paths (always add trailing slash for access rules) - oldPath = utils.AddTrailingSlashIfNotExists(oldPath) - newPath = utils.AddTrailingSlashIfNotExists(newPath) + oldKey := ruleKey(oldPath) + newKey := ruleKey(newPath) updated := 0 rulesToUpdate := make(map[string]string) // old path -> new path // Find all rules that need to be updated for rulePath := range rulesBySource { - if rulePath == oldPath { - // Exact match - rulesToUpdate[rulePath] = newPath - } else if strings.HasPrefix(rulePath, oldPath) { - // Subdirectory - replace prefix - newRulePath := newPath + strings.TrimPrefix(rulePath, oldPath) + if rulePath == oldKey { + rulesToUpdate[rulePath] = newKey + } else if strings.HasPrefix(rulePath, oldKey) { + newRulePath := newKey + strings.TrimPrefix(rulePath, oldKey) rulesToUpdate[rulePath] = newRulePath } } @@ -1225,8 +1226,13 @@ func (s *Storage) UpdateRules(sourcePath, oldPath, newPath string) (int, error) if updated > 0 { s.clearAllCaches() - if err := s.SaveToDB(); err != nil { - return updated, err + for oldRulePath := range rulesToUpdate { + if s.sqlStore != nil { + _ = s.sqlStore.DeleteAccessRule(sourcePath, oldRulePath) + } + } + for _, newRulePath := range rulesToUpdate { + s.persistRuleSQLNL(sourcePath, newRulePath) } } @@ -1234,42 +1240,48 @@ func (s *Storage) UpdateRules(sourcePath, oldPath, newPath string) (int, error) } // UpdateRulePath updates the path for a specific access rule (used by PATCH API endpoint). -func (s *Storage) UpdateRulePath(sourcePath, oldPath, newPath string) error { +func (s *Storage) UpdateRulePath(sourcePath string, oldPath, newPath utils.IndexPath) error { s.mux.Lock() defer s.mux.Unlock() - // Normalize paths - oldPath = utils.AddTrailingSlashIfNotExists(oldPath) - newPath = utils.AddTrailingSlashIfNotExists(newPath) + oldKey := ruleKey(oldPath) + newKey := ruleKey(newPath) rulesBySource, ok := s.AllRules[sourcePath] if !ok { return fmt.Errorf("no rules found for source: %s", sourcePath) } - rule, ok := rulesBySource[oldPath] + rule, ok := rulesBySource[oldKey] if !ok { - return fmt.Errorf("no rule found for path: %s", oldPath) + return fmt.Errorf("no rule found for path: %s", oldKey) } - // Remove the old rule and add it with the new path - delete(rulesBySource, oldPath) - rulesBySource[newPath] = rule + delete(rulesBySource, oldKey) + rulesBySource[newKey] = rule s.clearAllCaches() - logger.Debugf("access rule path updated: source=%s, fromPath=%s, toPath=%s", sourcePath, oldPath, newPath) - return s.SaveToDB() + if s.sqlStore != nil { + _ = s.sqlStore.DeleteAccessRule(sourcePath, oldKey) + } + s.persistRuleSQLNL(sourcePath, newKey) + logger.Debugf("access rule path updated: source=%s, fromPath=%s, toPath=%s", sourcePath, oldKey, newKey) + return nil } // RevokeToken adds a token hash to the revoked list and persists to DB. func (s *Storage) RevokeToken(tokenHash string) error { - s.mux.Lock() - defer s.mux.Unlock() - tokenHash = utils.HashSHA256(tokenHash) + s.mux.Lock() s.RevokedTokens[tokenHash] = struct{}{} - // Also remove from HashedTokens to prevent future lookups delete(s.HashedTokens, tokenHash) - return s.SaveToDB() + sqlStore := s.sqlStore + s.mux.Unlock() + + if sqlStore != nil { + _ = sqlStore.DeleteHashedToken(tokenHash) + _ = sqlStore.SaveRevokedToken(tokenHash) + } + return nil } // IsTokenRevoked checks if a token hash is in the revoked list (memory-only read). @@ -1281,22 +1293,26 @@ func (s *Storage) IsTokenRevoked(tokenHash string) bool { return exists } -// AddHashedToken adds a token hash to user ID mapping. -func (s *Storage) AddApiToken(tokenString string, userID uint) error { - s.mux.Lock() - defer s.mux.Unlock() +// AddApiToken maps a token string hash to an owner user id (for minimal JWTs). +func (s *Storage) AddApiToken(tokenString string, userID uint64) error { tokenHash := utils.HashSHA256(tokenString) + s.mux.Lock() s.HashedTokens[tokenHash] = userID - return s.SaveToDB() + sqlStore := s.sqlStore + s.mux.Unlock() + if sqlStore != nil { + return sqlStore.SaveHashedToken(tokenHash, userID) + } + return nil } -// GetUserIDFromToken retrieves the user ID for a given token string (memory-only read). -func (s *Storage) GetUserIDFromToken(tokenString string) (uint, bool) { +// GetUserIDFromToken retrieves the owner user id for a given token string (memory read; SQL populated at startup). +func (s *Storage) GetUserIDFromToken(tokenString string) (uint64, bool) { s.mux.RLock() defer s.mux.RUnlock() tokenHash := utils.HashSHA256(tokenString) - userID, exists := s.HashedTokens[tokenHash] - return userID, exists + uid, exists := s.HashedTokens[tokenHash] + return uid, exists } // GetRevokedTokens returns a copy of all revoked token hashes. @@ -1313,9 +1329,33 @@ func (s *Storage) GetRevokedTokens() map[string]struct{} { // RemoveApiToken removes a token hash mapping (used when deleting API keys). func (s *Storage) RemoveApiToken(tokenString string) error { - s.mux.Lock() - defer s.mux.Unlock() tokenHash := utils.HashSHA256(tokenString) + s.mux.Lock() delete(s.HashedTokens, tokenHash) - return s.SaveToDB() + sqlStore := s.sqlStore + s.mux.Unlock() + if sqlStore != nil { + return sqlStore.DeleteHashedToken(tokenHash) + } + return nil +} + +// RemoveHashedTokensForUser removes every minimal-JWT hash → user id mapping for that owner. +// Call when deleting a user so recycled usernames never resolve leftover token hashes to a new id. +func (s *Storage) RemoveHashedTokensForUser(userID uint64) error { + if userID == 0 { + return nil + } + s.mux.Lock() + for hash, uid := range s.HashedTokens { + if uid == userID { + delete(s.HashedTokens, hash) + } + } + sqlStore := s.sqlStore + s.mux.Unlock() + if sqlStore != nil { + return sqlStore.DeleteHashedTokensByUserID(userID) + } + return nil } diff --git a/backend/database/access/access_test.go b/backend/internal/database/access/access_test.go similarity index 72% rename from backend/database/access/access_test.go rename to backend/internal/database/access/access_test.go index 5cd4de4b0e..aecb4d7c3c 100644 --- a/backend/database/access/access_test.go +++ b/backend/internal/database/access/access_test.go @@ -1,30 +1,99 @@ package access_test import ( + "os" "path/filepath" "strings" "testing" - "github.com/asdine/storm/v3" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/database/access" - boltusers "github.com/gtsteffaniak/filebrowser/backend/database/storage/bolt" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "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/database/access" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/sqldb" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" ) -func createTestStorage(t *testing.T) (*access.Storage, *users.Storage) { - dir := t.TempDir() - dbPath := filepath.Join(dir, "test.db") - db, err := storm.Open(dbPath) - if err != nil { - t.Fatalf("failed to open storm db: %v", err) +func idxPath(s string) utils.IndexPath { + return utils.IndexPathFromNormalized(s, true) +} + +// sqlStoreAdapter adapts SQLStore to implement users.StorageBackend interface +type sqlStoreAdapter struct { + store *sqldb.SQLStore +} + +func (s *sqlStoreAdapter) GetBy(id uint64) (*users.User, error) { + if id == 0 { + return nil, errors.ErrNotExist } - userStore := users.NewStorage(boltusers.NewUsersBackend(db)) - return access.NewStorage(db, userStore), userStore + return s.store.GetUserByID(id) +} + +func (s *sqlStoreAdapter) Gets() ([]*users.User, error) { + return s.store.ListUsers() +} + +func (s *sqlStoreAdapter) Save(user *users.User, changePass, disableScopeChange bool) error { + // Check if user exists + existingUser, err := s.store.GetUserByUsername(user.Username) + if err != nil { + // User doesn't exist - create new user + if user.ID == 0 { + nid, genErr := utils.RandomUint64ID() + if genErr != nil { + return genErr + } + user.ID = nid + } + return s.store.CreateUser(user) + } + // User exists - update + user.ID = existingUser.ID + return s.store.UpdateUser(user) +} + +func (s *sqlStoreAdapter) Update(user *users.User, adminActor bool, fields ...string) error { + return s.store.UpdateUser(user) +} + +func (s *sqlStoreAdapter) DeleteByID(id uint64) error { + return s.store.DeleteUserByID(id) +} + +func createTestStorage(t *testing.T) (*access.Storage, *users.Storage) { + // Create a temporary directory for the test database + tempDir, err := os.MkdirTemp("", "access_test_*") + if err != nil { + t.Fatalf("failed to create temp dir: %v", err) + } + t.Cleanup(func() { + os.RemoveAll(tempDir) + }) + + // Create an in-memory SQLite database for tests + dbPath := filepath.Join(tempDir, "test.db") + sqlStore, _, err := sqldb.NewSQLStore(dbPath) + if err != nil { + t.Fatalf("failed to create SQL store: %v", err) + } + t.Cleanup(func() { + sqlStore.Close() + }) + + // Wrap SQLStore with adapter + adapter := &sqlStoreAdapter{store: sqlStore} + userStore := users.NewStorage(adapter) + return access.NewStorage(userStore), userStore } func createTestUser(t *testing.T, userStore *users.Storage, username string) { - u := &users.User{NonAdminEditable: users.NonAdminEditable{Password: "test"}, Username: username} + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: username, + NonAdminEditable: users.NonAdminEditable{Password: "test"}, + }, + } err := userStore.Save(u, false, false) if err != nil { t.Fatalf("failed to create user %s: %v", username, err) @@ -59,8 +128,8 @@ func setupTestSources() { settings.Config.Server.SourceMap["mnt/storage"], settings.Config.Server.SourceMap["mnt/open"], } - settings.Config.UserDefaults.DefaultScopes = []users.SourceScope{ - {Name: "mnt/storage", Scope: "/"}, + settings.Config.UserDefaults.DefaultScopes = []users.BackendScope{ + {Path: "mnt/storage/", Scope: "/"}, } // Initialize user package resolvers settings.InitializeUserResolvers() @@ -71,17 +140,13 @@ func TestPermitted_UserBlacklist(t *testing.T) { s, userStore := createTestStorage(t) createTestUser(t, userStore, "alice") createTestUser(t, userStore, "bob") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } - if err := s.DenyUser("mnt/storage", "/secret", "alice"); err != nil { + if err := s.DenyUser("mnt/storage", idxPath("/secret"), "alice"); err != nil { t.Errorf("DenyUser failed: %v", err) } - if s.Permitted("mnt/storage", "/secret", "alice") { + if s.Permitted("mnt/storage", idxPath("/secret"), "alice") { t.Error("alice should not be permitted (denied)") } - if !s.Permitted("mnt/storage", "/secret", "bob") { + if !s.Permitted("mnt/storage", idxPath("/secret"), "bob") { t.Error("bob should be permitted (not denied)") } } @@ -91,17 +156,13 @@ func TestPermitted_UserWhitelist(t *testing.T) { s, userStore := createTestStorage(t) createTestUser(t, userStore, "alice") createTestUser(t, userStore, "bob") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } - if err := s.AllowUser("mnt/storage", "/vip", "bob"); err != nil { + if err := s.AllowUser("mnt/storage", idxPath("/vip"), "bob"); err != nil { t.Errorf("AllowUser failed: %v", err) } - if !s.Permitted("mnt/storage", "/vip", "bob") { + if !s.Permitted("mnt/storage", idxPath("/vip"), "bob") { t.Error("bob should be permitted (allowed)") } - if !s.Permitted("mnt/storage", "/vip", "alice") { + if !s.Permitted("mnt/storage", idxPath("/vip"), "alice") { t.Error("alice should be permitted (default allow behavior when DenyByDefault=false)") } } @@ -111,18 +172,14 @@ func TestPermitted_GroupBlacklist(t *testing.T) { s, userStore := createTestStorage(t) createTestUser(t, userStore, "alice") createTestUser(t, userStore, "bob") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } _ = s.AddUserToGroup("admins", "alice") - if err := s.DenyGroup("mnt/storage", "/admin", "admins"); err != nil { + if err := s.DenyGroup("mnt/storage", idxPath("/admin"), "admins"); err != nil { t.Errorf("DenyGroup failed: %v", err) } - if s.Permitted("mnt/storage", "/admin", "bob") == false { + if s.Permitted("mnt/storage", idxPath("/admin"), "bob") == false { t.Error("bob should be permitted (not in denied group)") } - if s.Permitted("mnt/storage", "/admin", "alice") { + if s.Permitted("mnt/storage", idxPath("/admin"), "alice") { t.Error("alice should not be permitted (in denied group)") } } @@ -132,18 +189,14 @@ func TestPermitted_GroupWhitelist(t *testing.T) { s, userStore := createTestStorage(t) createTestUser(t, userStore, "alice") createTestUser(t, userStore, "bob") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } _ = s.AddUserToGroup("vip", "bob") - if err := s.AllowGroup("mnt/storage", "/vip", "vip"); err != nil { + if err := s.AllowGroup("mnt/storage", idxPath("/vip"), "vip"); err != nil { t.Errorf("AllowGroup failed: %v", err) } - if !s.Permitted("mnt/storage", "/vip", "bob") { + if !s.Permitted("mnt/storage", idxPath("/vip"), "bob") { t.Error("bob should be permitted (in allowed group)") } - if !s.Permitted("mnt/storage", "/vip", "alice") { + if !s.Permitted("mnt/storage", idxPath("/vip"), "alice") { t.Error("alice should be permitted (default allow behavior when DenyByDefault=false)") } } @@ -151,11 +204,7 @@ func TestPermitted_GroupWhitelist(t *testing.T) { func TestPermitted_NoRule(t *testing.T) { setupTestSources() s, _ := createTestStorage(t) - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } - if !s.Permitted("mnt/storage", "/public", "anyone") { + if !s.Permitted("mnt/storage", idxPath("/public"), "anyone") { t.Error("anyone should be permitted if no rule exists") } } @@ -167,40 +216,34 @@ func TestPermitted_CombinedRules(t *testing.T) { createTestUser(t, userStore, "bob") createTestUser(t, userStore, "carol") createTestUser(t, userStore, "eve") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } - err = s.AddUserToGroup("vip", "bob") - if err != nil { + if err := s.AddUserToGroup("vip", "bob"); err != nil { t.Errorf("AddUserToGroup failed: %v", err) } - err = s.AddUserToGroup("admins", "alice") - if err != nil { + if err := s.AddUserToGroup("admins", "alice"); err != nil { t.Errorf("AddUserToGroup failed: %v", err) } - if err := s.DenyUser("mnt/storage", "/combo", "eve"); err != nil { + if err := s.DenyUser("mnt/storage", idxPath("/combo"), "eve"); err != nil { t.Errorf("DenyUser failed: %v", err) } - if err := s.AllowUser("mnt/storage", "/combo", "carol"); err != nil { + if err := s.AllowUser("mnt/storage", idxPath("/combo"), "carol"); err != nil { t.Errorf("AllowUser failed: %v", err) } - if err := s.DenyGroup("mnt/storage", "/combo", "admins"); err != nil { + if err := s.DenyGroup("mnt/storage", idxPath("/combo"), "admins"); err != nil { t.Errorf("DenyGroup failed: %v", err) } - if err := s.AllowGroup("mnt/storage", "/combo", "vip"); err != nil { + if err := s.AllowGroup("mnt/storage", idxPath("/combo"), "vip"); err != nil { t.Errorf("AllowGroup failed: %v", err) } - if s.Permitted("mnt/storage", "/combo", "eve") { + if s.Permitted("mnt/storage", idxPath("/combo"), "eve") { t.Error("eve should not be permitted (user denied)") } - if !s.Permitted("mnt/storage", "/combo", "carol") { + if !s.Permitted("mnt/storage", idxPath("/combo"), "carol") { t.Error("carol should be permitted (user allowed)") } - if s.Permitted("mnt/storage", "/combo", "alice") { + if s.Permitted("mnt/storage", idxPath("/combo"), "alice") { t.Error("alice should not be permitted (in group denied)") } - if !s.Permitted("mnt/storage", "/combo", "bob") { + if !s.Permitted("mnt/storage", idxPath("/combo"), "bob") { t.Error("bob should be permitted (in group allowed)") } } @@ -210,32 +253,28 @@ func TestPermitted_DenyAll(t *testing.T) { s, userStore := createTestStorage(t) createTestUser(t, userStore, "alice") createTestUser(t, userStore, "bob") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // Test DenyAll - if err = s.DenyAll("mnt/storage", "/private"); err != nil { + if err := s.DenyAll("mnt/storage", idxPath("/private")); err != nil { t.Errorf("DenyAll failed: %v", err) } - if s.Permitted("mnt/storage", "/private", "alice") { + if s.Permitted("mnt/storage", idxPath("/private"), "alice") { t.Error("alice should not be permitted (deny all)") } - if s.Permitted("mnt/storage", "/private", "bob") { + if s.Permitted("mnt/storage", idxPath("/private"), "bob") { t.Error("bob should not be permitted (deny all)") } // Test that Allow rule overrides DenyAll - if err = s.AllowUser("mnt/storage", "/private", "alice"); err != nil { + if err := s.AllowUser("mnt/storage", idxPath("/private"), "alice"); err != nil { t.Errorf("AllowUser failed: %v", err) } - if !s.Permitted("mnt/storage", "/private", "alice") { + if !s.Permitted("mnt/storage", idxPath("/private"), "alice") { t.Error("alice should be permitted (allow overrides deny all)") } // Test removing DenyAll - removed, err := s.RemoveDenyAll("mnt/storage", "/private") + removed, err := s.RemoveDenyAll("mnt/storage", idxPath("/private")) if err != nil { t.Errorf("RemoveDenyAll failed: %v", err) } @@ -244,12 +283,12 @@ func TestPermitted_DenyAll(t *testing.T) { } // After removing DenyAll, alice should be permitted due to the Allow rule - if !s.Permitted("mnt/storage", "/private", "alice") { + if !s.Permitted("mnt/storage", idxPath("/private"), "alice") { t.Error("alice should be permitted after removing deny all") } // Bob should be permitted because DenyByDefault=false makes allow lists additive (not exclusive) - if !s.Permitted("mnt/storage", "/private", "bob") { + if !s.Permitted("mnt/storage", idxPath("/private"), "bob") { t.Error("bob should be permitted after removing deny all (DenyByDefault=false makes allow lists additive)") } } @@ -262,10 +301,6 @@ func TestPermitted_DenyByDefault(t *testing.T) { s, userStore := createTestStorage(t) createTestUser(t, userStore, "alice") createTestUser(t, userStore, "bob") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // Setup test configuration with DenyByDefault enabled for one source originalSourceMap := settings.Config.Server.SourceMap @@ -292,64 +327,64 @@ func TestPermitted_DenyByDefault(t *testing.T) { } // Test DenyByDefault: When no rules exist, users should be denied - if s.Permitted("mnt/storage", "/private", "alice") { + if s.Permitted("mnt/storage", idxPath("/private"), "alice") { t.Error("alice should not be permitted (DenyByDefault is true and no rules exist)") } - if s.Permitted("mnt/storage", "/private", "bob") { + if s.Permitted("mnt/storage", idxPath("/private"), "bob") { t.Error("bob should not be permitted (DenyByDefault is true and no rules exist)") } // Test that explicit allow rules override DenyByDefault - if err := s.AllowUser("mnt/storage", "/allowed", "alice"); err != nil { + if err := s.AllowUser("mnt/storage", idxPath("/allowed"), "alice"); err != nil { t.Errorf("AllowUser failed: %v", err) } - if !s.Permitted("mnt/storage", "/allowed", "alice") { + if !s.Permitted("mnt/storage", idxPath("/allowed"), "alice") { t.Error("alice should be permitted (explicit allow rule overrides DenyByDefault)") } - if s.Permitted("mnt/storage", "/allowed", "bob") { + if s.Permitted("mnt/storage", idxPath("/allowed"), "bob") { t.Error("bob should not be permitted (not in allow list and DenyByDefault is true)") } // Test that explicit deny rules work with DenyByDefault - if err := s.DenyUser("mnt/storage", "/denied", "alice"); err != nil { + if err := s.DenyUser("mnt/storage", idxPath("/denied"), "alice"); err != nil { t.Errorf("DenyUser failed: %v", err) } - if s.Permitted("mnt/storage", "/denied", "alice") { + if s.Permitted("mnt/storage", idxPath("/denied"), "alice") { t.Error("alice should not be permitted (explicit deny rule)") } - if s.Permitted("mnt/storage", "/denied", "bob") { + if s.Permitted("mnt/storage", idxPath("/denied"), "bob") { t.Error("bob should not be permitted (DenyByDefault is true)") } // Test that DenyByDefault doesn't affect sources where it's disabled - if !s.Permitted("mnt/open", "/public", "alice") { + if !s.Permitted("mnt/open", idxPath("/public"), "alice") { t.Error("alice should be permitted in open source (DenyByDefault is false)") } - if !s.Permitted("mnt/open", "/public", "bob") { + if !s.Permitted("mnt/open", idxPath("/public"), "bob") { t.Error("bob should be permitted in open source (DenyByDefault is false)") } // Test recursive path checking with DenyByDefault // Allow alice at parent path, should work for child paths too - if err := s.AllowUser("mnt/storage", "/parent", "alice"); err != nil { + if err := s.AllowUser("mnt/storage", idxPath("/parent"), "alice"); err != nil { t.Errorf("AllowUser failed: %v", err) } - if !s.Permitted("mnt/storage", "/parent/child", "alice") { + if !s.Permitted("mnt/storage", idxPath("/parent/child"), "alice") { t.Error("alice should be permitted for child path (inherits from parent allow rule)") } - if s.Permitted("mnt/storage", "/parent/child", "bob") { + if s.Permitted("mnt/storage", idxPath("/parent/child"), "bob") { t.Error("bob should not be permitted for child path (DenyByDefault and not in allow list)") } // Test that group rules work with DenyByDefault _ = s.AddUserToGroup("vip", "alice") - if err := s.AllowGroup("mnt/storage", "/vip", "vip"); err != nil { + if err := s.AllowGroup("mnt/storage", idxPath("/vip"), "vip"); err != nil { t.Errorf("AllowGroup failed: %v", err) } - if !s.Permitted("mnt/storage", "/vip", "alice") { + if !s.Permitted("mnt/storage", idxPath("/vip"), "alice") { t.Error("alice should be permitted (in allowed group)") } - if s.Permitted("mnt/storage", "/vip", "bob") { + if s.Permitted("mnt/storage", idxPath("/vip"), "bob") { t.Error("bob should not be permitted (not in allowed group and DenyByDefault is true)") } } @@ -362,10 +397,6 @@ func TestPermitted_DenyByDefaultWithDenyAll(t *testing.T) { s, userStore := createTestStorage(t) createTestUser(t, userStore, "alice") createTestUser(t, userStore, "bob") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // Setup test configuration with DenyByDefault enabled originalSourceMap := settings.Config.Server.SourceMap @@ -385,26 +416,26 @@ func TestPermitted_DenyByDefaultWithDenyAll(t *testing.T) { } // Test that explicit DenyAll rule also works when DenyByDefault is enabled - if err = s.DenyAll("mnt/storage", "/restricted"); err != nil { + if err := s.DenyAll("mnt/storage", idxPath("/restricted")); err != nil { t.Errorf("DenyAll failed: %v", err) } - if s.Permitted("mnt/storage", "/restricted", "alice") { + if s.Permitted("mnt/storage", idxPath("/restricted"), "alice") { t.Error("alice should not be permitted (DenyAll rule)") } - if s.Permitted("mnt/storage", "/restricted", "bob") { + if s.Permitted("mnt/storage", idxPath("/restricted"), "bob") { t.Error("bob should not be permitted (DenyAll rule)") } // Test that Allow rule overrides DenyAll even with DenyByDefault - if err = s.AllowUser("mnt/storage", "/restricted", "alice"); err != nil { + if err := s.AllowUser("mnt/storage", idxPath("/restricted"), "alice"); err != nil { t.Errorf("AllowUser failed: %v", err) } - if !s.Permitted("mnt/storage", "/restricted", "alice") { + if !s.Permitted("mnt/storage", idxPath("/restricted"), "alice") { t.Error("alice should be permitted (allow overrides DenyAll)") } // Remove DenyAll and test that DenyByDefault takes effect - removed, err := s.RemoveDenyAll("mnt/storage", "/restricted") + removed, err := s.RemoveDenyAll("mnt/storage", idxPath("/restricted")) if err != nil { t.Errorf("RemoveDenyAll failed: %v", err) } @@ -413,11 +444,11 @@ func TestPermitted_DenyByDefaultWithDenyAll(t *testing.T) { } // After removing DenyAll, alice should be permitted due to Allow rule - if !s.Permitted("mnt/storage", "/restricted", "alice") { + if !s.Permitted("mnt/storage", idxPath("/restricted"), "alice") { t.Error("alice should be permitted after removing DenyAll (has allow rule)") } // Bob should not be permitted due to DenyByDefault - if s.Permitted("mnt/storage", "/restricted", "bob") { + if s.Permitted("mnt/storage", idxPath("/restricted"), "bob") { t.Error("bob should not be permitted (DenyByDefault is true and no allow rule)") } } @@ -429,10 +460,6 @@ func TestPermitted_DenyByDefault_AdminRootAccess(t *testing.T) { createTestUser(t, userStore, "admin") createTestUser(t, userStore, "graham") createTestUser(t, userStore, "bob") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // 2. Configure source with DenyByDefault: true originalSourceMap := settings.Config.Server.SourceMap @@ -451,47 +478,47 @@ func TestPermitted_DenyByDefault_AdminRootAccess(t *testing.T) { } // 3. Set up access rules - if err := s.AllowUser("mnt/secure", "/", "admin"); err != nil { + if err := s.AllowUser("mnt/secure", idxPath("/"), "admin"); err != nil { t.Fatalf("AllowUser for admin failed: %v", err) } - if err := s.AllowUser("mnt/secure", "/test", "graham"); err != nil { + if err := s.AllowUser("mnt/secure", idxPath("/test"), "graham"); err != nil { t.Fatalf("AllowUser for graham failed: %v", err) } // 4. Assertions // Admin checks - if !s.Permitted("mnt/secure", "/", "admin") { + if !s.Permitted("mnt/secure", idxPath("/"), "admin") { t.Error("admin should be permitted for /") } - if !s.Permitted("mnt/secure", "/test", "admin") { + if !s.Permitted("mnt/secure", idxPath("/test"), "admin") { t.Error("admin should be permitted for /test") } - if !s.Permitted("mnt/secure", "/test/sub", "admin") { + if !s.Permitted("mnt/secure", idxPath("/test/sub"), "admin") { t.Error("admin should be permitted for /test/sub (this is the bug)") } // Graham checks - if !s.Permitted("mnt/secure", "/test", "graham") { + if !s.Permitted("mnt/secure", idxPath("/test"), "graham") { t.Error("graham should be permitted for /test") } - if !s.Permitted("mnt/secure", "/test/sub", "graham") { + if !s.Permitted("mnt/secure", idxPath("/test/sub"), "graham") { t.Error("graham should be permitted for /test/sub") } - if s.Permitted("mnt/secure", "/", "graham") { + if s.Permitted("mnt/secure", idxPath("/"), "graham") { t.Error("graham should NOT be permitted for /") } - if s.Permitted("mnt/secure", "/anotherfolder", "graham") { + if s.Permitted("mnt/secure", idxPath("/anotherfolder"), "graham") { t.Error("graham should NOT be permitted for /anotherfolder") } // Bob checks (should have no access) - if s.Permitted("mnt/secure", "/", "bob") { + if s.Permitted("mnt/secure", idxPath("/"), "bob") { t.Error("bob should NOT be permitted for /") } - if s.Permitted("mnt/secure", "/test", "bob") { + if s.Permitted("mnt/secure", idxPath("/test"), "bob") { t.Error("bob should NOT be permitted for /test") } - if s.Permitted("mnt/secure", "/test/sub", "bob") { + if s.Permitted("mnt/secure", idxPath("/test/sub"), "bob") { t.Error("bob should NOT be permitted for /test/sub") } } @@ -505,11 +532,6 @@ func TestUserReportedBug(t *testing.T) { createTestUser(t, userStore, "testu1") createTestUser(t, userStore, "testu2") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } - // Setup test configuration for TEST_FOLDER source originalSourceMap := settings.Config.Server.SourceMap defer func() { @@ -529,28 +551,28 @@ func TestUserReportedBug(t *testing.T) { // SCENARIO 1: Set up initial access rules exactly as described // testu1 is denied access to USER2_folder - if err := s.DenyUser("TEST_FOLDER", "/USER2_folder", "testu1"); err != nil { + if err := s.DenyUser("TEST_FOLDER", idxPath("/USER2_folder"), "testu1"); err != nil { t.Fatalf("DenyUser failed for testu1->USER2_folder: %v", err) } // testu2 is denied access to USER1_folder - if err := s.DenyUser("TEST_FOLDER", "/USER1_folder", "testu2"); err != nil { + if err := s.DenyUser("TEST_FOLDER", idxPath("/USER1_folder"), "testu2"); err != nil { t.Fatalf("DenyUser failed for testu2->USER1_folder: %v", err) } // VERIFY SCENARIO 1: Initial permissions work correctly - if s.Permitted("TEST_FOLDER", "/USER2_folder", "testu1") { + if s.Permitted("TEST_FOLDER", idxPath("/USER2_folder"), "testu1") { t.Error("SCENARIO 1 FAILED: testu1 should NOT be permitted to access USER2_folder") } - if s.Permitted("TEST_FOLDER", "/USER1_folder", "testu2") { + if s.Permitted("TEST_FOLDER", idxPath("/USER1_folder"), "testu2") { t.Error("SCENARIO 1 FAILED: testu2 should NOT be permitted to access USER1_folder") } // Verify allowed access still works - if !s.Permitted("TEST_FOLDER", "/USER1_folder", "testu1") { + if !s.Permitted("TEST_FOLDER", idxPath("/USER1_folder"), "testu1") { t.Error("SCENARIO 1 FAILED: testu1 SHOULD be permitted to access USER1_folder") } - if !s.Permitted("TEST_FOLDER", "/USER2_folder", "testu2") { + if !s.Permitted("TEST_FOLDER", idxPath("/USER2_folder"), "testu2") { t.Error("SCENARIO 1 FAILED: testu2 SHOULD be permitted to access USER2_folder") } @@ -558,7 +580,7 @@ func TestUserReportedBug(t *testing.T) { // SCENARIO 2: The bug should NOT happen with proper access control // testu2 should still be denied access regardless of filesystem changes - if s.Permitted("TEST_FOLDER", "/USER1_folder", "testu2") { + if s.Permitted("TEST_FOLDER", idxPath("/USER1_folder"), "testu2") { t.Fatal("BUG REPRODUCED: testu2 can now access USER1_folder!") } @@ -571,10 +593,6 @@ func TestSubfolderAccessLogicBug(t *testing.T) { s, userStore := createTestStorage(t) createTestUser(t, userStore, "testu1") createTestUser(t, userStore, "testu2") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } originalSourceMap := settings.Config.Server.SourceMap defer func() { @@ -593,27 +611,27 @@ func TestSubfolderAccessLogicBug(t *testing.T) { } // Set up the exact scenario: testu2 denied access to /USER1_folder - if err := s.DenyUser("TEST_FOLDER", "/USER1_folder", "testu2"); err != nil { + if err := s.DenyUser("TEST_FOLDER", idxPath("/USER1_folder"), "testu2"); err != nil { t.Fatalf("DenyUser failed: %v", err) } // TEST THEORY: What happens when we check testu2's access to a SUBFOLDER that has no explicit rule? // Case 1: testu2 access to parent folder (should be denied) - if s.Permitted("TEST_FOLDER", "/USER1_folder", "testu2") { + if s.Permitted("TEST_FOLDER", idxPath("/USER1_folder"), "testu2") { t.Error("testu2 should be denied access to /USER1_folder") } // Case 2: testu2 access to subfolder that doesn't have explicit deny rule // With DenyByDefault=false, this should be ALLOWED! - if !s.Permitted("TEST_FOLDER", "/USER1_folder/test_folder", "testu2") { + if !s.Permitted("TEST_FOLDER", idxPath("/USER1_folder/test_folder"), "testu2") { t.Log("testu2 is denied access to /USER1_folder/test_folder (subfolder)") } else { t.Log("testu2 HAS access to /USER1_folder/test_folder (subfolder) - this might be the bug!") } // Case 3: Let's test with a deeply nested subfolder - if s.Permitted("TEST_FOLDER", "/USER1_folder/sub1/sub2/deep", "testu2") { + if s.Permitted("TEST_FOLDER", idxPath("/USER1_folder/sub1/sub2/deep"), "testu2") { t.Log("testu2 HAS access to deep subfolder - confirming the pattern") } @@ -630,10 +648,6 @@ func TestFileInfoBrowsingBug(t *testing.T) { s, userStore := createTestStorage(t) createTestUser(t, userStore, "testu1") createTestUser(t, userStore, "testu2") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } originalSourceMap := settings.Config.Server.SourceMap defer func() { @@ -652,7 +666,7 @@ func TestFileInfoBrowsingBug(t *testing.T) { } // Set up: testu2 denied access to /USER1_folder - if err := s.DenyUser("TEST_FOLDER", "/USER1_folder", "testu2"); err != nil { + if err := s.DenyUser("TEST_FOLDER", idxPath("/USER1_folder"), "testu2"); err != nil { t.Fatalf("DenyUser failed: %v", err) } @@ -660,8 +674,8 @@ func TestFileInfoBrowsingBug(t *testing.T) { // This tests the exact line: indexPath := info.Path + subFolder.Name // Scenario A: Subfolder should inherit deny rule from parent (correct behavior) - parentDenied := !s.Permitted("TEST_FOLDER", "/USER1_folder", "testu2") - subfolderDenied := !s.Permitted("TEST_FOLDER", "/USER1_folder/test_folder", "testu2") + parentDenied := !s.Permitted("TEST_FOLDER", idxPath("/USER1_folder"), "testu2") + subfolderDenied := !s.Permitted("TEST_FOLDER", idxPath("/USER1_folder/test_folder"), "testu2") t.Logf("Parent denied: %v, Subfolder denied: %v", parentDenied, subfolderDenied) @@ -681,7 +695,7 @@ func TestFileInfoBrowsingBug(t *testing.T) { } for _, testPath := range testPaths { - permitted := s.Permitted("TEST_FOLDER", testPath, "testu2") + permitted := s.Permitted("TEST_FOLDER", idxPath(testPath), "testu2") t.Logf("Path %q permitted for testu2: %v", testPath, permitted) // Paths without leading slash should ALWAYS be denied (security fix) @@ -708,10 +722,6 @@ func TestCacheClearingOnRuleDeletion(t *testing.T) { s, userStore := createTestStorage(t) createTestUser(t, userStore, "user1") createTestUser(t, userStore, "user2") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // Setup test sources originalSourceMap := settings.Config.Server.SourceMap @@ -731,12 +741,10 @@ func TestCacheClearingOnRuleDeletion(t *testing.T) { } // Step 1: Add some rules - err = s.DenyUser("test_source", "/path1/", "user1") - if err != nil { + if err := s.DenyUser("test_source", idxPath("/path1/"), "user1"); err != nil { t.Fatalf("Failed to deny user1: %v", err) } - err = s.AllowUser("test_source", "/path2/", "user2") - if err != nil { + if err := s.AllowUser("test_source", idxPath("/path2/"), "user2"); err != nil { t.Fatalf("Failed to allow user2: %v", err) } @@ -769,7 +777,7 @@ func TestCacheClearingOnRuleDeletion(t *testing.T) { } // Step 4: Delete a rule - removed, err := s.RemoveDenyUser("test_source", "/path1/", "user1") + removed, err := s.RemoveDenyUser("test_source", idxPath("/path1/"), "user1") if err != nil { t.Fatalf("Failed to remove deny user: %v", err) } @@ -795,7 +803,7 @@ func TestCacheClearingOnRuleDeletion(t *testing.T) { } // Step 6: Delete the remaining rule - removed, err = s.RemoveAllowUser("test_source", "/path2/", "user2") + removed, err = s.RemoveAllowUser("test_source", idxPath("/path2/"), "user2") if err != nil { t.Fatalf("Failed to remove allow user: %v", err) } @@ -825,10 +833,6 @@ func TestCacheClearingOnBulkRuleDeletion(t *testing.T) { s, userStore := createTestStorage(t) createTestUser(t, userStore, "user1") createTestUser(t, userStore, "user2") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // Setup test sources originalSourceMap := settings.Config.Server.SourceMap @@ -848,16 +852,13 @@ func TestCacheClearingOnBulkRuleDeletion(t *testing.T) { } // Step 1: Add multiple rules for user1 - err = s.DenyUser("test_source", "/path1", "user1") - if err != nil { + if err := s.DenyUser("test_source", idxPath("/path1"), "user1"); err != nil { t.Fatalf("Failed to deny user1 on path1: %v", err) } - err = s.AllowUser("test_source", "/path2", "user1") - if err != nil { + if err := s.AllowUser("test_source", idxPath("/path2"), "user1"); err != nil { t.Fatalf("Failed to allow user1 on path2: %v", err) } - err = s.DenyUser("test_source", "/path3", "user1") - if err != nil { + if err := s.DenyUser("test_source", idxPath("/path3"), "user1"); err != nil { t.Fatalf("Failed to deny user1 on path3: %v", err) } @@ -898,10 +899,6 @@ func TestNestedFolderAccessBug(t *testing.T) { s, userStore := createTestStorage(t) createTestUser(t, userStore, "user1") createTestUser(t, userStore, "user2") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // Setup test sources originalSourceMap := settings.Config.Server.SourceMap @@ -921,11 +918,11 @@ func TestNestedFolderAccessBug(t *testing.T) { } // Set up access rules as described - err = s.DenyUser("TEST", "/folder2", "user1") + err := s.DenyUser("TEST", idxPath("/folder2"), "user1") if err != nil { t.Fatalf("Failed to deny user1 access to folder2: %v", err) } - err = s.DenyUser("TEST", "/folder1", "user2") + err = s.DenyUser("TEST", idxPath("/folder1"), "user2") if err != nil { t.Fatalf("Failed to deny user2 access to folder1: %v", err) } @@ -934,7 +931,7 @@ func TestNestedFolderAccessBug(t *testing.T) { // Scenario 1: Direct folder access (should work correctly) t.Log("Testing user1 access to /folder2 (should be denied)") - result1 := s.Permitted("TEST", "/folder2", "user1") + result1 := s.Permitted("TEST", idxPath("/folder2"), "user1") if result1 { t.Error("user1 should be denied access to /folder2") } else { @@ -942,7 +939,7 @@ func TestNestedFolderAccessBug(t *testing.T) { } t.Log("Testing user2 access to /folder1 (should be denied)") - result2 := s.Permitted("TEST", "/folder1", "user2") + result2 := s.Permitted("TEST", idxPath("/folder1"), "user2") if result2 { t.Error("user2 should be denied access to /folder1") } else { @@ -950,7 +947,7 @@ func TestNestedFolderAccessBug(t *testing.T) { } t.Log("Testing user1 access to /folder1 (should be allowed)") - result3 := s.Permitted("TEST", "/folder1", "user1") + result3 := s.Permitted("TEST", idxPath("/folder1"), "user1") if !result3 { t.Error("user1 should be allowed access to /folder1") } else { @@ -958,7 +955,7 @@ func TestNestedFolderAccessBug(t *testing.T) { } t.Log("Testing user2 access to /folder2 (should be allowed)") - result4 := s.Permitted("TEST", "/folder2", "user2") + result4 := s.Permitted("TEST", idxPath("/folder2"), "user2") if !result4 { t.Error("user2 should be allowed access to /folder2") } else { @@ -969,7 +966,7 @@ func TestNestedFolderAccessBug(t *testing.T) { // Scenario 2: Nested folder access (this is where the bug occurs) t.Log("Testing user1 access to /folder2/another_folder2 (should be denied due to parent rule)") - result5 := s.Permitted("TEST", "/folder2/another_folder2", "user1") + result5 := s.Permitted("TEST", idxPath("/folder2/another_folder2"), "user1") if result5 { t.Error("BUG: user1 should be denied access to /folder2/another_folder2 (parent folder is denied)") } else { @@ -977,7 +974,7 @@ func TestNestedFolderAccessBug(t *testing.T) { } t.Log("Testing user2 access to /folder1/another_folder1 (should be denied due to parent rule)") - result6 := s.Permitted("TEST", "/folder1/another_folder1", "user2") + result6 := s.Permitted("TEST", idxPath("/folder1/another_folder1"), "user2") if result6 { t.Error("BUG: user2 should be denied access to /folder1/another_folder1 (parent folder is denied)") } else { @@ -985,7 +982,7 @@ func TestNestedFolderAccessBug(t *testing.T) { } t.Log("Testing user1 access to /folder1/another_folder1 (should be allowed)") - result7 := s.Permitted("TEST", "/folder1/another_folder1", "user1") + result7 := s.Permitted("TEST", idxPath("/folder1/another_folder1"), "user1") if !result7 { t.Error("user1 should be allowed access to /folder1/another_folder1") } else { @@ -993,7 +990,7 @@ func TestNestedFolderAccessBug(t *testing.T) { } t.Log("Testing user2 access to /folder2/another_folder2 (should be allowed)") - result8 := s.Permitted("TEST", "/folder2/another_folder2", "user2") + result8 := s.Permitted("TEST", idxPath("/folder2/another_folder2"), "user2") if !result8 { t.Error("user2 should be allowed access to /folder2/another_folder2") } else { @@ -1002,7 +999,7 @@ func TestNestedFolderAccessBug(t *testing.T) { // Test deeper nesting t.Log("Testing deeper nesting: user1 access to /folder2/another_folder2/deep_folder (should be denied)") - result9 := s.Permitted("TEST", "/folder2/another_folder2/deep_folder", "user1") + result9 := s.Permitted("TEST", idxPath("/folder2/another_folder2/deep_folder"), "user1") if result9 { t.Error("BUG: user1 should be denied access to /folder2/another_folder2/deep_folder (parent folder is denied)") } else { @@ -1012,13 +1009,13 @@ func TestNestedFolderAccessBug(t *testing.T) { t.Log("=== SCENARIO 3: Specific allow rule on subfolder ===") // Add a specific allow rule for user1 on a subfolder of folder2 - err = s.AllowUser("TEST", "/folder2/allowed_subfolder", "user1") + err = s.AllowUser("TEST", idxPath("/folder2/allowed_subfolder"), "user1") if err != nil { t.Fatalf("Failed to allow user1 access to /folder2/allowed_subfolder: %v", err) } t.Log("Testing user1 access to /folder2/allowed_subfolder (should be allowed due to specific allow rule)") - result10 := s.Permitted("TEST", "/folder2/allowed_subfolder", "user1") + result10 := s.Permitted("TEST", idxPath("/folder2/allowed_subfolder"), "user1") if !result10 { t.Error("user1 should be allowed access to /folder2/allowed_subfolder (has specific allow rule)") } else { @@ -1026,7 +1023,7 @@ func TestNestedFolderAccessBug(t *testing.T) { } t.Log("Testing user1 access to /folder2/denied_subfolder (should be denied - no specific allow rule)") - result11 := s.Permitted("TEST", "/folder2/denied_subfolder", "user1") + result11 := s.Permitted("TEST", idxPath("/folder2/denied_subfolder"), "user1") if result11 { t.Error("user1 should be denied access to /folder2/denied_subfolder (no specific allow rule)") } else { @@ -1042,8 +1039,18 @@ func TestFolderVisibilityBugReproduction(t *testing.T) { s, userStorage := createTestStorage(t) // Create test users first - user1 := &users.User{NonAdminEditable: users.NonAdminEditable{Password: "test"}, Username: "user1"} - user2 := &users.User{NonAdminEditable: users.NonAdminEditable{Password: "test"}, Username: "user2"} + user1 := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "user1", + NonAdminEditable: users.NonAdminEditable{Password: "test"}, + }, + } + user2 := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "user2", + NonAdminEditable: users.NonAdminEditable{Password: "test"}, + }, + } err := userStorage.Save(user1, false, false) if err != nil { t.Fatalf("failed to create user1: %v", err) @@ -1071,11 +1078,11 @@ func TestFolderVisibilityBugReproduction(t *testing.T) { } // Set up the exact access rules from the user's report - err = s.DenyUser("TEST", "/test/folder1", "user2") + err = s.DenyUser("TEST", idxPath("/test/folder1"), "user2") if err != nil { t.Fatalf("failed to deny user2 access to /test/folder1: %v", err) } - err = s.DenyUser("TEST", "/test/folder2", "user1") + err = s.DenyUser("TEST", idxPath("/test/folder2"), "user1") if err != nil { t.Fatalf("failed to deny user1 access to /test/folder2: %v", err) } @@ -1084,7 +1091,7 @@ func TestFolderVisibilityBugReproduction(t *testing.T) { // This simulates what happens when the frontend calls the API // First, verify that user1 cannot access /test/folder2 directly - permitted := s.Permitted("TEST", "/test/folder2", "user1") + permitted := s.Permitted("TEST", idxPath("/test/folder2"), "user1") if permitted { t.Error("user1 should be denied access to /test/folder2") } else { @@ -1111,7 +1118,7 @@ func TestFolderVisibilityBugReproduction(t *testing.T) { // These should fail (buggy behavior) - but they actually fail due to missing source config for i, path := range buggyPaths { - permitted := s.Permitted("TEST", path, "user1") + permitted := s.Permitted("TEST", idxPath(path), "user1") // Note: These actually return false because there's no source config, not because of the path bug t.Logf("Buggy path %d: %s -> %v (would be true if source config existed)", i+1, path, permitted) } @@ -1124,7 +1131,7 @@ func TestFolderVisibilityBugReproduction(t *testing.T) { // These should fail (correct behavior) for i, path := range correctPaths { - permitted := s.Permitted("TEST", path, "user1") + permitted := s.Permitted("TEST", idxPath(path), "user1") if permitted { t.Errorf("Correct path construction should deny access: %s", path) } @@ -1136,7 +1143,7 @@ func TestFolderVisibilityBugReproduction(t *testing.T) { hasPermittedPaths := false for _, folder := range mockFolders { correctPath := "/test/folder2/" + folder.Name - if s.Permitted("TEST", correctPath, "user1") { + if s.Permitted("TEST", idxPath(correctPath), "user1") { hasPermittedPaths = true t.Logf("Found permitted subfolder: %s", folder.Name) } @@ -1157,8 +1164,18 @@ func TestHasAnyVisibleItems(t *testing.T) { s, userStorage := createTestStorage(t) // Create test users - user1 := &users.User{NonAdminEditable: users.NonAdminEditable{Password: "test"}, Username: "user1"} - user2 := &users.User{NonAdminEditable: users.NonAdminEditable{Password: "test"}, Username: "user2"} + user1 := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "user1", + NonAdminEditable: users.NonAdminEditable{Password: "test"}, + }, + } + user2 := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "user2", + NonAdminEditable: users.NonAdminEditable{Password: "test"}, + }, + } err := userStorage.Save(user1, false, false) if err != nil { t.Fatalf("failed to create user1: %v", err) @@ -1186,11 +1203,11 @@ func TestHasAnyVisibleItems(t *testing.T) { } // Set up access rules - err = s.DenyUser("TEST", "/folder1", "user1") + err = s.DenyUser("TEST", idxPath("/folder1"), "user1") if err != nil { t.Fatalf("failed to deny user1 access to /folder1: %v", err) } - err = s.AllowUser("TEST", "/folder1/allowed_subfolder", "user1") + err = s.AllowUser("TEST", idxPath("/folder1/allowed_subfolder"), "user1") if err != nil { t.Fatalf("failed to allow user1 access to /folder1/allowed_subfolder: %v", err) } @@ -1199,19 +1216,19 @@ func TestHasAnyVisibleItems(t *testing.T) { itemNames := []string{"allowed_subfolder", "denied_subfolder", "another_denied_folder"} // Test for user1 (denied access to parent folder but has access to one subfolder) - hasVisible := s.HasAnyVisibleItems("TEST", "/folder1", itemNames, "user1") + hasVisible := s.HasAnyVisibleItems("TEST", idxPath("/folder1"), itemNames, "user1") if !hasVisible { t.Error("Expected user1 to have access to at least one item in /folder1") } // Test for user2 (no restrictions, but no source config so will be denied) - hasVisible2 := s.HasAnyVisibleItems("TEST", "/folder1", itemNames, "user2") + hasVisible2 := s.HasAnyVisibleItems("TEST", idxPath("/folder1"), itemNames, "user2") // Note: user2 will be denied due to missing source config, not due to access rules t.Logf("user2 access to items in /folder1: %v (denied due to missing source config)", hasVisible2) // Test with no accessible items deniedItemNames := []string{"denied_subfolder", "another_denied_folder"} - hasVisible3 := s.HasAnyVisibleItems("TEST", "/folder1", deniedItemNames, "user1") + hasVisible3 := s.HasAnyVisibleItems("TEST", idxPath("/folder1"), deniedItemNames, "user1") if hasVisible3 { t.Error("Expected user1 to NOT have access to denied items in /folder1") } @@ -1224,28 +1241,24 @@ func TestRemoveUserCascade_OnlyRemovesSpecificList(t *testing.T) { setupTestSources() s, userStore := createTestStorage(t) createTestUser(t, userStore, "alice") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } - + var err error // Set up rules: alice has both allow and deny rules on different paths - if err = s.AllowUser("mnt/storage", "/docs/", "alice"); err != nil { + if err = s.AllowUser("mnt/storage", idxPath("/docs/"), "alice"); err != nil { t.Fatalf("AllowUser failed: %v", err) } - if err = s.AllowUser("mnt/storage", "/docs/public/", "alice"); err != nil { + if err = s.AllowUser("mnt/storage", idxPath("/docs/public/"), "alice"); err != nil { t.Fatalf("AllowUser failed: %v", err) } - if err = s.DenyUser("mnt/storage", "/docs/", "alice"); err != nil { + if err = s.DenyUser("mnt/storage", idxPath("/docs/"), "alice"); err != nil { t.Fatalf("DenyUser failed: %v", err) } - if err = s.DenyUser("mnt/storage", "/docs/private/", "alice"); err != nil { + if err = s.DenyUser("mnt/storage", idxPath("/docs/private/"), "alice"); err != nil { t.Fatalf("DenyUser failed: %v", err) } // Cascade delete only allow rules var count int - count, err = s.RemoveUserCascade("mnt/storage", "/docs/", "alice", true) + count, err = s.RemoveUserCascade("mnt/storage", idxPath("/docs/"), "alice", true) if err != nil { t.Fatalf("RemoveUserCascade failed: %v", err) } @@ -1254,21 +1267,21 @@ func TestRemoveUserCascade_OnlyRemovesSpecificList(t *testing.T) { } // Verify allow rules are gone - rule, ok := s.GetFrontendRules("mnt/storage", "/docs/") + rule, ok := s.GetFrontendRules("mnt/storage", idxPath("/docs/")) if ok && len(rule.Allow.Users) != 0 { t.Error("Allow rule should be removed from /docs/") } - rule, ok = s.GetFrontendRules("mnt/storage", "/docs/public/") + rule, ok = s.GetFrontendRules("mnt/storage", idxPath("/docs/public/")) if ok && len(rule.Allow.Users) != 0 { t.Error("Allow rule should be removed from /docs/public/") } // Verify deny rules are still present - rule, ok = s.GetFrontendRules("mnt/storage", "/docs/") + rule, ok = s.GetFrontendRules("mnt/storage", idxPath("/docs/")) if !ok || len(rule.Deny.Users) == 0 { t.Error("Deny rule should still exist on /docs/") } - rule, ok = s.GetFrontendRules("mnt/storage", "/docs/private/") + rule, ok = s.GetFrontendRules("mnt/storage", idxPath("/docs/private/")) if !ok || len(rule.Deny.Users) == 0 { t.Error("Deny rule should still exist on /docs/private/") } @@ -1281,28 +1294,25 @@ func TestRemoveUserCascade_DenyRules(t *testing.T) { setupTestSources() s, userStore := createTestStorage(t) createTestUser(t, userStore, "bob") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } + var err error // Set up both allow and deny rules - if err = s.AllowUser("mnt/storage", "/projects/", "bob"); err != nil { + if err = s.AllowUser("mnt/storage", idxPath("/projects/"), "bob"); err != nil { t.Fatalf("AllowUser failed: %v", err) } - if err = s.AllowUser("mnt/storage", "/projects/team/", "bob"); err != nil { + if err = s.AllowUser("mnt/storage", idxPath("/projects/team/"), "bob"); err != nil { t.Fatalf("AllowUser failed: %v", err) } - if err = s.DenyUser("mnt/storage", "/projects/", "bob"); err != nil { + if err = s.DenyUser("mnt/storage", idxPath("/projects/"), "bob"); err != nil { t.Fatalf("DenyUser failed: %v", err) } - if err = s.DenyUser("mnt/storage", "/projects/secret/", "bob"); err != nil { + if err = s.DenyUser("mnt/storage", idxPath("/projects/secret/"), "bob"); err != nil { t.Fatalf("DenyUser failed: %v", err) } // Cascade delete only deny rules var count int - count, err = s.RemoveUserCascade("mnt/storage", "/projects/", "bob", false) + count, err = s.RemoveUserCascade("mnt/storage", idxPath("/projects/"), "bob", false) if err != nil { t.Fatalf("RemoveUserCascade failed: %v", err) } @@ -1311,21 +1321,21 @@ func TestRemoveUserCascade_DenyRules(t *testing.T) { } // Verify deny rules are gone - rule, ok := s.GetFrontendRules("mnt/storage", "/projects/") + rule, ok := s.GetFrontendRules("mnt/storage", idxPath("/projects/")) if !ok || len(rule.Deny.Users) != 0 { t.Error("Deny rule should be removed from /projects/") } - rule, ok = s.GetFrontendRules("mnt/storage", "/projects/secret/") + rule, ok = s.GetFrontendRules("mnt/storage", idxPath("/projects/secret/")) if ok && len(rule.Deny.Users) != 0 { t.Error("Deny rule should be removed from /projects/secret/") } // Verify allow rules are still present - rule, ok = s.GetFrontendRules("mnt/storage", "/projects/") + rule, ok = s.GetFrontendRules("mnt/storage", idxPath("/projects/")) if !ok || len(rule.Allow.Users) == 0 { t.Error("Allow rule should still exist on /projects/") } - rule, ok = s.GetFrontendRules("mnt/storage", "/projects/team/") + rule, ok = s.GetFrontendRules("mnt/storage", idxPath("/projects/team/")) if !ok || len(rule.Allow.Users) == 0 { t.Error("Allow rule should still exist on /projects/team/") } @@ -1338,10 +1348,6 @@ func TestRemoveUserCascade_MultipleSubpaths(t *testing.T) { setupTestSources() s, userStore := createTestStorage(t) createTestUser(t, userStore, "carol") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // Set up a deep hierarchy of allow rules paths := []string{ @@ -1356,14 +1362,15 @@ func TestRemoveUserCascade_MultipleSubpaths(t *testing.T) { } for _, path := range paths { - if err = s.AllowUser("mnt/storage", path, "carol"); err != nil { + if err := s.AllowUser("mnt/storage", idxPath(path), "carol"); err != nil { t.Fatalf("AllowUser failed for %s: %v", path, err) } } // Cascade delete from /data/2024/ should remove all 2024 subpaths var count int - count, err = s.RemoveUserCascade("mnt/storage", "/data/2024/", "carol", true) + var err error + count, err = s.RemoveUserCascade("mnt/storage", idxPath("/data/2024/"), "carol", true) if err != nil { t.Fatalf("RemoveUserCascade failed: %v", err) } @@ -1373,18 +1380,18 @@ func TestRemoveUserCascade_MultipleSubpaths(t *testing.T) { // Verify 2024 paths are gone for _, path := range []string{"/data/2024/", "/data/2024/q1/", "/data/2024/q1/jan/", "/data/2024/q1/feb/", "/data/2024/q2/", "/data/2024/q2/apr/"} { - rule, ok := s.GetFrontendRules("mnt/storage", path) + rule, ok := s.GetFrontendRules("mnt/storage", idxPath(path)) if ok && len(rule.Allow.Users) > 0 { t.Errorf("Rule should be removed from %s", path) } } // Verify other paths still exist - rule, ok := s.GetFrontendRules("mnt/storage", "/data/") + rule, ok := s.GetFrontendRules("mnt/storage", idxPath("/data/")) if !ok || len(rule.Allow.Users) == 0 { t.Error("Rule should still exist on /data/") } - rule, ok = s.GetFrontendRules("mnt/storage", "/data/2025/") + rule, ok = s.GetFrontendRules("mnt/storage", idxPath("/data/2025/")) if !ok || len(rule.Allow.Users) == 0 { t.Error("Rule should still exist on /data/2025/") } @@ -1397,32 +1404,28 @@ func TestRemoveGroupCascade_OnlyRemovesSpecificList(t *testing.T) { setupTestSources() s, userStore := createTestStorage(t) createTestUser(t, userStore, "alice") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // Create a group - if err = s.AddUserToGroup("editors", "alice"); err != nil { + if err := s.AddUserToGroup("editors", "alice"); err != nil { t.Fatalf("AddUserToGroup failed: %v", err) } // Set up both allow and deny rules for the group - if err = s.AllowGroup("mnt/storage", "/content/", "editors"); err != nil { + if err := s.AllowGroup("mnt/storage", idxPath("/content/"), "editors"); err != nil { t.Fatalf("AllowGroup failed: %v", err) } - if err = s.AllowGroup("mnt/storage", "/content/articles/", "editors"); err != nil { + if err := s.AllowGroup("mnt/storage", idxPath("/content/articles/"), "editors"); err != nil { t.Fatalf("AllowGroup failed: %v", err) } - if err = s.DenyGroup("mnt/storage", "/content/", "editors"); err != nil { + if err := s.DenyGroup("mnt/storage", idxPath("/content/"), "editors"); err != nil { t.Fatalf("DenyGroup failed: %v", err) } - if err = s.DenyGroup("mnt/storage", "/content/drafts/", "editors"); err != nil { + if err := s.DenyGroup("mnt/storage", idxPath("/content/drafts/"), "editors"); err != nil { t.Fatalf("DenyGroup failed: %v", err) } // Cascade delete only allow rules - count, err := s.RemoveGroupCascade("mnt/storage", "/content/", "editors", true) + count, err := s.RemoveGroupCascade("mnt/storage", idxPath("/content/"), "editors", true) if err != nil { t.Fatalf("RemoveGroupCascade failed: %v", err) } @@ -1431,17 +1434,17 @@ func TestRemoveGroupCascade_OnlyRemovesSpecificList(t *testing.T) { } // Verify allow rules are gone - rule, ok := s.GetFrontendRules("mnt/storage", "/content/") + rule, ok := s.GetFrontendRules("mnt/storage", idxPath("/content/")) if !ok || len(rule.Allow.Groups) != 0 { t.Error("Allow rule should be removed from /content/") } // Verify deny rules are still present - rule, ok = s.GetFrontendRules("mnt/storage", "/content/") + rule, ok = s.GetFrontendRules("mnt/storage", idxPath("/content/")) if !ok || len(rule.Deny.Groups) == 0 { t.Error("Deny rule should still exist on /content/") } - rule, ok = s.GetFrontendRules("mnt/storage", "/content/drafts/") + rule, ok = s.GetFrontendRules("mnt/storage", idxPath("/content/drafts/")) if !ok || len(rule.Deny.Groups) == 0 { t.Error("Deny rule should still exist on /content/drafts/") } @@ -1454,33 +1457,30 @@ func TestRemoveGroupCascade_DenyRules(t *testing.T) { setupTestSources() s, userStore := createTestStorage(t) createTestUser(t, userStore, "alice") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // Create a group - if err = s.AddUserToGroup("contractors", "alice"); err != nil { + err := s.AddUserToGroup("contractors", "alice") + if err != nil { t.Fatalf("AddUserToGroup failed: %v", err) } // Set up both allow and deny rules for the group - if err = s.AllowGroup("mnt/storage", "/work/", "contractors"); err != nil { + if err = s.AllowGroup("mnt/storage", idxPath("/work/"), "contractors"); err != nil { t.Fatalf("AllowGroup failed: %v", err) } - if err = s.AllowGroup("mnt/storage", "/work/public/", "contractors"); err != nil { + if err = s.AllowGroup("mnt/storage", idxPath("/work/public/"), "contractors"); err != nil { t.Fatalf("AllowGroup failed: %v", err) } - if err = s.DenyGroup("mnt/storage", "/work/", "contractors"); err != nil { + if err = s.DenyGroup("mnt/storage", idxPath("/work/"), "contractors"); err != nil { t.Fatalf("DenyGroup failed: %v", err) } - if err = s.DenyGroup("mnt/storage", "/work/confidential/", "contractors"); err != nil { + if err = s.DenyGroup("mnt/storage", idxPath("/work/confidential/"), "contractors"); err != nil { t.Fatalf("DenyGroup failed: %v", err) } // Cascade delete only deny rules var count int - count, err = s.RemoveGroupCascade("mnt/storage", "/work/", "contractors", false) + count, err = s.RemoveGroupCascade("mnt/storage", idxPath("/work/"), "contractors", false) if err != nil { t.Fatalf("RemoveGroupCascade failed: %v", err) } @@ -1489,21 +1489,21 @@ func TestRemoveGroupCascade_DenyRules(t *testing.T) { } // Verify deny rules are gone - rule, ok := s.GetFrontendRules("mnt/storage", "/work/") + rule, ok := s.GetFrontendRules("mnt/storage", idxPath("/work/")) if ok && len(rule.Deny.Groups) != 0 { t.Error("Deny rule should be removed from /work/") } - rule, ok = s.GetFrontendRules("mnt/storage", "/work/confidential/") + rule, ok = s.GetFrontendRules("mnt/storage", idxPath("/work/confidential/")) if ok && len(rule.Deny.Groups) != 0 { t.Error("Deny rule should be removed from /work/confidential/") } // Verify allow rules are still present - rule, ok = s.GetFrontendRules("mnt/storage", "/work/") + rule, ok = s.GetFrontendRules("mnt/storage", idxPath("/work/")) if !ok || len(rule.Allow.Groups) == 0 { t.Error("Allow rule should still exist on /work/") } - rule, ok = s.GetFrontendRules("mnt/storage", "/work/public/") + rule, ok = s.GetFrontendRules("mnt/storage", idxPath("/work/public/")) if !ok || len(rule.Allow.Groups) == 0 { t.Error("Allow rule should still exist on /work/public/") } @@ -1516,14 +1516,11 @@ func TestRemoveUserCascade_EmptyResult(t *testing.T) { setupTestSources() s, userStore := createTestStorage(t) createTestUser(t, userStore, "dave") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // Try to cascade delete when no rules exist var count int - count, err = s.RemoveUserCascade("mnt/storage", "/nonexistent/", "dave", true) + var err error + count, err = s.RemoveUserCascade("mnt/storage", idxPath("/nonexistent/"), "dave", true) if err != nil { t.Fatalf("RemoveUserCascade should not error on nonexistent rules: %v", err) } @@ -1539,19 +1536,16 @@ func TestRemoveUserCascade_ExactPathOnly(t *testing.T) { setupTestSources() s, userStore := createTestStorage(t) createTestUser(t, userStore, "eve") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // Add rule only on exact path, no subpaths - if err = s.AllowUser("mnt/storage", "/single/", "eve"); err != nil { + err := s.AllowUser("mnt/storage", idxPath("/single/"), "eve") + if err != nil { t.Fatalf("AllowUser failed: %v", err) } // Cascade delete should remove the exact path rule var count int - count, err = s.RemoveUserCascade("mnt/storage", "/single/", "eve", true) + count, err = s.RemoveUserCascade("mnt/storage", idxPath("/single/"), "eve", true) if err != nil { t.Fatalf("RemoveUserCascade failed: %v", err) } @@ -1560,7 +1554,7 @@ func TestRemoveUserCascade_ExactPathOnly(t *testing.T) { } // Verify rule is gone - rule, ok := s.GetFrontendRules("mnt/storage", "/single/") + rule, ok := s.GetFrontendRules("mnt/storage", idxPath("/single/")) if ok && len(rule.Allow.Users) > 0 { t.Error("Rule should be removed from /single/") } @@ -1573,24 +1567,20 @@ func TestRemoveUserCascade_DoesNotAffectParentPaths(t *testing.T) { setupTestSources() s, userStore := createTestStorage(t) createTestUser(t, userStore, "frank") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // Set up rules on parent and child paths - if err = s.AllowUser("mnt/storage", "/parent/", "frank"); err != nil { + if err := s.AllowUser("mnt/storage", idxPath("/parent/"), "frank"); err != nil { t.Fatalf("AllowUser failed: %v", err) } - if err = s.AllowUser("mnt/storage", "/parent/child/", "frank"); err != nil { + if err := s.AllowUser("mnt/storage", idxPath("/parent/child/"), "frank"); err != nil { t.Fatalf("AllowUser failed: %v", err) } - if err = s.AllowUser("mnt/storage", "/parent/child/grandchild/", "frank"); err != nil { + if err := s.AllowUser("mnt/storage", idxPath("/parent/child/grandchild/"), "frank"); err != nil { t.Fatalf("AllowUser failed: %v", err) } // Cascade delete from child path - count, err := s.RemoveUserCascade("mnt/storage", "/parent/child/", "frank", true) + count, err := s.RemoveUserCascade("mnt/storage", idxPath("/parent/child/"), "frank", true) if err != nil { t.Fatalf("RemoveUserCascade failed: %v", err) } @@ -1599,13 +1589,13 @@ func TestRemoveUserCascade_DoesNotAffectParentPaths(t *testing.T) { } // Verify parent rule still exists - rule, ok := s.GetFrontendRules("mnt/storage", "/parent/") + rule, ok := s.GetFrontendRules("mnt/storage", idxPath("/parent/")) if !ok || len(rule.Allow.Users) == 0 { t.Error("Parent rule should still exist") } // Verify child rules are gone - rule, ok = s.GetFrontendRules("mnt/storage", "/parent/child/") + rule, ok = s.GetFrontendRules("mnt/storage", idxPath("/parent/child/")) if ok && len(rule.Allow.Users) > 0 { t.Error("Child rule should be removed") } @@ -1618,16 +1608,12 @@ func TestRemoveUserCascade_CleanupEmptyRules(t *testing.T) { setupTestSources() s, userStore := createTestStorage(t) createTestUser(t, userStore, "grace") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // Add only allow rule (no deny rules) - if err = s.AllowUser("mnt/storage", "/temp/", "grace"); err != nil { + if err := s.AllowUser("mnt/storage", idxPath("/temp/"), "grace"); err != nil { t.Fatalf("AllowUser failed: %v", err) } - if err = s.AllowUser("mnt/storage", "/temp/files/", "grace"); err != nil { + if err := s.AllowUser("mnt/storage", idxPath("/temp/files/"), "grace"); err != nil { t.Fatalf("AllowUser failed: %v", err) } @@ -1642,7 +1628,7 @@ func TestRemoveUserCascade_CleanupEmptyRules(t *testing.T) { // Cascade delete - should remove rules and cleanup empty rule objects var count int - count, err = s.RemoveUserCascade("mnt/storage", "/temp/", "grace", true) + count, err = s.RemoveUserCascade("mnt/storage", idxPath("/temp/"), "grace", true) if err != nil { t.Fatalf("RemoveUserCascade failed: %v", err) } @@ -1671,28 +1657,25 @@ func TestRemoveUserCascade_MixedUsers(t *testing.T) { s, userStore := createTestStorage(t) createTestUser(t, userStore, "henry") createTestUser(t, userStore, "iris") - err := s.LoadFromDB() - if err != nil && err != storm.ErrNotFound { - t.Errorf("unexpected error loading from DB: %v", err) - } // Add rules for both users on same paths - if err = s.AllowUser("mnt/storage", "/shared/", "henry"); err != nil { + err := s.AllowUser("mnt/storage", idxPath("/shared/"), "henry") + if err != nil { t.Fatalf("AllowUser failed: %v", err) } - if err = s.AllowUser("mnt/storage", "/shared/", "iris"); err != nil { + if err = s.AllowUser("mnt/storage", idxPath("/shared/"), "iris"); err != nil { t.Fatalf("AllowUser failed: %v", err) } - if err = s.AllowUser("mnt/storage", "/shared/docs/", "henry"); err != nil { + if err = s.AllowUser("mnt/storage", idxPath("/shared/docs/"), "henry"); err != nil { t.Fatalf("AllowUser failed: %v", err) } - if err = s.AllowUser("mnt/storage", "/shared/docs/", "iris"); err != nil { + if err = s.AllowUser("mnt/storage", idxPath("/shared/docs/"), "iris"); err != nil { t.Fatalf("AllowUser failed: %v", err) } // Cascade delete only henry's rules var count int - count, err = s.RemoveUserCascade("mnt/storage", "/shared/", "henry", true) + count, err = s.RemoveUserCascade("mnt/storage", idxPath("/shared/"), "henry", true) if err != nil { t.Fatalf("RemoveUserCascade failed: %v", err) } @@ -1701,7 +1684,7 @@ func TestRemoveUserCascade_MixedUsers(t *testing.T) { } // Verify henry's rules are gone - rule, ok := s.GetFrontendRules("mnt/storage", "/shared/") + rule, ok := s.GetFrontendRules("mnt/storage", idxPath("/shared/")) if !ok { t.Fatal("Rule should still exist (iris's rule)") } @@ -1728,3 +1711,4 @@ func TestRemoveUserCascade_MixedUsers(t *testing.T) { t.Log("✓ Cascade delete only affects the specified user") } + diff --git a/backend/database/access/helper.go b/backend/internal/database/access/helper.go similarity index 73% rename from backend/database/access/helper.go rename to backend/internal/database/access/helper.go index ff578ca49c..01882f8a3c 100644 --- a/backend/database/access/helper.go +++ b/backend/internal/database/access/helper.go @@ -1,10 +1,10 @@ package access import ( - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/indexing" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" ) func (s *Storage) CheckChildItemAccess(response *iteminfo.FileInfo, index *indexing.Index, username string) error { @@ -22,7 +22,6 @@ func (s *Storage) CheckChildItemAccess(response *iteminfo.FileInfo, index *index // response is an ExtendedFileInfo which represents a directory (has Folders and Files) parentPath := index.MakeIndexPath(response.Path, true) - // Check if user has access to any items if !s.HasAnyVisibleItems(index.Path, parentPath, allItemNames, username) && len(allItemNames) > 0 { return errors.ErrAccessDenied } @@ -37,16 +36,13 @@ func (s *Storage) CheckChildItemAccess(response *iteminfo.FileInfo, index *index // Check each subfolder for access permissions for _, folder := range originalFolders { - indexPath := parentPath + folder.Name - if s.Permitted(index.Path, indexPath, username) { + if s.Permitted(index.Path, parentPath.Join(folder.Name, true), username) { response.Folders = append(response.Folders, folder) } } - // Check each subfile for access permissions for _, file := range originalFiles { - indexPath := parentPath + file.Name - if s.Permitted(index.Path, indexPath, username) { + if s.Permitted(index.Path, parentPath.Join(file.Name, false), username) { response.Files = append(response.Files, file) } } diff --git a/backend/internal/database/access/migration_test.go b/backend/internal/database/access/migration_test.go new file mode 100644 index 0000000000..aef692be13 --- /dev/null +++ b/backend/internal/database/access/migration_test.go @@ -0,0 +1,29 @@ +package access + +import ( + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" +) + +func TestRemoveRuleByPathKey_exactLegacyKey(t *testing.T) { + s := NewStorage(nil) + sourcePath := "test_source" + legacyKey := "/legacy" + + s.AllRules[sourcePath] = RuleMap{ + legacyKey: { + Allow: RuleSet{Users: StringSet{"alice": {}}}, + Deny: RuleSet{Users: make(StringSet), Groups: make(StringSet)}, + }, + } + + s.RemoveRuleByPathKey(sourcePath, legacyKey) + + if _, ok := s.AllRules[sourcePath][legacyKey]; ok { + t.Fatal("legacy key should be removed") + } + if _, ok := s.AllRules[sourcePath][utils.AddTrailingSlashIfNotExists(legacyKey)]; ok { + t.Fatal("normalized key should not remain when only legacy existed") + } +} diff --git a/backend/internal/database/access/path.go b/backend/internal/database/access/path.go new file mode 100644 index 0000000000..8a556a43b0 --- /dev/null +++ b/backend/internal/database/access/path.go @@ -0,0 +1,13 @@ +package access + +import "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + +// ruleKey returns the canonical storage key for access rules (directory form with trailing slash). +func ruleKey(path utils.IndexPath) string { + return path.RuleKey() +} + +// checkPath normalizes an index path for permission checks (directory form for hierarchy walk). +func checkPath(path utils.IndexPath) utils.IndexPath { + return path.AsDirectory() +} diff --git a/backend/internal/database/activity/activity.go b/backend/internal/database/activity/activity.go new file mode 100644 index 0000000000..576555d63c --- /dev/null +++ b/backend/internal/database/activity/activity.go @@ -0,0 +1,231 @@ +package activity + +import "encoding/json" + +// Details holds metadata stored as JSON in the database. +type Details struct { + TargetUsername string `json:"targetUsername,omitempty"` + Source string `json:"source,omitempty"` + Path string `json:"path,omitempty"` + TargetPath string `json:"targetPath,omitempty"` + ShareHash string `json:"shareHash,omitempty"` + ShareOwnerUserID uint64 `json:"shareOwnerUserId,omitempty"` + Scopes []ScopeDetail `json:"scopes,omitempty"` + TokenName string `json:"tokenName,omitempty"` // actor token; API exposes on FrontendEntry only + AffectedTokenName string `json:"affectedTokenName,omitempty"` // token created/deleted (actor token is TokenName) + AuthMethod string `json:"authMethod,omitempty"` // actor auth; API exposes on FrontendEntry only + LoginMethod string `json:"loginMethod,omitempty"` + PasskeyName string `json:"passkeyName,omitempty"` + UpdatedFields []string `json:"updatedFields,omitempty"` + Changes []FieldChange `json:"changes,omitempty"` + Cached bool `json:"cached,omitempty"` + FileCount int `json:"fileCount,omitempty"` + Paths []string `json:"paths,omitempty"` + Truncated bool `json:"truncated,omitempty"` + Bytes int64 `json:"bytes,omitempty"` + DurationMs int64 `json:"durationMs,omitempty"` + Error string `json:"error,omitempty"` +} + +// ScopeDetail is a user source + path scope for admin/user mutation events. +type ScopeDetail struct { + Source string `json:"source"` + Path string `json:"path"` +} + +// FieldChange records one attribute that changed on user/share update events. +type FieldChange struct { + Field string `json:"field"` + From string `json:"from,omitempty"` + To string `json:"to"` +} + +// FrontendDetails is the admin-only detail payload exposed to the API. +type FrontendDetails struct { + TargetUsername string `json:"targetUsername,omitempty"` + Source string `json:"source,omitempty"` + Path string `json:"path,omitempty"` + TargetPath string `json:"targetPath,omitempty"` + Scopes []ScopeDetail `json:"scopes,omitempty"` + AffectedTokenName string `json:"affectedTokenName,omitempty"` + LoginMethod string `json:"loginMethod,omitempty"` + PasskeyName string `json:"passkeyName,omitempty"` + UpdatedFields []string `json:"updatedFields,omitempty"` + Changes []FieldChange `json:"changes,omitempty"` + Cached bool `json:"cached,omitempty"` + FileCount int `json:"fileCount,omitempty"` + Paths []string `json:"paths,omitempty"` + Truncated bool `json:"truncated,omitempty"` + Bytes int64 `json:"bytes,omitempty"` + DurationMs int64 `json:"durationMs,omitempty"` + Error string `json:"error,omitempty"` +} + +const maxDetailPaths = 50 + +// MaxSplitActivityRecords caps how many individual rows are recorded from one multi-path action. +const MaxSplitActivityRecords = maxDetailPaths + +// CapPaths limits paths stored in details to avoid oversized JSON blobs. +func (d *Details) CapPaths() { + if len(d.Paths) <= maxDetailPaths { + return + } + d.Paths = d.Paths[:maxDetailPaths] + d.Truncated = true +} + +// ToFrontendDetails maps persisted details to the API shape (drops internal fields). +func (d Details) ToFrontendDetails() FrontendDetails { + return FrontendDetails{ + TargetUsername: d.TargetUsername, + Source: d.Source, + Path: d.Path, + TargetPath: d.TargetPath, + Scopes: d.Scopes, + AffectedTokenName: d.AffectedTokenName, + LoginMethod: d.LoginMethod, + PasskeyName: d.PasskeyName, + UpdatedFields: d.UpdatedFields, + Changes: append([]FieldChange(nil), d.Changes...), + Cached: d.Cached, + FileCount: d.FileCount, + Paths: append([]string(nil), d.Paths...), + Truncated: d.Truncated, + Bytes: d.Bytes, + DurationMs: d.DurationMs, + Error: d.Error, + } +} + +// Entry is a single activity log row (buffered before persistence). +type Entry struct { + ID int64 `json:"id,omitempty"` + CreatedAt int64 `json:"createdAt"` + UserID uint64 `json:"userId"` + EventType EventType `json:"eventType"` + Source string `json:"source,omitempty"` + Path string `json:"path,omitempty"` + TargetPath string `json:"targetPath,omitempty"` + IPAddress string `json:"ipAddress,omitempty"` + Details Details `json:"details"` +} + +// FrontendEntry is the narrowed API response (like FrontendUser on User). +type FrontendEntry struct { + ID int64 `json:"id"` + CreatedAt int64 `json:"createdAt"` + Username string `json:"username"` + EventType EventType `json:"eventType"` + Source string `json:"source,omitempty"` + Path string `json:"path,omitempty"` + TargetPath string `json:"targetPath,omitempty"` + ShareHash string `json:"shareHash,omitempty"` + TokenName string `json:"tokenName,omitempty"` + AuthMethod string `json:"authMethod,omitempty"` + IPAddress string `json:"ipAddress,omitempty"` + Details FrontendDetails `json:"details,omitempty"` +} + +// PrepForFrontend converts a persisted entry into the API response shape. +// actorUsername is the display name for the user who performed the action (from UserID). +func (e Entry) PrepForFrontend(actorUsername string) FrontendEntry { + fe := FrontendEntry{ + ID: e.ID, + CreatedAt: e.CreatedAt, + Username: actorUsername, + EventType: e.EventType, + Source: e.Source, + Path: e.Path, + TargetPath: e.TargetPath, + IPAddress: e.IPAddress, + Details: e.Details.ToFrontendDetails(), + } + if fe.Source == "" { + fe.Source = e.Details.Source + } + if fe.Path == "" { + fe.Path = e.Details.Path + } + if fe.TargetPath == "" { + fe.TargetPath = e.Details.TargetPath + } + fe.ShareHash = e.Details.ShareHash + if fe.TokenName == "" { + fe.TokenName = e.Details.TokenName + } + if fe.AuthMethod == "" { + fe.AuthMethod = e.Details.AuthMethod + } + return fe +} + +// ListResponse is the paginated activity list API response. +type ListResponse struct { + Items []FrontendEntry `json:"items"` + Total int `json:"total"` + Page int `json:"page"` + Limit int `json:"limit"` + TotalPages int `json:"totalPages"` +} + +// StatsBucket is one aggregated chart data point. +type StatsBucket struct { + Bucket int64 `json:"bucket"` + SeriesKey string `json:"seriesKey"` + SeriesLabel string `json:"seriesLabel,omitempty"` + Count int `json:"count"` + EventType string `json:"eventType,omitempty"` +} + +// StatsResponse is the aggregated grouped activity API response. +type StatsResponse struct { + Buckets []StatsBucket `json:"buckets"` +} + +// GroupedResponse is an alias for chart/grouped endpoints. +type GroupedResponse = StatsResponse + +// ListRow is a persisted entry with the actor username resolved from SQL. +type ListRow struct { + Entry + ActorUsername string +} + +// QueryFilter scopes activity queries. +type QueryFilter struct { + From int64 + To int64 + UserID uint64 + UserFilter bool // when true, filter by UserID (including 0 for anonymous) + Scope string // all, files, shares — drives share-scope download matching + EventTypes []EventType + Source string + PathPrefix string + PathGlob string + ShareHash string + ShareOwnerUserID uint64 + ShareOwnerFilter bool // restrict to shares owned by ShareOwnerUserID + Page int + Limit int + Interval string // minute, hour, day, none — time bucket on the X-axis + SplitBy string // eventType, user, none — series dimension + GroupBy string // maps to Interval when Interval is empty +} + +// MarshalDetailsJSON serializes details for SQLite storage. +func MarshalDetailsJSON(d Details) (string, error) { + b, err := json.Marshal(d) + if err != nil { + return "{}", err + } + return string(b), nil +} + +// UnmarshalDetailsJSON parses details from SQLite. +func UnmarshalDetailsJSON(raw string, d *Details) error { + if raw == "" { + return nil + } + return json.Unmarshal([]byte(raw), d) +} diff --git a/backend/internal/database/activity/activity_test.go b/backend/internal/database/activity/activity_test.go new file mode 100644 index 0000000000..47f8dfa39a --- /dev/null +++ b/backend/internal/database/activity/activity_test.go @@ -0,0 +1,83 @@ +package activity + +import ( + "encoding/json" + "testing" +) + +func TestPrepForFrontendPromotesAuthWithoutDuplicatingDetails(t *testing.T) { + entry := Entry{ + ID: 1, + CreatedAt: 1700000000, + EventType: EventUserUpdate, + Details: Details{ + TargetUsername: "admin", + TokenName: "unique", + AuthMethod: "apiKey", + Changes: []FieldChange{{ + Field: "quickDownload", + From: "true", + To: "false", + }}, + }, + } + + fe := entry.PrepForFrontend("admin") + if fe.TokenName != "unique" { + t.Fatalf("TokenName = %q, want unique", fe.TokenName) + } + if fe.AuthMethod != "apiKey" { + t.Fatalf("AuthMethod = %q, want apiKey", fe.AuthMethod) + } + detailsJSON, err := json.Marshal(fe.Details) + if err != nil { + t.Fatal(err) + } + var details map[string]any + if err := json.Unmarshal(detailsJSON, &details); err != nil { + t.Fatal(err) + } + if _, ok := details["tokenName"]; ok { + t.Fatalf("details must not include tokenName: %s", detailsJSON) + } + if _, ok := details["authMethod"]; ok { + t.Fatalf("details must not include authMethod: %s", detailsJSON) + } + if len(fe.Details.Changes) != 1 { + t.Fatalf("expected 1 change in details, got %d", len(fe.Details.Changes)) + } +} + +func TestPrepForFrontendPromotesShareHashWithoutDuplicatingDetails(t *testing.T) { + entry := Entry{ + ID: 2, + CreatedAt: 1700000001, + EventType: EventShareUpdate, + Details: Details{ + Source: "default", + Path: "/shared", + ShareHash: "abc123", + Changes: []FieldChange{{ + Field: "title", + From: "before", + To: "after", + }}, + }, + } + + fe := entry.PrepForFrontend("owner") + if fe.ShareHash != "abc123" { + t.Fatalf("ShareHash = %q, want abc123", fe.ShareHash) + } + detailsJSON, err := json.Marshal(fe.Details) + if err != nil { + t.Fatal(err) + } + var details map[string]any + if err := json.Unmarshal(detailsJSON, &details); err != nil { + t.Fatal(err) + } + if _, ok := details["shareHash"]; ok { + t.Fatalf("details must not include shareHash: %s", detailsJSON) + } +} diff --git a/backend/internal/database/activity/event_type.go b/backend/internal/database/activity/event_type.go new file mode 100644 index 0000000000..951020dad2 --- /dev/null +++ b/backend/internal/database/activity/event_type.go @@ -0,0 +1,174 @@ +package activity + +import "fmt" + +// EventType identifies a semantic user activity for audit logging. +type EventType string + +const ( + EventDownload EventType = "download" + EventMove EventType = "move" + EventCopy EventType = "copy" + EventRename EventType = "rename" + EventUpload EventType = "upload" + EventDelete EventType = "delete" + EventBulkDelete EventType = "bulkDelete" + EventArchive EventType = "archive" + EventUnarchive EventType = "unarchive" + EventShareCreate EventType = "shareCreate" + EventShareUpdate EventType = "shareUpdate" + EventShareDelete EventType = "shareDelete" + EventUserCreate EventType = "userCreate" + EventUserUpdate EventType = "userUpdate" + EventUserDelete EventType = "userDelete" + EventAccessUpdate EventType = "accessUpdate" + EventAccessCreate EventType = "accessCreate" + EventAccessDelete EventType = "accessDelete" + EventLogin EventType = "login" + EventLogout EventType = "logout" + EventSignup EventType = "signup" + EventPasskeyRegister EventType = "passkeyRegister" + EventPasskeyDelete EventType = "passkeyDelete" + EventTokenCreate EventType = "tokenCreate" + EventTokenDelete EventType = "tokenDelete" + EventDuplicateFinder EventType = "duplicateFinder" +) + +// AllEventTypes lists every defined event type for validation and UI filters. +var AllEventTypes = []EventType{ + EventDownload, + EventMove, + EventCopy, + EventRename, + EventUpload, + EventDelete, + EventBulkDelete, + EventArchive, + EventUnarchive, + EventShareCreate, + EventShareUpdate, + EventShareDelete, + EventUserCreate, + EventUserUpdate, + EventUserDelete, + EventAccessUpdate, + EventAccessCreate, + EventAccessDelete, + EventLogin, + EventLogout, + EventSignup, + EventPasskeyRegister, + EventPasskeyDelete, + EventTokenCreate, + EventTokenDelete, + EventDuplicateFinder, +} + +// FileEventTypes are file and path operations (scope=files). +var FileEventTypes = []EventType{ + EventDownload, + EventMove, + EventCopy, + EventRename, + EventUpload, + EventDelete, + EventBulkDelete, + EventArchive, + EventUnarchive, +} + +// AccessEventTypes are access rule mutations (scope=access). +var AccessEventTypes = []EventType{ + EventAccessCreate, + EventAccessUpdate, + EventAccessDelete, +} + +// ShareEventTypes are share lifecycle events (scope=shares). Share downloads are +// EventDownload rows with a non-empty details.shareHash. +var ShareEventTypes = []EventType{ + EventShareCreate, + EventShareUpdate, + EventShareDelete, +} + +// ShareScopeEventTypes are valid explicit event-type filters when scope=shares. +var ShareScopeEventTypes = append(append([]EventType{}, ShareEventTypes...), EventDownload) + +// ResolveScopeEventTypes returns the effective event-type filter for a scope. +func ResolveScopeEventTypes(scope string, explicit []EventType) ([]EventType, error) { + var allowed []EventType + switch scope { + case "", "all": + if len(explicit) == 0 { + return nil, nil + } + return explicit, nil + case "files": + allowed = FileEventTypes + case "access": + allowed = AccessEventTypes + case "shares": + if len(explicit) == 0 { + return nil, nil + } + allowed = ShareScopeEventTypes + default: + return nil, fmt.Errorf("scope must be all, files, access, or shares") + } + if len(explicit) == 0 { + return allowed, nil + } + return intersectEventTypes(explicit, allowed), nil +} + +func intersectEventTypes(requested, allowed []EventType) []EventType { + allowedSet := make(map[EventType]struct{}, len(allowed)) + for _, et := range allowed { + allowedSet[et] = struct{}{} + } + var out []EventType + for _, et := range requested { + if _, ok := allowedSet[et]; ok { + out = append(out, et) + } + } + return out +} + +// Valid reports whether e is a known event type constant. +func (e EventType) Valid() bool { + switch e { + case EventDownload, EventMove, EventCopy, EventRename, + EventUpload, EventDelete, EventBulkDelete, + EventArchive, EventUnarchive, + EventShareCreate, EventShareUpdate, EventShareDelete, + EventUserCreate, EventUserUpdate, EventUserDelete, EventAccessUpdate, EventAccessCreate, EventAccessDelete, + EventLogin, EventLogout, EventSignup, + EventPasskeyRegister, EventPasskeyDelete, + EventTokenCreate, EventTokenDelete, + EventDuplicateFinder: + return true + default: + return false + } +} + +// String returns the wire/database representation. +func (e EventType) String() string { + return string(e) +} + +// EventTypeFromAction maps a resource PATCH action string to an event type. +func EventTypeFromAction(action string) (EventType, bool) { + switch action { + case "copy": + return EventCopy, true + case "move": + return EventMove, true + case "rename": + return EventRename, true + default: + return "", false + } +} diff --git a/backend/internal/database/activity/event_type_test.go b/backend/internal/database/activity/event_type_test.go new file mode 100644 index 0000000000..9974df9c05 --- /dev/null +++ b/backend/internal/database/activity/event_type_test.go @@ -0,0 +1,75 @@ +package activity + +import "testing" + +func TestEventTypeValid(t *testing.T) { + for _, et := range AllEventTypes { + if !et.Valid() { + t.Errorf("expected %q to be valid", et) + } + } + if EventType("notARealEvent").Valid() { + t.Error("expected unknown event type to be invalid") + } +} + +func TestResolveScopeEventTypes(t *testing.T) { + got, err := ResolveScopeEventTypes("shares", nil) + if err != nil || got != nil { + t.Fatalf("shares default: got %v, %v; want nil, nil", got, err) + } + got, err = ResolveScopeEventTypes("shares", []EventType{EventDownload}) + if err != nil { + t.Fatal(err) + } + if len(got) != 1 || got[0] != EventDownload { + t.Fatalf("shares explicit download: got %v", got) + } + got, err = ResolveScopeEventTypes("files", nil) + if err != nil { + t.Fatal(err) + } + if len(got) != len(FileEventTypes) { + t.Fatalf("files default: got %d types, want %d", len(got), len(FileEventTypes)) + } + got, err = ResolveScopeEventTypes("access", nil) + if err != nil { + t.Fatal(err) + } + if len(got) != len(AccessEventTypes) { + t.Fatalf("access default: got %d types, want %d", len(got), len(AccessEventTypes)) + } + for _, et := range AccessEventTypes { + if !containsEventType(got, et) { + t.Fatalf("access default missing %q in %v", et, got) + } + } +} + +func containsEventType(list []EventType, target EventType) bool { + for _, et := range list { + if et == target { + return true + } + } + return false +} + +func TestEventTypeFromAction(t *testing.T) { + cases := []struct { + action string + want EventType + ok bool + }{ + {"copy", EventCopy, true}, + {"move", EventMove, true}, + {"rename", EventRename, true}, + {"delete", "", false}, + } + for _, tc := range cases { + got, ok := EventTypeFromAction(tc.action) + if ok != tc.ok || got != tc.want { + t.Errorf("EventTypeFromAction(%q) = (%q, %v), want (%q, %v)", tc.action, got, ok, tc.want, tc.ok) + } + } +} diff --git a/backend/internal/database/activity/paths.go b/backend/internal/database/activity/paths.go new file mode 100644 index 0000000000..2db2569838 --- /dev/null +++ b/backend/internal/database/activity/paths.go @@ -0,0 +1,103 @@ +package activity + +import ( + "strings" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// TrimPathForUserScope removes a user's index scope prefix from a stored path. +// If the path is outside the scope prefix it is returned unchanged. +func TrimPathForUserScope(path, userScope string) string { + if userScope == "/" || userScope == "" { + return path + } + + path = strings.TrimSpace(path) + scope := strings.TrimRight(strings.TrimSpace(userScope), "/") + if path == "" || scope == "" || scope == "/" { + return path + } + if !strings.HasPrefix(scope, "/") { + scope = "/" + scope + } + rest, ok := strings.CutPrefix(path, scope) + if !ok { + return path + } + if rest == "" { + return "/" + } + return "/" + strings.TrimPrefix(rest, "/") +} + +func scopeForUserSource(user *users.User, source string) (string, bool) { + if user == nil || source == "" { + return "", false + } + if scope, err := user.GetScopeForSourceName(source); err == nil { + return scope, true + } + if scope, err := user.GetScopeForSourcePath(source); err == nil { + return scope, true + } + return "", false +} + +func trimPathForUser(user *users.User, source, path string) string { + if path == "" { + return path + } + if source == "" { + return path + } + scope, ok := scopeForUserSource(user, source) + if !ok { + return path + } + return TrimPathForUserScope(path, scope) +} + +// TrimPathsForUser strips the user's per-source scope prefix from file paths in the API entry. +// User scope settings in Details.Scopes are left unchanged. +func (fe *FrontendEntry) TrimPathsForUser(user *users.User) { + if user == nil || user.ID == 0 { + return + } + + source := fe.Source + if source == "" { + source = fe.Details.Source + } + + if fe.Path != "" { + fe.Path = trimPathForUser(user, source, fe.Path) + } + if fe.TargetPath != "" { + fe.TargetPath = trimPathForUser(user, source, fe.TargetPath) + } + + if fe.Details.Path != "" { + detailsSource := fe.Details.Source + if detailsSource == "" { + detailsSource = source + } + fe.Details.Path = trimPathForUser(user, detailsSource, fe.Details.Path) + } + if fe.Details.TargetPath != "" { + detailsSource := fe.Details.Source + if detailsSource == "" { + detailsSource = source + } + fe.Details.TargetPath = trimPathForUser(user, detailsSource, fe.Details.TargetPath) + } + if len(fe.Details.Paths) > 0 { + detailsSource := fe.Details.Source + if detailsSource == "" { + detailsSource = source + } + for i, p := range fe.Details.Paths { + fe.Details.Paths[i] = trimPathForUser(user, detailsSource, p) + } + } +} diff --git a/backend/internal/database/activity/paths_test.go b/backend/internal/database/activity/paths_test.go new file mode 100644 index 0000000000..9e3e7b3974 --- /dev/null +++ b/backend/internal/database/activity/paths_test.go @@ -0,0 +1,52 @@ +package activity + +import ( + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func TestTrimPathForUserScope(t *testing.T) { + tests := []struct { + path string + scope string + want string + }{ + {path: "/users/alice/docs/file.txt", scope: "/users/alice", want: "/docs/file.txt"}, + {path: "/source/users/graham/path/to/file", scope: "/source/users/graham", want: "/path/to/file"}, + {path: "/users/alice", scope: "/users/alice", want: "/"}, + {path: "/docs/file.txt", scope: "/users/alice", want: "/docs/file.txt"}, + {path: "/docs/file.txt", scope: "/", want: "/docs/file.txt"}, + {path: "", scope: "/users/alice", want: ""}, + } + for _, tc := range tests { + got := TrimPathForUserScope(tc.path, tc.scope) + if got != tc.want { + t.Fatalf("TrimPathForUserScope(%q, %q) = %q, want %q", tc.path, tc.scope, got, tc.want) + } + } +} + +func TestFrontendEntryTrimPathsForUser(t *testing.T) { + actor := &users.User{ + ID: 1, + BackendScopes: []users.BackendScope{ + {Path: "/data", Scope: "/users/alice"}, + }, + } + fe := FrontendEntry{ + Source: "/data", + Path: "/users/alice/docs/readme.txt", + Details: FrontendDetails{ + Source: "/data", + Paths: []string{"/users/alice/docs/a.txt", "/users/alice/docs/b.txt"}, + }, + } + fe.TrimPathsForUser(actor) + if fe.Path != "/docs/readme.txt" { + t.Fatalf("Path = %q, want /docs/readme.txt", fe.Path) + } + if fe.Details.Paths[0] != "/docs/a.txt" || fe.Details.Paths[1] != "/docs/b.txt" { + t.Fatalf("Details.Paths = %#v", fe.Details.Paths) + } +} diff --git a/backend/database/crud/crud.go b/backend/internal/database/crud/crud.go similarity index 100% rename from backend/database/crud/crud.go rename to backend/internal/database/crud/crud.go diff --git a/backend/database/dbindex/indexing.go b/backend/internal/database/dbindex/indexing.go similarity index 100% rename from backend/database/dbindex/indexing.go rename to backend/internal/database/dbindex/indexing.go diff --git a/backend/database/dbindex/storage.go b/backend/internal/database/dbindex/storage.go similarity index 97% rename from backend/database/dbindex/storage.go rename to backend/internal/database/dbindex/storage.go index d7966e177c..1eafa5b672 100644 --- a/backend/database/dbindex/storage.go +++ b/backend/internal/database/dbindex/storage.go @@ -3,8 +3,8 @@ package dbindex import ( "sync" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/database/crud" + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/crud" ) // StorageBackend is the interface to implement for an indexing storage. diff --git a/backend/database/share/extended.go b/backend/internal/database/share/extended.go similarity index 65% rename from backend/database/share/extended.go rename to backend/internal/database/share/extended.go index 19099b006e..aef98f3272 100644 --- a/backend/database/share/extended.go +++ b/backend/internal/database/share/extended.go @@ -7,13 +7,13 @@ import ( "path/filepath" "strings" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" ) // IsSingleFileShare determines if this share is for a single file (not a directory). // It checks both the file extension and filesystem to determine if the path points to a file. -func (l *Link) IsSingleFileShare() bool { +func (l *Share) IsSingleFileShare() bool { if l.Path == "" { return false } @@ -30,12 +30,12 @@ func (l *Link) IsSingleFileShare() bool { } // isFileOnFilesystem checks if the path exists and is a file on the filesystem -func (l *Link) isFileOnFilesystem() bool { +func (l *Share) isFileOnFilesystem() bool { // Construct the full path using Source and Path fullPath := l.Path - if l.Source != "" { - // If Source is provided, it might be a relative path from the source - fullPath = filepath.Join(l.Source, l.Path) + if l.SourcePath != "" { + // If SourcePath is provided, it might be a relative path from the source + fullPath = filepath.Join(l.SourcePath, l.Path) } info, err := os.Stat(fullPath) @@ -48,12 +48,12 @@ func (l *Link) isFileOnFilesystem() bool { } // isDirectoryOnFilesystem checks if the path exists and is a directory on the filesystem -func (l *Link) isDirectoryOnFilesystem() bool { +func (l *Share) isDirectoryOnFilesystem() bool { // Construct the full path using Source and Path fullPath := l.Path - if l.Source != "" { - // If Source is provided, it might be a relative path from the source - fullPath = filepath.Join(l.Source, l.Path) + if l.SourcePath != "" { + // If SourcePath is provided, it might be a relative path from the source + fullPath = filepath.Join(l.SourcePath, l.Path) } info, err := os.Stat(fullPath) @@ -66,7 +66,7 @@ func (l *Link) isDirectoryOnFilesystem() bool { } // IsExpired checks if the share has expired based on the Expire timestamp -func (l *Link) IsExpired() bool { +func (l *Share) IsExpired() bool { if l.Expire == 0 { return false // No expiration set } @@ -76,17 +76,17 @@ func (l *Link) IsExpired() bool { } // HasPassword checks if the share is password protected -func (l *Link) HasPassword() bool { +func (l *Share) HasPassword() bool { return l.PasswordHash != "" } // IsPermanent checks if the share is permanent (no expiration) -func (l *Link) IsPermanent() bool { +func (l *Share) IsPermanent() bool { return l.Expire == 0 } // GetFileExtension returns the file extension of the shared file -func (l *Link) GetFileExtension() string { +func (l *Share) GetFileExtension() string { if l.Path == "" { return "" } @@ -94,7 +94,7 @@ func (l *Link) GetFileExtension() string { } // GetFileName returns just the filename (without path) of the shared item -func (l *Link) GetFileName() string { +func (l *Share) GetFileName() string { if l.Path == "" { return "" } @@ -102,18 +102,16 @@ func (l *Link) GetFileName() string { } // InitUserDownloads initializes the user downloads map if needed -func (l *Link) InitUserDownloads() { - l.Mu.Lock() - defer l.Mu.Unlock() +func (l *Share) InitUserDownloads() { + // Note: This should be called within a lock at the state package level if l.UserDownloads == nil { l.UserDownloads = make(map[string]int) } } // IncrementUserDownload increments the download count for a specific user -func (l *Link) IncrementUserDownload(username string) { - l.Mu.Lock() - defer l.Mu.Unlock() +func (l *Share) IncrementUserDownload(username string) { + // Note: This should be called within a lock at the state package level if l.UserDownloads == nil { l.UserDownloads = make(map[string]int) } @@ -121,9 +119,8 @@ func (l *Link) IncrementUserDownload(username string) { } // GetUserDownloadCount returns the download count for a specific user -func (l *Link) GetUserDownloadCount(username string) int { - l.Mu.Lock() - defer l.Mu.Unlock() +func (l *Share) GetUserDownloadCount(username string) int { + // Note: This should be called within a lock at the state package level if l.UserDownloads == nil { return 0 } @@ -131,15 +128,14 @@ func (l *Link) GetUserDownloadCount(username string) int { } // ResetDownloadCounts resets both global and per-user download counts -func (l *Link) ResetDownloadCounts() { - l.Mu.Lock() - defer l.Mu.Unlock() +func (l *Share) ResetDownloadCounts() { + // Note: This should be called within a lock at the state package level l.Downloads = 0 l.UserDownloads = make(map[string]int) } // HasReachedUserLimit checks if a user has reached their download limit -func (l *Link) HasReachedUserLimit(username string) bool { +func (l *Share) HasReachedUserLimit(username string) bool { if !l.PerUserDownloadLimit || l.DownloadsLimit == 0 { return false } @@ -147,19 +143,31 @@ func (l *Link) HasReachedUserLimit(username string) bool { return count >= l.DownloadsLimit } -func (l *Link) GetSourceName() string { - sourceInfo, ok := settings.Config.Server.SourceMap[l.Source] - if !ok { - return "" +func resolveSource(sourcePath string) (*settings.Source, bool) { + if sourceInfo, ok := settings.Config.Server.SourceMap[sourcePath]; ok { + return sourceInfo, true } - return sourceInfo.Name + if sourceInfo, ok := settings.Config.Server.NameToSource[sourcePath]; ok { + return sourceInfo, true + } + return nil, false } -func (l *Link) UserCanEdit(user *users.User) bool { - return l.UserID == user.ID || user.Permissions.Admin +func (l *Share) GetSourceName() string { + if sourceInfo, ok := resolveSource(l.SourcePath); ok { + return sourceInfo.Name + } + return "" } -func (l *Link) SourceURL(user *users.User) string { +func (l *Share) UserCanEdit(user *users.User) bool { + if user.Permissions.Admin { + return true + } + return l.UserID != 0 && l.UserID == user.ID +} + +func (l *Share) SourceURL(user *users.User) string { sourceName := l.GetSourceName() // get user scope path from share userScope, err := user.GetScopeForSourceName(sourceName) @@ -173,23 +181,23 @@ func (l *Link) SourceURL(user *users.User) string { return "/" + filepath.Join("files", sourceName, scopedPath) } -func (l *Link) BannerURL() string { +func (l *Share) BannerURL() string { _, _, err := l.GetShareImagePartsHelper(true) if err == nil { - return fmt.Sprintf("%s%spublic/api/share/image?banner=true&hash=%s", settings.Config.Server.ExternalUrl, settings.Config.Server.BaseURL, l.Hash) + return fmt.Sprintf("%s%spublic/api/share/image?banner=true&hash=%s", settings.Config.Http.ExternalUrl, settings.Config.Http.BaseURL, l.Hash) } return l.Banner } -func (l *Link) FaviconURL() string { +func (l *Share) FaviconURL() string { _, _, err := l.GetShareImagePartsHelper(false) if err == nil { - return fmt.Sprintf("%s%spublic/api/share/image?favicon=true&hash=%s", settings.Config.Server.ExternalUrl, settings.Config.Server.BaseURL, l.Hash) + return fmt.Sprintf("%s%spublic/api/share/image?favicon=true&hash=%s", settings.Config.Http.ExternalUrl, settings.Config.Http.BaseURL, l.Hash) } return l.Favicon } -func (l *Link) GetShareImagePartsHelper(isBanner bool) (string, string, error) { +func (l *Share) GetShareImagePartsHelper(isBanner bool) (string, string, error) { // Get the asset query string from share var assetQueryString string if isBanner { diff --git a/backend/internal/database/share/frontend.go b/backend/internal/database/share/frontend.go new file mode 100644 index 0000000000..23f612c6cf --- /dev/null +++ b/backend/internal/database/share/frontend.go @@ -0,0 +1,92 @@ +package share + +import ( + "fmt" + "net/http" + "net/url" + "path/filepath" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// PrepForFrontend builds API-safe ShareFrontend copies (never exposes backend Share fields). +// publicHost and publicScheme must be set when building share/download URLs (resolved in web/proxy.go). +// ownerLookup resolves share owner usernames from stable user ids; may be nil. +func PrepForFrontend(viewer *users.User, r *http.Request, publicHost, publicScheme string, ownerLookup func(uint64) string, links ...*Share) []*ShareFrontend { + out := make([]*ShareFrontend, 0, len(links)) + for _, link := range links { + if link == nil { + continue + } + out = append(out, prepForFrontendOne(link, viewer, r, publicHost, publicScheme, ownerLookup)) + } + return utils.NonNilSlice(out) +} + +func copyShareFrontendFromShare(link *Share) ShareFrontend { + snap := *link + out := ShareFrontend{ + ShareEditable: ShareEditable{ + FrontendShareInfo: snap.FrontendShareInfo, + ShareLimits: snap.ShareLimits, + }, + ShareColumns: snap.ShareColumns, + } + if snap.AllowedUsernames != nil { + out.AllowedUsernames = append([]string(nil), snap.AllowedUsernames...) + } + if snap.SidebarLinks != nil { + out.SidebarLinks = make([]users.SidebarLink, len(snap.SidebarLinks)) + copy(out.SidebarLinks, snap.SidebarLinks) + } + return out +} + +func prepForFrontendOne(link *Share, viewer *users.User, r *http.Request, publicHost, publicScheme string, ownerLookup func(uint64) string) *ShareFrontend { + snap := *link + out := copyShareFrontendFromShare(link) + out.HasPassword = snap.HasPassword() + if snap.UserID != 0 && ownerLookup != nil { + out.Username = ownerLookup(snap.UserID) + } + if sourceInfo, ok := resolveSource(snap.SourcePath); ok { + out.PathExists = utils.CheckPathExists(filepath.Join(sourceInfo.Path, out.Path)) + } + if viewer != nil { + out.CanEditShare = snap.UserCanEdit(viewer) + if out.CanEditShare { + out.SourceURL = snap.SourceURL(viewer) + } + } + out.SingleFileShare = snap.IsSingleFileShare() + if r != nil && publicHost != "" { + out.DownloadURL = PublicShareURL(publicHost, publicScheme, out.Hash, true, snap.Token) + out.ShareURL = PublicShareURL(publicHost, publicScheme, out.Hash, false, snap.Token) + } + return &out +} + +// PublicShareURL builds share/download URLs using pre-resolved host and scheme (see web/proxy.go). +func PublicShareURL(host, scheme, hash string, isDirectDownload bool, token string) string { + tokenParam := "" + if token != "" && isDirectDownload { + tokenParam = fmt.Sprintf("&token=%s", url.QueryEscape(token)) + } + + if settings.Config.Http.ExternalUrl != "" { + if isDirectDownload { + return fmt.Sprintf("%s%spublic/api/resources/download?hash=%s%s", + settings.Config.Http.ExternalUrl, settings.Config.Http.BaseURL, hash, tokenParam) + } + return fmt.Sprintf("%s%spublic/share/%s", + settings.Config.Http.ExternalUrl, settings.Config.Http.BaseURL, hash) + } + + if isDirectDownload { + return fmt.Sprintf("%s://%s%spublic/api/resources/download?hash=%s%s", + scheme, host, settings.Config.Http.BaseURL, hash, tokenParam) + } + return fmt.Sprintf("%s://%s%spublic/share/%s", scheme, host, settings.Config.Http.BaseURL, hash) +} diff --git a/backend/internal/database/share/permissions.go b/backend/internal/database/share/permissions.go new file mode 100644 index 0000000000..790f1d0264 --- /dev/null +++ b/backend/internal/database/share/permissions.go @@ -0,0 +1,47 @@ +package share + +import ( + "fmt" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// FilePermissions maps share settings to per-source file operation flags. +func (l *Share) FilePermissions() users.SourceFilePermissions { + return users.SourceFilePermissions{ + View: !l.DisableFileViewer, + Download: !l.DisableDownload, + Modify: l.AllowModify, + Delete: l.AllowDelete, + Create: l.AllowCreate, + } +} + +// EffectiveFilePermissions returns share-scoped permissions when link is active, +// otherwise resolves permissions from the authenticated user. +func EffectiveFilePermissions(user *users.User, link *Share, sourceName string) (users.SourceFilePermissions, error) { + if link != nil && link.Hash != "" { + return link.FilePermissions(), nil + } + if user == nil { + return users.DenyAllSourceFilePermissions(), fmt.Errorf("user context not set") + } + return user.FilePermsForSourceName(sourceName) +} + +// ClampShareEditable limits client-requested share flags to what the owner is allowed on the source. +func ClampShareEditable(ownerPerms users.SourceFilePermissions, editable *ShareEditable) { + if editable == nil { + return + } + editable.AllowModify = editable.AllowModify && ownerPerms.Modify + editable.AllowCreate = editable.AllowCreate && ownerPerms.Create + editable.AllowDelete = editable.AllowDelete && ownerPerms.Delete + if !ownerPerms.Download { + editable.DisableDownload = true + } + if !ownerPerms.View { + editable.DisableFileViewer = true + editable.EnableOnlyOffice = false + } +} diff --git a/backend/internal/database/share/permissions_test.go b/backend/internal/database/share/permissions_test.go new file mode 100644 index 0000000000..ebdbef6f1c --- /dev/null +++ b/backend/internal/database/share/permissions_test.go @@ -0,0 +1,100 @@ +package share + +import ( + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func initPermissionsTestSources(t *testing.T) { + t.Helper() + users.SetSourceNameResolver(func(name string) (string, error) { + if name == "default" { + return "/default", nil + } + return "", nil + }) +} + +func TestEffectiveFilePermissionsUsesUserSourcePerms(t *testing.T) { + t.Parallel() + initPermissionsTestSources(t) + + userPerms := users.SourceFilePermissions{ + View: true, Download: true, Modify: true, Create: true, Delete: true, + } + user := &users.User{ + FrontendUser: users.FrontendUser{Username: "alice"}, + BackendScopes: []users.BackendScope{ + {Path: "/default", Scope: "/", Permissions: userPerms}, + }, + BackendSourcePermissions: map[string]users.SourceFilePermissions{ + "/default": userPerms, + }, + Version: users.SourcePermissionsMigrationVersion, + } + + got, err := EffectiveFilePermissions(user, nil, "default") + if err != nil { + t.Fatalf("EffectiveFilePermissions: %v", err) + } + if got != userPerms { + t.Fatalf("EffectiveFilePermissions = %+v, want %+v", got, userPerms) + } +} + +func TestShareFilePermissions(t *testing.T) { + t.Parallel() + link := Share{ShareColumns: ShareColumns{Hash: "abc"}} + link.DisableFileViewer = true + link.DisableDownload = true + link.AllowModify = true + link.AllowDelete = false + link.AllowCreate = true + got := link.FilePermissions() + want := users.SourceFilePermissions{ + View: false, Download: false, Modify: true, Delete: false, Create: true, + } + if got != want { + t.Fatalf("FilePermissions = %+v, want %+v", got, want) + } +} + +func TestClampShareEditable(t *testing.T) { + t.Parallel() + ownerPerms := users.SourceFilePermissions{ + View: true, Download: false, Modify: false, Create: true, Delete: false, + } + editable := ShareEditable{} + editable.AllowModify = true + editable.AllowCreate = true + editable.AllowDelete = true + editable.DisableDownload = false + editable.DisableFileViewer = false + editable.EnableOnlyOffice = true + + ClampShareEditable(ownerPerms, &editable) + + if editable.AllowModify { + t.Fatal("expected AllowModify clamped to false") + } + if !editable.DisableDownload { + t.Fatal("expected DisableDownload forced true when owner lacks download") + } + if editable.AllowCreate != true { + t.Fatal("expected AllowCreate to remain true") + } + if editable.AllowDelete { + t.Fatal("expected AllowDelete clamped to false") + } + + noView := users.SourceFilePermissions{View: false, Download: true, Modify: true, Create: true, Delete: true} + editable2 := ShareEditable{FrontendShareInfo: FrontendShareInfo{EnableOnlyOffice: true}} + ClampShareEditable(noView, &editable2) + if !editable2.DisableFileViewer { + t.Fatal("expected DisableFileViewer when owner lacks view") + } + if editable2.EnableOnlyOffice { + t.Fatal("expected EnableOnlyOffice false when owner lacks view") + } +} diff --git a/backend/database/share/pinned_items.go b/backend/internal/database/share/pinned_items.go similarity index 80% rename from backend/database/share/pinned_items.go rename to backend/internal/database/share/pinned_items.go index 99142f2ed5..f5bc00b46c 100644 --- a/backend/database/share/pinned_items.go +++ b/backend/internal/database/share/pinned_items.go @@ -5,7 +5,7 @@ import ( "slices" "strings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" ) // PinnedItems maps share-relative directory paths to pinned item names. @@ -56,17 +56,17 @@ func (p PinnedItems) NamesForDirectory(shareRelDir string) []string { } // EnsurePinnedItems returns a non-nil map for mutation. -func (l *Link) EnsurePinnedItems() PinnedItems { - if l.PinnedItems == nil { - l.PinnedItems = make(PinnedItems) +func (s *Share) EnsurePinnedItems() PinnedItems { + if s.PinnedItems == nil { + s.PinnedItems = make(PinnedItems) } - return l.PinnedItems + return s.PinnedItems } // ShareRelativeDir maps a source index directory path to a share-relative directory path. -// link.Path is the index path of the share root (e.g. "/share/"). -func (l *Link) ShareRelativeDir(indexDirPath string) (string, error) { - shareRootIndex := utils.AddTrailingSlashIfNotExists(l.Path) +// s.Path is the index path of the share root (e.g. "/share/"). +func (s *Share) ShareRelativeDir(indexDirPath string) (string, error) { + shareRootIndex := utils.AddTrailingSlashIfNotExists(s.Path) indexDirPath = utils.AddTrailingSlashIfNotExists(indexDirPath) if !strings.HasPrefix(indexDirPath, shareRootIndex) { return "", fmt.Errorf("path is outside share scope") diff --git a/backend/database/share/pinned_items_test.go b/backend/internal/database/share/pinned_items_test.go similarity index 95% rename from backend/database/share/pinned_items_test.go rename to backend/internal/database/share/pinned_items_test.go index 36e892b33e..683d72a957 100644 --- a/backend/database/share/pinned_items_test.go +++ b/backend/internal/database/share/pinned_items_test.go @@ -38,7 +38,7 @@ func TestSharePinnedNamesForDirectory(t *testing.T) { } func TestShareRelativeDir(t *testing.T) { - link := &Link{CommonShare: CommonShare{Path: "/share/"}} + link := &Share{ShareColumns: ShareColumns{Path: "/share/"}} got, err := link.ShareRelativeDir("/share/") if err != nil { diff --git a/backend/internal/database/share/share.go b/backend/internal/database/share/share.go new file mode 100644 index 0000000000..472a575a0c --- /dev/null +++ b/backend/internal/database/share/share.go @@ -0,0 +1,139 @@ +package share + +import ( + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// FrontendShareInfo is share presentation and behavior for visitors (stored in share_settings JSON). +type FrontendShareInfo struct { + ShareTheme string `json:"shareTheme,omitempty"` + DisableAnonymous bool `json:"disableAnonymous,omitempty"` + DisableThumbnails bool `json:"disableThumbnails,omitempty"` + KeepAfterExpiration bool `json:"keepAfterExpiration,omitempty"` + ThemeColor string `json:"themeColor,omitempty"` + Title string `json:"title,omitempty"` + Description string `json:"description,omitempty"` + Favicon string `json:"favicon,omitempty"` + QuickDownload bool `json:"quickDownload,omitempty"` + HideNavButtons bool `json:"hideNavButtons,omitempty"` + DisableSidebar bool `json:"disableSidebar"` + DownloadURL string `json:"downloadURL,omitempty"` + ShareURL string `json:"shareURL,omitempty"` + FaviconUrl string `json:"faviconUrl,omitempty"` + BannerUrl string `json:"bannerUrl,omitempty"` + DisableShareCard bool `json:"disableShareCard,omitempty"` + EnforceDarkLightMode string `json:"enforceDarkLightMode,omitempty"` // "dark" or "light" + ViewMode string `json:"viewMode,omitempty"` // default view mode for anonymous users + EnableOnlyOffice bool `json:"enableOnlyOffice,omitempty"` + ShareType string `json:"shareType"` + AllowDelete bool `json:"allowDelete,omitempty"` + AllowCreate bool `json:"allowCreate,omitempty"` + AllowModify bool `json:"allowModify,omitempty"` + DisableFileViewer bool `json:"disableFileViewer,omitempty"` + DisableDownload bool `json:"disableDownload,omitempty"` + AllowReplacements bool `json:"allowReplacements,omitempty"` + SidebarLinks []users.SidebarLink `json:"sidebarLinks"` + HasPassword bool `json:"hasPassword,omitempty"` + ShowHidden bool `json:"showHidden,omitempty"` + DisableLoginOption bool `json:"disableLoginOption"` + SourceURL string `json:"sourceURL,omitempty"` + CanEditShare bool `json:"canEditShare,omitempty"` + SingleFileShare bool `json:"singleFileShare,omitempty"` +} + +// ShareLimits are bandwidth, access, and banner settings stored in share_settings JSON. +type ShareLimits struct { + MaxBandwidth int `json:"maxBandwidth,omitempty"` + AllowedUsernames []string `json:"allowedUsernames,omitempty"` + PerUserDownloadLimit bool `json:"perUserDownloadLimit,omitempty"` + ExtractEmbeddedSubtitles bool `json:"extractEmbeddedSubtitles,omitempty"` + DownloadsLimit int `json:"downloadsLimit,omitempty"` + HideFileExt string `json:"hideFileExt,omitempty"` // show hidden files based on extensions in shares + Banner string `json:"banner,omitempty"` + SourceName string `json:"source,omitempty"` // source display name for API; backend path is Share.SourcePath +} + +// ShareExpiryInput is POST body input used to compute ShareColumns.Expire (not persisted). +type ShareExpiryInput struct { + Expires string `json:"expires,omitempty"` + Unit string `json:"unit,omitempty"` +} + +// ShareSettings is persisted in the share_settings JSON column. +type ShareSettings struct { + FrontendShareInfo + ShareLimits + PinnedItems PinnedItems `json:"pinnedItems,omitempty"` +} + +// ShareColumns are SQL-backed identity and counter fields. +type ShareColumns struct { + Hash string `json:"hash,omitempty" storm:"id,index"` + Path string `json:"path,omitempty"` + Expire int64 `json:"expire"` + Downloads int `json:"downloads,omitempty"` +} + +// ShareEditable is the client-editable subset used in POST/PATCH bodies. +type ShareEditable struct { + FrontendShareInfo + ShareLimits + ShareExpiryInput +} + +// ShareFrontend is the share shape returned by list/get/create/update API responses. +type ShareFrontend struct { + ShareEditable + ShareColumns + Username string `json:"username,omitempty"` + PathExists bool `json:"pathExists,omitempty"` +} + +// SharePostBody is POST /api/share JSON. Plaintext password is hashed to Share.PasswordHash before persist. +// Password omitted (nil) on update means keep the existing hash; empty string clears it. +type SharePostBody struct { + ShareEditable + Password *string `json:"password,omitempty"` + Hash string `json:"hash,omitempty"` + Path string `json:"path,omitempty"` +} + +// ApplyPostBodyUpdate copies client-editable fields onto link. +// Caller must preserve path, sourcePath, pinnedItems, version, download counters, and secrets. +func ApplyPostBodyUpdate(link *Share, req *SharePostBody, expire int64) { + link.FrontendShareInfo = req.FrontendShareInfo + link.ShareLimits = req.ShareLimits + link.Expire = expire +} + +// Share is the persisted share: settings JSON, SQL columns, and backend-only fields. +type Share struct { + ShareSettings + ShareColumns + PasswordHash string `json:"password_hash,omitempty"` + UserID uint64 `json:"userID,omitempty"` + Token string `json:"token,omitempty"` + UserDownloads map[string]int `json:"userDownloads,omitempty"` + Version int `json:"version,omitempty"` + SourcePath string `json:"sourcePath,omitempty"` +} + +// LegacyShare embeds Share for Bolt/Storm. LegacyRoutingSource is the historical Bolt/JSON "source" field +// (path or name); it becomes Share.SourcePath after migration. +type LegacyShare struct { + Share + PasswordHash string `json:"password_hash,omitempty"` + LegacyRoutingSource string `json:"source,omitempty"` +} + +// ToShare builds the SQLite/runtime share from a Bolt/Storm legacy record. +// Legacy JSON "source" (backend filesystem path) → SourcePath; share "path" stays Path. +// Legacy userID (small uint from Bolt users) is kept as-is; owner username is not stored. +func (l *LegacyShare) ToShare() Share { + s := l.Share + if l.PasswordHash != "" { + s.PasswordHash = l.PasswordHash + } + s.SourcePath = l.LegacyRoutingSource + return s +} diff --git a/backend/internal/database/share/storage.go b/backend/internal/database/share/storage.go new file mode 100644 index 0000000000..ebe0af5b0b --- /dev/null +++ b/backend/internal/database/share/storage.go @@ -0,0 +1,221 @@ +package share + +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/go-logger/logger" +) + +// StorageBackend is the interface to implement for a share storage. +type StorageBackend interface { + All() ([]*Share, error) + FindByUserID(userID uint64) ([]*Share, error) + GetByHash(hash string) (*Share, error) + GetShareInfoByHash(hash string) (*FrontendShareInfo, error) + GetPermanent(path, source string, userID uint64) (*Share, error) + GetBySourcePath(path, source string) ([]*Share, error) + Gets(path, source string, userID uint64) ([]*Share, error) + Save(s *Share) error + Delete(hash string) error +} + +// crudBackend implements crud.CrudBackend[ShareInfo] for share storage. +type crudBackend struct { + back StorageBackend +} + +func (c *crudBackend) GetByID(id any) (*Share, error) { + hash, ok := id.(string) + if !ok { + return nil, errors.ErrInvalidDataType + } + return c.back.GetByHash(hash) +} + +func (c *crudBackend) GetAll() ([]*Share, error) { + return c.back.All() +} + +func (c *crudBackend) Save(obj *Share) error { + return c.back.Save(obj) +} + +func (c *crudBackend) DeleteByID(id any) error { + hash, ok := id.(string) + if !ok { + return errors.ErrInvalidDataType + } + return c.back.Delete(hash) +} + +// Storage fronts StorageBackend (e.g. state.shareBackend). Authoritative in-memory shares live in +// package state, updated after successful database writes; this wrapper does not keep a second copy. +type Storage struct { + Generic *crud.Storage[Share] + back StorageBackend + users *users.Storage +} + +// NewStorage returns Storage that delegates all operations to back. +func NewStorage(back StorageBackend, usersStore *users.Storage) *Storage { + return &Storage{ + Generic: crud.NewStorage[Share](&crudBackend{back: back}), + back: back, + users: usersStore, + } +} + +// All returns all non-expired shares from the backend. +func (s *Storage) All() ([]*Share, error) { + return s.back.All() +} + +// FindByUserID returns non-expired shares owned by userID from the backend. +func (s *Storage) FindByUserID(userID uint64) ([]*Share, error) { + return s.back.FindByUserID(userID) +} + +// PrepForFrontend returns API-safe ShareFrontend copies for one or more shares. +func (s *Storage) PrepForFrontend(viewer *users.User, r *http.Request, links ...*Share) []*ShareFrontend { + return PrepForFrontend(viewer, r, "", "", nil, links...) +} + +// GetByHash wraps StorageBackend.GetByHash and handles expiry. +func (s *Storage) GetByHash(hash string) (*Share, error) { + link, err := s.back.GetByHash(hash) + if err != nil { + return nil, err + } + if link.Expire != 0 && link.Expire <= time.Now().Unix() { + _ = s.back.Delete(hash) + return nil, errors.ErrNotExist + } + link.InitUserDownloads() + return link, nil +} + +// GetPermanent wraps StorageBackend.GetPermanent +func (s *Storage) GetPermanent(path, source string, userID uint64) (*Share, error) { + return s.back.GetPermanent(path, source, userID) +} + +// Gets returns shares for the given path, source, and owner user id. +func (s *Storage) Gets(sourcePath, source string, userID uint64) ([]*Share, error) { + return s.back.Gets(sourcePath, source, userID) +} + +// GetBySourcePath returns shares for the given path and source. +func (s *Storage) GetBySourcePath(path, source string) ([]*Share, error) { + return s.back.GetBySourcePath(path, source) +} + +// IsShared returns whether the given path and source have any shares for owner userID. +func (s *Storage) IsShared(path, source string, userID uint64) bool { + links, _ := s.GetBySourcePath(path, source) + for _, l := range links { + if l.UserID == userID { + return true + } + } + return len(links) > 0 +} + +// UpdateShares updates all shares that match oldSource and oldPath to point to newSource and newPath. +// Handles both exact matches and subdirectories, regardless of trailing slashes. +func (s *Storage) UpdateShares(oldSource, oldPath, newSource, newPath string) (int, error) { + links, err := s.back.All() + if err != nil && err != errors.ErrNotExist { + logger.Error("failed to list shares", "error", err) + 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 { + continue + } + + l.SourcePath = newSource + l.Path = newPath + + if err := s.back.Save(l); err != nil { + logger.Error("failed to save updated share", "hash", l.Hash, "error", err) + return updated, err + } + updated++ + } + return updated, nil +} + +// UpdateSharePath updates the path for a specific share identified by hash +func (s *Storage) UpdateSharePath(hash, newPath string) error { + link, err := s.GetByHash(hash) + if err != nil { + return err + } + + link.Path = newPath + + if err := s.back.Save(link); err != nil { + logger.Error("failed to save updated share", "hash", hash, "error", err) + return err + } + + logger.Debug("share path updated", "hash", hash, "toPath", newPath) + return nil +} + +// CreateShare creates a new share via the backend (database + state). +func (s *Storage) CreateShare(l *Share) error { + _, err := s.back.GetByHash(l.Hash) + if err == nil { + return fmt.Errorf("share with hash %s already exists", l.Hash) + } + if !stderrors.Is(err, errors.ErrNotExist) { + return err + } + return s.back.Save(l) +} + +// UpdateShare updates an existing share via the backend. +func (s *Storage) UpdateShare(l *Share) error { + if _, err := s.back.GetByHash(l.Hash); err != nil { + if stderrors.Is(err, errors.ErrNotExist) { + return fmt.Errorf("share with hash %s not found", l.Hash) + } + return err + } + return s.back.Save(l) +} + +// Delete wraps StorageBackend.Delete +func (s *Storage) Delete(hash string) error { + return s.back.Delete(hash) +} + +// Flush is a no-op: writes go through the backend immediately. +func (s *Storage) Flush() error { + return nil +} + +// GetShareInfoByHash returns share presentation fields for a hash (e.g. public/info). +func (s *Storage) GetShareInfoByHash(hash string) (*FrontendShareInfo, error) { + return s.back.GetShareInfoByHash(hash) +} diff --git a/backend/internal/database/share/update_test.go b/backend/internal/database/share/update_test.go new file mode 100644 index 0000000000..ef3b4844cf --- /dev/null +++ b/backend/internal/database/share/update_test.go @@ -0,0 +1,44 @@ +package share + +import "testing" + +func TestApplyPostBodyUpdateCopiesShareFrontendFields(t *testing.T) { + link := &Share{ + ShareSettings: ShareSettings{ + ShareLimits: ShareLimits{ + MaxBandwidth: 99, + }, + }, + } + req := SharePostBody{ + ShareEditable: ShareEditable{ + ShareLimits: ShareLimits{ + MaxBandwidth: 512, + DownloadsLimit: 3, + HideFileExt: ".tmp", + }, + FrontendShareInfo: FrontendShareInfo{ + ShareTheme: "dark", + Title: "updated", + }, + }, + } + + ApplyPostBodyUpdate(link, &req, 12345) + + if link.MaxBandwidth != 512 { + t.Fatalf("MaxBandwidth: got %d want 512", link.MaxBandwidth) + } + if link.DownloadsLimit != 3 { + t.Fatalf("DownloadsLimit: got %d want 3", link.DownloadsLimit) + } + if link.HideFileExt != ".tmp" { + t.Fatalf("HideFileExt: got %q want .tmp", link.HideFileExt) + } + if link.ShareTheme != "dark" || link.Title != "updated" { + t.Fatalf("FrontendShareInfo not applied: %#v", link.FrontendShareInfo) + } + if link.Expire != 12345 { + t.Fatalf("Expire: got %d want 12345", link.Expire) + } +} diff --git a/backend/database/sql/driver_cgo.go b/backend/internal/database/sql/driver_cgo.go similarity index 100% rename from backend/database/sql/driver_cgo.go rename to backend/internal/database/sql/driver_cgo.go diff --git a/backend/database/sql/driver_nocgo.go b/backend/internal/database/sql/driver_nocgo.go similarity index 100% rename from backend/database/sql/driver_nocgo.go rename to backend/internal/database/sql/driver_nocgo.go diff --git a/backend/database/sql/duplicates.go b/backend/internal/database/sql/duplicates.go similarity index 100% rename from backend/database/sql/duplicates.go rename to backend/internal/database/sql/duplicates.go diff --git a/backend/database/sql/index.go b/backend/internal/database/sql/index.go similarity index 99% rename from backend/database/sql/index.go rename to backend/internal/database/sql/index.go index 26dd629f6c..b9e2ba625d 100644 --- a/backend/database/sql/index.go +++ b/backend/internal/database/sql/index.go @@ -9,8 +9,8 @@ import ( "strings" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" "github.com/gtsteffaniak/go-logger/logger" ) diff --git a/backend/database/sql/index_startup_test.go b/backend/internal/database/sql/index_startup_test.go similarity index 93% rename from backend/database/sql/index_startup_test.go rename to backend/internal/database/sql/index_startup_test.go index 9fbb7f6551..b0d9d38232 100644 --- a/backend/database/sql/index_startup_test.go +++ b/backend/internal/database/sql/index_startup_test.go @@ -5,9 +5,9 @@ import ( "testing" "time" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" ) func TestMain(m *testing.M) { diff --git a/backend/database/sql/search.go b/backend/internal/database/sql/search.go similarity index 100% rename from backend/database/sql/search.go rename to backend/internal/database/sql/search.go diff --git a/backend/database/sql/sqlite.go b/backend/internal/database/sql/tempdb.go similarity index 99% rename from backend/database/sql/sqlite.go rename to backend/internal/database/sql/tempdb.go index 535cd9809b..d7b108a4ed 100644 --- a/backend/database/sql/sqlite.go +++ b/backend/internal/database/sql/tempdb.go @@ -8,8 +8,8 @@ import ( "sync" "time" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" "github.com/gtsteffaniak/go-logger/logger" // SQLite driver is imported in driver_cgo.go or driver_nocgo.go based on build tags ) diff --git a/backend/internal/database/sqldb/access.go b/backend/internal/database/sqldb/access.go new file mode 100644 index 0000000000..271bccb3a3 --- /dev/null +++ b/backend/internal/database/sqldb/access.go @@ -0,0 +1,147 @@ +package sqldb + +import ( + "database/sql" + "encoding/json" + "fmt" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/access" +) + +// Access rules SQL operations + +// GetAccessRulesBySource retrieves all access rules for a source +func (s *SQLStore) GetAccessRulesBySource(source string) (map[string]*access.AccessRule, error) { + query := `SELECT path, rule_data FROM access_rules WHERE source = ? ORDER BY path` + + rows, err := s.db.Query(query, source) + if err != nil { + return nil, fmt.Errorf("failed to get access rules: %w", err) + } + defer rows.Close() + + rules := make(map[string]*access.AccessRule) + for rows.Next() { + var path string + var ruleDataJSON []byte + + err := rows.Scan(&path, &ruleDataJSON) + if err != nil { + return nil, fmt.Errorf("failed to scan access rule: %w", err) + } + + var rule access.AccessRule + if err := json.Unmarshal(ruleDataJSON, &rule); err != nil { + return nil, fmt.Errorf("failed to unmarshal rule data: %w", err) + } + + rules[path] = &rule + } + + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("error iterating access rules: %w", err) + } + + return rules, nil +} + +// GetAccessRule retrieves a specific access rule +func (s *SQLStore) GetAccessRule(source, path string) (*access.AccessRule, error) { + query := `SELECT rule_data FROM access_rules WHERE source = ? AND path = ?` + + var ruleDataJSON []byte + err := s.db.QueryRow(query, source, path).Scan(&ruleDataJSON) + + if err == sql.ErrNoRows { + return nil, fmt.Errorf("access rule not found") + } + if err != nil { + return nil, fmt.Errorf("failed to get access rule: %w", err) + } + + var rule access.AccessRule + if err := json.Unmarshal(ruleDataJSON, &rule); err != nil { + return nil, fmt.Errorf("failed to unmarshal rule data: %w", err) + } + + return &rule, nil +} + +// GetAllAccessRules retrieves all access rules organized by source +func (s *SQLStore) GetAllAccessRules() (access.SourceRuleMap, error) { + query := `SELECT source, path, rule_data FROM access_rules ORDER BY source, path` + + rows, err := s.db.Query(query) + if err != nil { + return nil, fmt.Errorf("failed to get all access rules: %w", err) + } + defer rows.Close() + + allRules := make(access.SourceRuleMap) + for rows.Next() { + var source, path string + var ruleDataJSON []byte + + err := rows.Scan(&source, &path, &ruleDataJSON) + if err != nil { + return nil, fmt.Errorf("failed to scan access rule: %w", err) + } + + var rule access.AccessRule + if err := json.Unmarshal(ruleDataJSON, &rule); err != nil { + return nil, fmt.Errorf("failed to unmarshal rule data: %w", err) + } + + if allRules[source] == nil { + allRules[source] = make(access.RuleMap) + } + allRules[source][path] = &rule + } + + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("error iterating access rules: %w", err) + } + + return allRules, nil +} + +// SaveAccessRule inserts or updates an access rule +func (s *SQLStore) SaveAccessRule(source, path string, rule *access.AccessRule) error { + ruleDataJSON, err := json.Marshal(rule) + if err != nil { + return fmt.Errorf("failed to marshal rule data: %w", err) + } + + query := `INSERT OR REPLACE INTO access_rules (source, path, rule_data) VALUES (?, ?, ?)` + _, err = s.db.Exec(query, source, path, ruleDataJSON) + if err != nil { + return fmt.Errorf("failed to save access rule: %w", err) + } + + return nil +} + +// DeleteAccessRule deletes an access rule +func (s *SQLStore) DeleteAccessRule(source, path string) error { + query := `DELETE FROM access_rules WHERE source = ? AND path = ?` + result, err := s.db.Exec(query, source, path) + if err != nil { + return fmt.Errorf("failed to delete access rule: %w", err) + } + + if _, err := result.RowsAffected(); err != nil { + return fmt.Errorf("failed to get rows affected: %w", err) + } + + return nil +} + +// DeleteAccessRulesBySource deletes all access rules for a source +func (s *SQLStore) DeleteAccessRulesBySource(source string) error { + query := `DELETE FROM access_rules WHERE source = ?` + _, err := s.db.Exec(query, source) + if err != nil { + return fmt.Errorf("failed to delete access rules: %w", err) + } + return nil +} diff --git a/backend/internal/database/sqldb/activity.go b/backend/internal/database/sqldb/activity.go new file mode 100644 index 0000000000..fa09fcd353 --- /dev/null +++ b/backend/internal/database/sqldb/activity.go @@ -0,0 +1,414 @@ +package sqldb + +import ( + "database/sql" + "fmt" + "strings" + + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// BulkInsertActivity inserts activity rows in a single transaction. +func (s *SQLStore) BulkInsertActivity(entries []activity.Entry) error { + if len(entries) == 0 { + return nil + } + + tx, err := s.db.Begin() + if err != nil { + return fmt.Errorf("begin activity transaction: %w", err) + } + + stmt, err := tx.Prepare(`INSERT INTO activity_log ( + created_at, user_id, event_type, source, path, target_path, + ip_address, status, success, details + ) VALUES (?, ?, ?, ?, ?, ?, ?, 200, 1, ?)`) + if err != nil { + _ = tx.Rollback() + return fmt.Errorf("prepare activity insert: %w", err) + } + defer stmt.Close() + + for _, e := range entries { + detailsJSON, err := activity.MarshalDetailsJSON(e.Details) + if err != nil { + _ = tx.Rollback() + return fmt.Errorf("marshal activity details: %w", err) + } + _, err = stmt.Exec( + e.CreatedAt, + shareUserIDDB(e.UserID), + string(e.EventType), + nullString(e.Source), + nullString(e.Path), + nullString(e.TargetPath), + nullString(e.IPAddress), + detailsJSON, + ) + if err != nil { + _ = tx.Rollback() + return fmt.Errorf("insert activity row: %w", err) + } + } + + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit activity transaction: %w", err) + } + return nil +} + +func nullString(s string) interface{} { + if s == "" { + return nil + } + return s +} + +// CountActivity returns the total matching rows for pagination. +func (s *SQLStore) CountActivity(filter activity.QueryFilter) (int, error) { + where, args := buildActivityWhere(filter) + query := "SELECT COUNT(*) FROM activity_log" + where + var count int + err := s.db.QueryRow(query, args...).Scan(&count) + if err != nil { + return 0, fmt.Errorf("count activity: %w", err) + } + return count, nil +} + +// ListActivity returns paginated activity rows newest first with actor usernames joined. +func (s *SQLStore) ListActivity(filter activity.QueryFilter) ([]activity.ListRow, error) { + where, args := buildActivityWhere(filter) + where = whereWithAlias(where, "a") + limit := filter.Limit + if limit <= 0 { + limit = 100 + } + if limit > 500 { + limit = 500 + } + page := filter.Page + if page < 1 { + page = 1 + } + offset := (page - 1) * limit + + query := `SELECT a.id, a.created_at, a.user_id, a.event_type, a.source, a.path, a.target_path, + a.ip_address, a.details, + COALESCE(u.username, '') AS actor_username + FROM activity_log a + LEFT JOIN users u ON a.user_id = u.user_id` + where + + " ORDER BY a.created_at DESC, a.id DESC LIMIT ? OFFSET ?" + args = append(args, limit, offset) + + rows, err := s.db.Query(query, args...) + if err != nil { + return nil, fmt.Errorf("list activity: %w", err) + } + defer rows.Close() + + var items []activity.ListRow + for rows.Next() { + row, err := scanActivityListRow(rows) + if err != nil { + return nil, fmt.Errorf("scan activity row: %w", err) + } + items = append(items, *row) + } + return utils.NonNilSlice(items), rows.Err() +} + +func scanActivityListRow(scanner interface { + Scan(dest ...interface{}) error +}) (*activity.ListRow, error) { + var e activity.Entry + var userIDStr string + var source, path, targetPath, ipAddress sql.NullString + var detailsJSON string + var actorUsername string + + err := scanner.Scan( + &e.ID, + &e.CreatedAt, + &userIDStr, + &e.EventType, + &source, + &path, + &targetPath, + &ipAddress, + &detailsJSON, + &actorUsername, + ) + if err != nil { + return nil, err + } + + if err := scanShareUserID(userIDStr, &e.UserID); err != nil { + return nil, err + } + if source.Valid { + e.Source = source.String + } + if path.Valid { + e.Path = path.String + } + if targetPath.Valid { + e.TargetPath = targetPath.String + } + if ipAddress.Valid { + e.IPAddress = ipAddress.String + } + if err := activity.UnmarshalDetailsJSON(detailsJSON, &e.Details); err != nil { + return nil, fmt.Errorf("unmarshal activity details: %w", err) + } + return &activity.ListRow{Entry: e, ActorUsername: actorUsername}, nil +} + +// ListActivityStats returns aggregated counts for charts. +func (s *SQLStore) ListActivityStats(filter activity.QueryFilter) ([]activity.StatsBucket, error) { + interval := normalizeActivityInterval(filter) + splitBy := normalizeActivitySplitBy(filter) + hasTimeBucket := interval != "none" + + table := "activity_log" + where, args := buildActivityWhereTable(filter, table) + bucketExpr := activityBucketExpr(interval) + + var query string + switch { + case hasTimeBucket && splitBy == "eventType": + query = fmt.Sprintf(`SELECT %s AS bucket, event_type AS series_key, '' AS series_label, COUNT(*) AS cnt + FROM %s%s GROUP BY bucket, event_type ORDER BY bucket ASC, cnt DESC`, bucketExpr, table, where) + case hasTimeBucket && splitBy == "user": + query = fmt.Sprintf(`SELECT %s AS bucket, a.user_id AS series_key, COALESCE(u.username, CASE WHEN a.user_id = '0' THEN '%s' ELSE a.user_id END) AS series_label, COUNT(*) AS cnt + FROM activity_log a LEFT JOIN users u ON a.user_id = u.user_id%s + GROUP BY bucket, a.user_id ORDER BY bucket ASC, cnt DESC`, bucketExpr, users.AnonymousUserName, whereWithAlias(where, "a")) + case hasTimeBucket && splitBy == "none": + query = fmt.Sprintf(`SELECT %s AS bucket, 'total' AS series_key, '' AS series_label, COUNT(*) AS cnt + FROM %s%s GROUP BY bucket ORDER BY bucket ASC`, bucketExpr, table, where) + case !hasTimeBucket && splitBy == "eventType": + query = fmt.Sprintf(`SELECT 0 AS bucket, event_type AS series_key, '' AS series_label, COUNT(*) AS cnt + FROM %s%s GROUP BY event_type ORDER BY cnt DESC`, table, where) + case !hasTimeBucket && splitBy == "user": + query = fmt.Sprintf(`SELECT 0 AS bucket, a.user_id AS series_key, COALESCE(u.username, CASE WHEN a.user_id = '0' THEN '%s' ELSE a.user_id END) AS series_label, COUNT(*) AS cnt + FROM activity_log a LEFT JOIN users u ON a.user_id = u.user_id%s + GROUP BY a.user_id ORDER BY cnt DESC`, users.AnonymousUserName, whereWithAlias(where, "a")) + default: + query = fmt.Sprintf(`SELECT 0 AS bucket, 'total' AS series_key, '' AS series_label, COUNT(*) AS cnt + FROM %s%s`, table, where) + } + + rows, err := s.db.Query(query, args...) + if err != nil { + return nil, fmt.Errorf("list activity stats: %w", err) + } + defer rows.Close() + + var buckets []activity.StatsBucket + for rows.Next() { + var b activity.StatsBucket + if err := rows.Scan(&b.Bucket, &b.SeriesKey, &b.SeriesLabel, &b.Count); err != nil { + return nil, fmt.Errorf("scan activity stats: %w", err) + } + if splitBy == "eventType" { + b.EventType = b.SeriesKey + } + buckets = append(buckets, b) + } + return utils.NonNilSlice(buckets), rows.Err() +} + +func normalizeActivityInterval(filter activity.QueryFilter) string { + if filter.Interval != "" { + return filter.Interval + } + switch filter.GroupBy { + case "day": + return "day" + case "none": + return "none" + case "hour", "": + return "hour" + default: + return "hour" + } +} + +func normalizeActivitySplitBy(filter activity.QueryFilter) string { + if filter.SplitBy != "" { + return filter.SplitBy + } + return "eventType" +} + +func activityBucketExpr(interval string) string { + switch interval { + case "minute": + return "((created_at / 60) * 60)" + case "hour": + return "((created_at / 3600) * 3600)" + case "day": + return "((created_at / 86400) * 86400)" + default: + return "0" + } +} + +func whereWithAlias(where, alias string) string { + if where == "" { + return "" + } + return strings.ReplaceAll(where, "activity_log.", alias+".") +} + +// PurgeActivityBefore deletes rows older than cutoffUnix. +func (s *SQLStore) PurgeActivityBefore(cutoffUnix int64) (int64, error) { + res, err := s.db.Exec("DELETE FROM activity_log WHERE created_at < ?", cutoffUnix) + if err != nil { + return 0, fmt.Errorf("purge activity: %w", err) + } + n, err := res.RowsAffected() + if err != nil { + return 0, fmt.Errorf("purge activity rows affected: %w", err) + } + return n, nil +} + +func buildActivityWhere(filter activity.QueryFilter) (string, []interface{}) { + return buildActivityWhereTable(filter, "activity_log") +} + +func buildActivityWhereTable(filter activity.QueryFilter, table string) (string, []interface{}) { + var clauses []string + var args []interface{} + col := func(name string) string { + return table + "." + name + } + + if filter.From > 0 { + clauses = append(clauses, col("created_at")+" >= ?") + args = append(args, filter.From) + } + if filter.To > 0 { + clauses = append(clauses, col("created_at")+" <= ?") + args = append(args, filter.To) + } + if filter.UserFilter { + clauses = append(clauses, col("user_id")+" = ?") + args = append(args, shareUserIDDB(filter.UserID)) + } + if filter.ShareOwnerFilter { + appendShareOwnerActivityClauses(&clauses, &args, filter, table) + } + if filter.Scope == "shares" { + appendShareScopeEventClauses(&clauses, &args, filter, table) + } else if len(filter.EventTypes) > 0 { + placeholders := make([]string, len(filter.EventTypes)) + for i, et := range filter.EventTypes { + placeholders[i] = "?" + args = append(args, string(et)) + } + clauses = append(clauses, col("event_type")+" IN ("+strings.Join(placeholders, ",")+")") + } + if filter.Source != "" { + clauses = append(clauses, col("source")+" = ?") + args = append(args, filter.Source) + } + if filter.PathPrefix != "" { + like := escapeLikePrefix(filter.PathPrefix) + clauses = append(clauses, "("+col("path")+" LIKE ? ESCAPE '\\' OR EXISTS (SELECT 1 FROM json_each("+table+".details, '$.paths') je WHERE je.value LIKE ? ESCAPE '\\'))") + args = append(args, like, like) + } + if filter.PathGlob != "" { + clauses = append(clauses, "("+col("path")+" GLOB ? OR EXISTS (SELECT 1 FROM json_each("+table+".details, '$.paths') je WHERE je.value GLOB ?))") + args = append(args, filter.PathGlob, filter.PathGlob) + } + if filter.ShareHash != "" { + clauses = append(clauses, "json_extract("+table+".details, '$.shareHash') = ?") + args = append(args, filter.ShareHash) + } + + where := "" + if len(clauses) > 0 { + where = " WHERE " + strings.Join(clauses, " AND ") + } + return where, args +} + +func shareHashPresentExpr(table string) string { + return "COALESCE(json_extract(" + table + ".details, '$.shareHash'), '') != ''" +} + +func appendShareScopeEventClauses(clauses *[]string, args *[]interface{}, filter activity.QueryFilter, table string) { + col := func(name string) string { + return table + "." + name + } + shareHash := shareHashPresentExpr(table) + + if len(filter.EventTypes) == 0 { + *clauses = append(*clauses, "("+col("event_type")+" IN (?,?,?) OR ("+col("event_type")+" = ? AND "+shareHash+"))") + *args = append(*args, + string(activity.EventShareCreate), + string(activity.EventShareUpdate), + string(activity.EventShareDelete), + string(activity.EventDownload), + ) + return + } + + var parts []string + for _, et := range filter.EventTypes { + switch et { + case activity.EventShareCreate, activity.EventShareUpdate, activity.EventShareDelete: + parts = append(parts, col("event_type")+" = ?") + *args = append(*args, string(et)) + case activity.EventDownload: + parts = append(parts, "("+col("event_type")+" = ? AND "+shareHash+")") + *args = append(*args, string(et)) + } + } + if len(parts) > 0 { + *clauses = append(*clauses, "("+strings.Join(parts, " OR ")+")") + } +} + +func appendShareOwnerActivityClauses(clauses *[]string, args *[]interface{}, filter activity.QueryFilter, table string) { + col := func(name string) string { + return table + "." + name + } + ownerID := shareUserIDDB(filter.ShareOwnerUserID) + shareOwnerInDetails := "CAST(json_extract(" + table + ".details, '$.shareOwnerUserId') AS TEXT) = ?" + + downloadMatch := "(" + col("event_type") + " = ? AND " + shareOwnerInDetails + ")" + downloadArgs := []interface{}{ + string(activity.EventDownload), + ownerID, + } + + clause := "((" + col("event_type") + " IN (?,?,?) AND " + col("user_id") + " = ?) OR " + downloadMatch + ")" + *clauses = append(*clauses, clause) + *args = append(*args, + string(activity.EventShareCreate), + string(activity.EventShareUpdate), + string(activity.EventShareDelete), + ownerID, + ) + *args = append(*args, downloadArgs...) +} + +func escapeLikePrefix(prefix string) string { + var b strings.Builder + b.Grow(len(prefix) + 8) + for _, r := range prefix { + switch r { + case '\\', '%', '_': + b.WriteRune('\\') + } + b.WriteRune(r) + } + b.WriteByte('%') + return b.String() +} + diff --git a/backend/internal/database/sqldb/activity_test.go b/backend/internal/database/sqldb/activity_test.go new file mode 100644 index 0000000000..ce10281e5d --- /dev/null +++ b/backend/internal/database/sqldb/activity_test.go @@ -0,0 +1,379 @@ +package sqldb + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" +) + +func TestActivityBulkInsertAndQuery(t *testing.T) { + dir := t.TempDir() + dbPath := filepath.Join(dir, "test.sqlite") + + store, _, err := NewSQLStore(dbPath) + if err != nil { + t.Fatalf("NewSQLStore: %v", err) + } + defer store.Close() + + now := time.Now().Unix() + entries := []activitydb.Entry{ + { + CreatedAt: now, + UserID: 42, + EventType: activitydb.EventDownload, + Source: "default", + Path: "/file.txt", + Details: activitydb.Details{Source: "default", Path: "/file.txt"}, + }, + { + CreatedAt: now - 10, + UserID: 99, + EventType: activitydb.EventUpload, + Source: "default", + Path: "/upload.bin", + }, + } + if err = store.BulkInsertActivity(entries); err != nil { + t.Fatalf("BulkInsertActivity: %v", err) + } + + filter := activitydb.QueryFilter{ + From: now - 3600, + To: now + 10, + UserID: 42, + UserFilter: true, + Page: 1, + Limit: 10, + } + count, err := store.CountActivity(filter) + if err != nil { + t.Fatalf("CountActivity: %v", err) + } + if count != 1 { + t.Fatalf("expected count 1, got %d", count) + } + + rows, err := store.ListActivity(filter) + if err != nil { + t.Fatalf("ListActivity: %v", err) + } + if len(rows) != 1 || rows[0].EventType != activitydb.EventDownload { + t.Fatalf("unexpected rows: %+v", rows) + } + + anonEntry := activitydb.Entry{ + CreatedAt: now - 5, + UserID: 0, + EventType: activitydb.EventDownload, + Source: "default", + Path: "/shared.txt", + Details: activitydb.Details{ShareHash: "test-hash", Source: "default", Path: "/shared.txt"}, + } + if err = store.BulkInsertActivity([]activitydb.Entry{anonEntry}); err != nil { + t.Fatalf("BulkInsertActivity anonymous: %v", err) + } + + anonFilter := activitydb.QueryFilter{ + From: now - 3600, + To: now + 10, + UserID: 0, + UserFilter: true, + Page: 1, + Limit: 10, + } + anonCount, err := store.CountActivity(anonFilter) + if err != nil { + t.Fatalf("CountActivity anonymous: %v", err) + } + if anonCount != 1 { + t.Fatalf("expected anonymous count 1, got %d", anonCount) + } + + stats, err := store.ListActivityStats(activitydb.QueryFilter{ + From: now - 3600, + To: now + 10, + Interval: "hour", + SplitBy: "eventType", + }) + if err != nil { + t.Fatalf("ListActivityStats: %v", err) + } + if len(stats) < 2 { + t.Fatalf("expected stats buckets, got %+v", stats) + } + + n, err := store.PurgeActivityBefore(now + 1) + if err != nil { + t.Fatalf("PurgeActivityBefore: %v", err) + } + if n < 2 { + t.Fatalf("expected purge >= 2, got %d", n) + } + + // Ensure DB file exists on disk + if _, err := os.Stat(dbPath); err != nil { + t.Fatalf("db file missing: %v", err) + } +} + +func TestActivityShareScope(t *testing.T) { + dir := t.TempDir() + dbPath := filepath.Join(dir, "share-scope.sqlite") + + store, _, err := NewSQLStore(dbPath) + if err != nil { + t.Fatalf("NewSQLStore: %v", err) + } + defer store.Close() + + now := time.Now().Unix() + entries := []activitydb.Entry{ + { + CreatedAt: now, + UserID: 1, + EventType: activitydb.EventShareCreate, + Source: "default", + Path: "/share-path", + Details: activitydb.Details{ShareHash: "abc123"}, + }, + { + CreatedAt: now, + UserID: 0, + EventType: activitydb.EventDownload, + Source: "default", + Path: "/file.txt", + Details: activitydb.Details{ShareHash: "abc123", Source: "default", Path: "/file.txt"}, + }, + { + CreatedAt: now, + UserID: 0, + EventType: activitydb.EventDownload, + Source: "default", + Path: "/plain.txt", + }, + } + if err = store.BulkInsertActivity(entries); err != nil { + t.Fatalf("BulkInsertActivity: %v", err) + } + + base := activitydb.QueryFilter{ + From: now - 10, + To: now + 10, + Scope: "shares", + Page: 1, + Limit: 50, + } + shareCount, err := store.CountActivity(base) + if err != nil { + t.Fatalf("CountActivity shares scope: %v", err) + } + if shareCount != 2 { + t.Fatalf("shares scope expected 2 rows (create + share download), got %d", shareCount) + } + + filesFilter := activitydb.QueryFilter{ + From: now - 10, + To: now + 10, + Scope: "files", + EventTypes: activitydb.FileEventTypes, + Page: 1, + Limit: 50, + } + fileCount, err := store.CountActivity(filesFilter) + if err != nil { + t.Fatalf("CountActivity files scope: %v", err) + } + if fileCount != 2 { + t.Fatalf("files scope expected 2 download rows, got %d", fileCount) + } + + downloadOnly := base + downloadOnly.EventTypes = []activitydb.EventType{activitydb.EventDownload} + dlCount, err := store.CountActivity(downloadOnly) + if err != nil { + t.Fatalf("CountActivity shares download filter: %v", err) + } + if dlCount != 1 { + t.Fatalf("shares download filter expected 1 row, got %d", dlCount) + } +} + +func TestActivityShareOwnerFilter(t *testing.T) { + dir := t.TempDir() + dbPath := filepath.Join(dir, "share-owner.sqlite") + + store, _, err := NewSQLStore(dbPath) + if err != nil { + t.Fatalf("NewSQLStore: %v", err) + } + defer store.Close() + + now := time.Now().Unix() + entries := []activitydb.Entry{ + { + CreatedAt: now, + UserID: 5, + EventType: activitydb.EventShareCreate, + Source: "default", + Path: "/mine", + Details: activitydb.Details{ShareHash: "owned-hash"}, + }, + { + CreatedAt: now, + UserID: 0, + EventType: activitydb.EventDownload, + Source: "default", + Path: "/file.txt", + Details: activitydb.Details{ + ShareHash: "owned-hash", + ShareOwnerUserID: 5, + Source: "default", + Path: "/file.txt", + }, + }, + { + CreatedAt: now, + UserID: 9, + EventType: activitydb.EventShareCreate, + Source: "default", + Path: "/other", + Details: activitydb.Details{ShareHash: "other-hash"}, + }, + } + if err = store.BulkInsertActivity(entries); err != nil { + t.Fatalf("BulkInsertActivity: %v", err) + } + + ownerFilter := activitydb.QueryFilter{ + From: now - 10, + To: now + 10, + Scope: "shares", + ShareOwnerUserID: 5, + ShareOwnerFilter: true, + Page: 1, + Limit: 50, + } + ownerCount, err := store.CountActivity(ownerFilter) + if err != nil { + t.Fatalf("CountActivity share owner: %v", err) + } + if ownerCount != 2 { + t.Fatalf("share owner filter expected 2 rows, got %d", ownerCount) + } +} + +func TestActivityListActivityMalformedDetailsJSON(t *testing.T) { + dir := t.TempDir() + dbPath := filepath.Join(dir, "test.sqlite") + + store, _, err := NewSQLStore(dbPath) + if err != nil { + t.Fatalf("NewSQLStore: %v", err) + } + defer store.Close() + + now := time.Now().Unix() + _, err = store.db.Exec(`INSERT INTO activity_log ( + created_at, user_id, event_type, source, path, target_path, + ip_address, status, success, details + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + now, "1", "download", "default", "/bad.json", nil, nil, 200, 1, "{not valid json", + ) + if err != nil { + t.Fatalf("insert malformed details row: %v", err) + } + + filter := activitydb.QueryFilter{ + From: now - 10, + To: now + 10, + Page: 1, + Limit: 10, + } + _, err = store.ListActivity(filter) + if err == nil { + t.Fatal("expected error listing activity with malformed details JSON") + } + if !strings.Contains(err.Error(), "unmarshal activity details") { + t.Fatalf("expected unmarshal activity details error, got: %v", err) + } +} + +func TestActivityPathPrefixLikeLiterals(t *testing.T) { + dir := t.TempDir() + dbPath := filepath.Join(dir, "test.sqlite") + + store, _, err := NewSQLStore(dbPath) + if err != nil { + t.Fatalf("NewSQLStore: %v", err) + } + defer store.Close() + + now := time.Now().Unix() + entries := []activitydb.Entry{ + { + CreatedAt: now, + UserID: 1, + EventType: activitydb.EventDownload, + Source: "default", + Path: "/a%b/file.txt", + }, + { + CreatedAt: now, + UserID: 1, + EventType: activitydb.EventDownload, + Source: "default", + Path: "/axb/file.txt", + }, + { + CreatedAt: now, + UserID: 1, + EventType: activitydb.EventDownload, + Source: "default", + Path: "/a_b/file.txt", + }, + } + if err = store.BulkInsertActivity(entries); err != nil { + t.Fatalf("BulkInsertActivity: %v", err) + } + + filter := activitydb.QueryFilter{ + From: now - 10, + To: now + 10, + PathPrefix: "/a%b", + Page: 1, + Limit: 10, + } + rows, err := store.ListActivity(filter) + if err != nil { + t.Fatalf("ListActivity with literal %% prefix: %v", err) + } + if len(rows) != 1 { + t.Fatalf("literal %% prefix expected 1 row, got %d: %+v", len(rows), rows) + } + if rows[0].Path != "/a%b/file.txt" { + t.Fatalf("expected /a%%b/file.txt, got %q", rows[0].Path) + } + + underscoreFilter := activitydb.QueryFilter{ + From: now - 10, + To: now + 10, + PathPrefix: "/a_b", + Page: 1, + Limit: 10, + } + underscoreRows, err := store.ListActivity(underscoreFilter) + if err != nil { + t.Fatalf("ListActivity with literal _ prefix: %v", err) + } + if len(underscoreRows) != 1 { + t.Fatalf("literal _ prefix expected 1 row, got %d: %+v", len(underscoreRows), underscoreRows) + } + if underscoreRows[0].Path != "/a_b/file.txt" { + t.Fatalf("expected /a_b/file.txt, got %q", underscoreRows[0].Path) + } +} diff --git a/backend/internal/database/sqldb/auth.go b/backend/internal/database/sqldb/auth.go new file mode 100644 index 0000000000..3c4fdb8179 --- /dev/null +++ b/backend/internal/database/sqldb/auth.go @@ -0,0 +1,88 @@ +package sqldb + +import ( + "database/sql" + "encoding/json" + "fmt" +) + +// Auth methods SQL operations + +// GetAuthMethod retrieves an auth method by type +func (s *SQLStore) GetAuthMethod(authType string) ([]byte, error) { + query := `SELECT config FROM auth_methods WHERE type = ?` + + var config []byte + err := s.db.QueryRow(query, authType).Scan(&config) + + if err == sql.ErrNoRows { + return nil, fmt.Errorf("auth method not found: %s", authType) + } + if err != nil { + return nil, fmt.Errorf("failed to get auth method: %w", err) + } + + return config, nil +} + +// SaveAuthMethod inserts or updates an auth method +func (s *SQLStore) SaveAuthMethod(authType string, config interface{}) error { + configJSON, err := json.Marshal(config) + if err != nil { + return fmt.Errorf("failed to marshal auth method config: %w", err) + } + + query := `INSERT OR REPLACE INTO auth_methods (type, config) VALUES (?, ?)` + _, err = s.db.Exec(query, authType, configJSON) + if err != nil { + return fmt.Errorf("failed to save auth method: %w", err) + } + + return nil +} + +// DeleteAuthMethod deletes an auth method by type +func (s *SQLStore) DeleteAuthMethod(authType string) error { + query := `DELETE FROM auth_methods WHERE type = ?` + result, err := s.db.Exec(query, authType) + if err != nil { + return fmt.Errorf("failed to delete auth method: %w", err) + } + + rowsAffected, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("failed to get rows affected: %w", err) + } + + if rowsAffected == 0 { + return fmt.Errorf("auth method not found") + } + + return nil +} + +// GetAllAuthMethods retrieves all auth methods as a map +func (s *SQLStore) GetAllAuthMethods() (map[string][]byte, error) { + query := `SELECT type, config FROM auth_methods` + rows, err := s.db.Query(query) + if err != nil { + return nil, fmt.Errorf("failed to get all auth methods: %w", err) + } + defer rows.Close() + + authMethods := make(map[string][]byte) + for rows.Next() { + var authType string + var config []byte + if err := rows.Scan(&authType, &config); err != nil { + return nil, fmt.Errorf("failed to scan auth method: %w", err) + } + authMethods[authType] = config + } + + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("error iterating auth methods: %w", err) + } + + return authMethods, nil +} diff --git a/backend/internal/database/sqldb/driver_cgo.go b/backend/internal/database/sqldb/driver_cgo.go new file mode 100644 index 0000000000..106c7957dd --- /dev/null +++ b/backend/internal/database/sqldb/driver_cgo.go @@ -0,0 +1,10 @@ +//go:build cgosql +// +build cgosql + +package sqldb + +import ( + _ "github.com/mattn/go-sqlite3" +) + +const SqliteDriver = "sqlite3" diff --git a/backend/internal/database/sqldb/driver_nocgo.go b/backend/internal/database/sqldb/driver_nocgo.go new file mode 100644 index 0000000000..6679a3a6ab --- /dev/null +++ b/backend/internal/database/sqldb/driver_nocgo.go @@ -0,0 +1,10 @@ +//go:build !cgosql +// +build !cgosql + +package sqldb + +import ( + _ "modernc.org/sqlite" +) + +const SqliteDriver = "sqlite" diff --git a/backend/internal/database/sqldb/groups.go b/backend/internal/database/sqldb/groups.go new file mode 100644 index 0000000000..1b1b719dab --- /dev/null +++ b/backend/internal/database/sqldb/groups.go @@ -0,0 +1,122 @@ +package sqldb + +import ( + "database/sql" + "encoding/json" + "fmt" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/access" +) + +// Groups SQL operations + +// GetGroup retrieves a group by name +func (s *SQLStore) GetGroup(name string) (access.StringSet, error) { + query := `SELECT members FROM groups WHERE name = ?` + + var membersJSON []byte + err := s.db.QueryRow(query, name).Scan(&membersJSON) + + if err == sql.ErrNoRows { + return nil, fmt.Errorf("group not found") + } + if err != nil { + return nil, fmt.Errorf("failed to get group: %w", err) + } + + var members []string + if err := json.Unmarshal(membersJSON, &members); err != nil { + return nil, fmt.Errorf("failed to unmarshal members: %w", err) + } + + // Convert slice to StringSet + memberSet := make(access.StringSet) + for _, member := range members { + memberSet[member] = struct{}{} + } + + return memberSet, nil +} + +// GetAllGroups retrieves all groups +func (s *SQLStore) GetAllGroups() (access.GroupMap, error) { + query := `SELECT name, members FROM groups ORDER BY name` + + rows, err := s.db.Query(query) + if err != nil { + return nil, fmt.Errorf("failed to get all groups: %w", err) + } + defer rows.Close() + + groups := make(access.GroupMap) + for rows.Next() { + var name string + var membersJSON []byte + + err := rows.Scan(&name, &membersJSON) + if err != nil { + return nil, fmt.Errorf("failed to scan group: %w", err) + } + + var members []string + if err := json.Unmarshal(membersJSON, &members); err != nil { + return nil, fmt.Errorf("failed to unmarshal members: %w", err) + } + + // Convert slice to StringSet + memberSet := make(access.StringSet) + for _, member := range members { + memberSet[member] = struct{}{} + } + + groups[name] = memberSet + } + + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("error iterating groups: %w", err) + } + + return groups, nil +} + +// SaveGroup inserts or updates a group +func (s *SQLStore) SaveGroup(name string, members access.StringSet) error { + // Convert StringSet to slice for JSON + memberSlice := make([]string, 0, len(members)) + for member := range members { + memberSlice = append(memberSlice, member) + } + + membersJSON, err := json.Marshal(memberSlice) + if err != nil { + return fmt.Errorf("failed to marshal members: %w", err) + } + + query := `INSERT OR REPLACE INTO groups (name, members) VALUES (?, ?)` + _, err = s.db.Exec(query, name, membersJSON) + if err != nil { + return fmt.Errorf("failed to save group: %w", err) + } + + return nil +} + +// DeleteGroup deletes a group by name +func (s *SQLStore) DeleteGroup(name string) error { + query := `DELETE FROM groups WHERE name = ?` + result, err := s.db.Exec(query, name) + if err != nil { + return fmt.Errorf("failed to delete group: %w", err) + } + + rowsAffected, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("failed to get rows affected: %w", err) + } + + if rowsAffected == 0 { + return fmt.Errorf("group not found") + } + + return nil +} diff --git a/backend/internal/database/sqldb/indexing.go b/backend/internal/database/sqldb/indexing.go new file mode 100644 index 0000000000..3183b0f202 --- /dev/null +++ b/backend/internal/database/sqldb/indexing.go @@ -0,0 +1,170 @@ +package sqldb + +import ( + "database/sql" + "encoding/json" + "fmt" + + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/dbindex" +) + +// Index info SQL operations + +// GetIndexInfoByPath retrieves index info by path +func (s *SQLStore) GetIndexInfoByPath(path string) (*dbindex.IndexInfo, error) { + query := `SELECT path, source, complexity, num_dirs, num_files, scanners + FROM index_info WHERE path = ?` + + var info dbindex.IndexInfo + var scannersJSON []byte + + err := s.db.QueryRow(query, path).Scan( + &info.Path, + &info.Source, + &info.Complexity, + &info.NumDirs, + &info.NumFiles, + &scannersJSON, + ) + + if err == sql.ErrNoRows { + return nil, errors.ErrNotExist + } + if err != nil { + return nil, fmt.Errorf("failed to get index info: %w", err) + } + + // Unmarshal scanners + if scannersJSON != nil { + if err := json.Unmarshal(scannersJSON, &info.Scanners); err != nil { + return nil, fmt.Errorf("failed to unmarshal scanners: %w", err) + } + } + + return &info, nil +} + +// GetIndexInfoBySource retrieves all index info for a source +func (s *SQLStore) GetIndexInfoBySource(source string) ([]*dbindex.IndexInfo, error) { + query := `SELECT path, source, complexity, num_dirs, num_files, scanners + FROM index_info WHERE source = ? ORDER BY path` + + rows, err := s.db.Query(query, source) + if err != nil { + return nil, fmt.Errorf("failed to get index info by source: %w", err) + } + defer rows.Close() + + return s.scanIndexInfo(rows) +} + +// ListAllIndexInfo retrieves all index info +func (s *SQLStore) ListAllIndexInfo() ([]*dbindex.IndexInfo, error) { + query := `SELECT path, source, complexity, num_dirs, num_files, scanners + FROM index_info ORDER BY path` + + rows, err := s.db.Query(query) + if err != nil { + return nil, fmt.Errorf("failed to list index info: %w", err) + } + defer rows.Close() + + return s.scanIndexInfo(rows) +} + +// SaveIndexInfo inserts or updates index info +func (s *SQLStore) SaveIndexInfo(info *dbindex.IndexInfo) error { + if s == nil || s.db == nil { + return fmt.Errorf("SQLStore not initialized") + } + + scannersJSON, err := json.Marshal(info.Scanners) + if err != nil { + return fmt.Errorf("failed to marshal scanners: %w", err) + } + + query := `INSERT OR REPLACE INTO index_info + (path, source, complexity, num_dirs, num_files, scanners) + VALUES (?, ?, ?, ?, ?, ?)` + + _, err = s.db.Exec(query, + info.Path, + info.Source, + info.Complexity, + info.NumDirs, + info.NumFiles, + scannersJSON, + ) + if err != nil { + return fmt.Errorf("failed to save index info: %w", err) + } + + return nil +} + +// DeleteIndexInfo deletes index info by path +func (s *SQLStore) DeleteIndexInfo(path string) error { + query := `DELETE FROM index_info WHERE path = ?` + result, err := s.db.Exec(query, path) + if err != nil { + return fmt.Errorf("failed to delete index info: %w", err) + } + + rowsAffected, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("failed to get rows affected: %w", err) + } + + if rowsAffected == 0 { + return errors.ErrNotExist + } + + return nil +} + +// DeleteIndexInfoBySource deletes all index info for a source +func (s *SQLStore) DeleteIndexInfoBySource(source string) error { + query := `DELETE FROM index_info WHERE source = ?` + _, err := s.db.Exec(query, source) + if err != nil { + return fmt.Errorf("failed to delete index info by source: %w", err) + } + return nil +} + +// scanIndexInfo is a helper to scan multiple index info rows +func (s *SQLStore) scanIndexInfo(rows *sql.Rows) ([]*dbindex.IndexInfo, error) { + var infoList []*dbindex.IndexInfo + for rows.Next() { + var info dbindex.IndexInfo + var scannersJSON []byte + + err := rows.Scan( + &info.Path, + &info.Source, + &info.Complexity, + &info.NumDirs, + &info.NumFiles, + &scannersJSON, + ) + if err != nil { + return nil, fmt.Errorf("failed to scan index info: %w", err) + } + + // Unmarshal scanners + if scannersJSON != nil { + if err := json.Unmarshal(scannersJSON, &info.Scanners); err != nil { + return nil, fmt.Errorf("failed to unmarshal scanners: %w", err) + } + } + + infoList = append(infoList, &info) + } + + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("error iterating index info: %w", err) + } + + return infoList, nil +} diff --git a/backend/internal/database/sqldb/migrations.go b/backend/internal/database/sqldb/migrations.go new file mode 100644 index 0000000000..fba71ff94f --- /dev/null +++ b/backend/internal/database/sqldb/migrations.go @@ -0,0 +1,198 @@ +package sqldb + +import ( + "database/sql" + "fmt" +) + +// currentSchemaVersion is the SQLite schema marker for this codebase (version 1). +// BoltDB has no schema_version; importing via cmd/migrate builds this SQLite shape directly. +const currentSchemaVersion = 1 + +// Schema creates all tables for the SQLite database +func createSchema(db *sql.DB) error { + schema := ` + -- Schema version tracking + CREATE TABLE IF NOT EXISTS schema_version ( + version INTEGER PRIMARY KEY, + updated_at INTEGER NOT NULL + ); + + -- Users: user_id is the primary key (stable identity); username is unique (one active login per name) + CREATE TABLE IF NOT EXISTS users ( + user_id TEXT PRIMARY KEY NOT NULL, + username TEXT NOT NULL UNIQUE, + perm_api INTEGER NOT NULL DEFAULT 0, + perm_admin INTEGER NOT NULL DEFAULT 0, + perm_realtime INTEGER NOT NULL DEFAULT 0, + user_data TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_users_admin ON users(perm_admin); + CREATE INDEX IF NOT EXISTS idx_users_api ON users(perm_api); + + -- Shares (owner is user_id) + CREATE TABLE IF NOT EXISTS shares ( + hash TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + source TEXT NOT NULL, + path TEXT NOT NULL, + expire INTEGER NOT NULL DEFAULT 0, + downloads INTEGER NOT NULL DEFAULT 0, + password_hash TEXT, + token TEXT, + user_downloads TEXT, + share_settings TEXT NOT NULL, + version INTEGER NOT NULL DEFAULT 0 + ); + CREATE INDEX IF NOT EXISTS idx_shares_user_id ON shares(user_id); + CREATE INDEX IF NOT EXISTS idx_shares_source ON shares(source); + CREATE INDEX IF NOT EXISTS idx_shares_path ON shares(path); + CREATE INDEX IF NOT EXISTS idx_shares_expire ON shares(expire); + CREATE INDEX IF NOT EXISTS idx_shares_source_path ON shares(source, path); + + -- Access rules table + CREATE TABLE IF NOT EXISTS access_rules ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + source TEXT NOT NULL, + path TEXT NOT NULL, + rule_data TEXT NOT NULL, + UNIQUE(source, path) + ); + CREATE INDEX IF NOT EXISTS idx_access_rules_source ON access_rules(source); + CREATE INDEX IF NOT EXISTS idx_access_rules_path ON access_rules(path); + CREATE INDEX IF NOT EXISTS idx_access_rules_source_path ON access_rules(source, path); + + -- Groups table + CREATE TABLE IF NOT EXISTS groups ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT UNIQUE NOT NULL, + members TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_groups_name ON groups(name); + + -- Revoked tokens table + CREATE TABLE IF NOT EXISTS revoked_tokens ( + token_hash TEXT PRIMARY KEY, + revoked_at INTEGER NOT NULL + ); + + -- Hashed tokens (minimal JWT → owner user_id) + CREATE TABLE IF NOT EXISTS hashed_tokens ( + token_hash TEXT PRIMARY KEY, + user_id TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_hashed_tokens_user_id ON hashed_tokens(user_id); + + -- Index info table + CREATE TABLE IF NOT EXISTS index_info ( + path TEXT PRIMARY KEY, + source TEXT NOT NULL, + complexity INTEGER NOT NULL DEFAULT 0, + num_dirs INTEGER NOT NULL DEFAULT 0, + num_files INTEGER NOT NULL DEFAULT 0, + scanners TEXT + ); + CREATE INDEX IF NOT EXISTS idx_index_info_source ON index_info(source); + + -- Auth methods table + CREATE TABLE IF NOT EXISTS auth_methods ( + type TEXT PRIMARY KEY, + config TEXT NOT NULL + ); + + -- Settings table + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + + -- Activity audit log (append-only; purged by retention policy) + CREATE TABLE IF NOT EXISTS activity_log ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created_at INTEGER NOT NULL, + user_id TEXT NOT NULL, + event_type TEXT NOT NULL, + source TEXT, + path TEXT, + target_path TEXT, + ip_address TEXT, + status INTEGER NOT NULL, + success INTEGER NOT NULL DEFAULT 1, + details TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_activity_created_at ON activity_log(created_at DESC); + CREATE INDEX IF NOT EXISTS idx_activity_user_created ON activity_log(user_id, created_at DESC); + CREATE INDEX IF NOT EXISTS idx_activity_event_created ON activity_log(event_type, created_at DESC); + CREATE INDEX IF NOT EXISTS idx_activity_user_event_created ON activity_log(user_id, event_type, created_at DESC); + ` + + _, err := db.Exec(schema) + if err != nil { + return fmt.Errorf("failed to create schema: %w", err) + } + + return nil +} + +// initializeSchemaVersion sets the initial schema version +func initializeSchemaVersion(db *sql.DB) error { + var count int + err := db.QueryRow("SELECT COUNT(*) FROM schema_version").Scan(&count) + if err != nil { + return fmt.Errorf("failed to check schema version: %w", err) + } + + if count == 0 { + _, err = db.Exec("INSERT INTO schema_version (version, updated_at) VALUES (?, ?)", + currentSchemaVersion, currentTimestamp()) + if err != nil { + return fmt.Errorf("failed to initialize schema version: %w", err) + } + } + + return nil +} + +// getSchemaVersion returns the current schema version from the database +func getSchemaVersion(db *sql.DB) (int, error) { + var version int + err := db.QueryRow("SELECT version FROM schema_version ORDER BY version DESC LIMIT 1").Scan(&version) + if err == sql.ErrNoRows { + return 0, nil + } + if err != nil { + return 0, fmt.Errorf("failed to get schema version: %w", err) + } + return version, nil +} + +func runMigrations(db *sql.DB, fromVersion int) error { + if fromVersion > currentSchemaVersion { + _, err := db.Exec("UPDATE schema_version SET version = ?, updated_at = ?", + currentSchemaVersion, currentTimestamp()) + if err != nil { + return fmt.Errorf("failed to normalize schema version: %w", err) + } + return nil + } + if fromVersion >= currentSchemaVersion { + return nil + } + + for v := fromVersion + 1; v <= currentSchemaVersion; v++ { + switch v { + case 1: + // Canonical schema is createSchema + Bolt import; no step migrations. + default: + return fmt.Errorf("unknown schema version: %d", v) + } + } + + _, err := db.Exec("UPDATE schema_version SET version = ?, updated_at = ?", + currentSchemaVersion, currentTimestamp()) + if err != nil { + return fmt.Errorf("failed to update schema version: %w", err) + } + + return nil +} diff --git a/backend/internal/database/sqldb/settings.go b/backend/internal/database/sqldb/settings.go new file mode 100644 index 0000000000..6d44e7a9cd --- /dev/null +++ b/backend/internal/database/sqldb/settings.go @@ -0,0 +1,88 @@ +package sqldb + +import ( + "database/sql" + "encoding/json" + "fmt" +) + +// Settings SQL operations + +// GetSetting retrieves a setting by key +func (s *SQLStore) GetSetting(key string) ([]byte, error) { + query := `SELECT value FROM settings WHERE key = ?` + + var value []byte + err := s.db.QueryRow(query, key).Scan(&value) + + if err == sql.ErrNoRows { + return nil, fmt.Errorf("setting not found: %s", key) + } + if err != nil { + return nil, fmt.Errorf("failed to get setting: %w", err) + } + + return value, nil +} + +// SaveSetting inserts or updates a setting +func (s *SQLStore) SaveSetting(key string, value interface{}) error { + valueJSON, err := json.Marshal(value) + if err != nil { + return fmt.Errorf("failed to marshal setting value: %w", err) + } + + query := `INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)` + _, err = s.db.Exec(query, key, valueJSON) + if err != nil { + return fmt.Errorf("failed to save setting: %w", err) + } + + return nil +} + +// DeleteSetting deletes a setting by key +func (s *SQLStore) DeleteSetting(key string) error { + query := `DELETE FROM settings WHERE key = ?` + result, err := s.db.Exec(query, key) + if err != nil { + return fmt.Errorf("failed to delete setting: %w", err) + } + + rowsAffected, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("failed to get rows affected: %w", err) + } + + if rowsAffected == 0 { + return fmt.Errorf("setting not found") + } + + return nil +} + +// GetAllSettings retrieves all settings as a map +func (s *SQLStore) GetAllSettings() (map[string][]byte, error) { + query := `SELECT key, value FROM settings` + rows, err := s.db.Query(query) + if err != nil { + return nil, fmt.Errorf("failed to get all settings: %w", err) + } + defer rows.Close() + + settings := make(map[string][]byte) + for rows.Next() { + var key string + var value []byte + if err := rows.Scan(&key, &value); err != nil { + return nil, fmt.Errorf("failed to scan setting: %w", err) + } + settings[key] = value + } + + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("error iterating settings: %w", err) + } + + return settings, nil +} diff --git a/backend/internal/database/sqldb/shares.go b/backend/internal/database/sqldb/shares.go new file mode 100644 index 0000000000..b247033d1c --- /dev/null +++ b/backend/internal/database/sqldb/shares.go @@ -0,0 +1,331 @@ +package sqldb + +import ( + "database/sql" + "encoding/json" + "fmt" + "strconv" + "time" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" +) + +func marshalShareSettings(link *share.Share) ([]byte, error) { + return json.Marshal(link.ShareSettings) +} + +func unmarshalShareSettings(data []byte, link *share.Share) error { + if len(data) == 0 { + return nil + } + return json.Unmarshal(data, &link.ShareSettings) +} + +func shareUserIDDB(id uint64) string { + return strconv.FormatUint(id, 10) +} + +func scanShareUserID(s string, dest *uint64) error { + if s == "" { + *dest = 0 + return nil + } + u, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return fmt.Errorf("parse share user_id: %w", err) + } + *dest = u + return nil +} + +// GetShareByHash retrieves a share by hash +func (s *SQLStore) GetShareByHash(hash string) (*share.Share, error) { + query := `SELECT hash, user_id, source, path, expire, downloads, + password_hash, token, user_downloads, share_settings, version + FROM shares WHERE hash = ?` + + var link share.Share + var userIDStr string + var userDownloadsJSON, shareSettingsJSON []byte + + err := s.db.QueryRow(query, hash).Scan( + &link.Hash, + &userIDStr, + &link.SourcePath, + &link.Path, + &link.Expire, + &link.Downloads, + &link.PasswordHash, + &link.Token, + &userDownloadsJSON, + &shareSettingsJSON, + &link.Version, + ) + + if err == sql.ErrNoRows { + return nil, fmt.Errorf("share not found") + } + if err != nil { + return nil, fmt.Errorf("failed to get share: %w", err) + } + if err := scanShareUserID(userIDStr, &link.UserID); err != nil { + return nil, err + } + + if userDownloadsJSON != nil { + if err := json.Unmarshal(userDownloadsJSON, &link.UserDownloads); err != nil { + return nil, fmt.Errorf("failed to unmarshal user downloads: %w", err) + } + } + if err := unmarshalShareSettings(shareSettingsJSON, &link); err != nil { + return nil, fmt.Errorf("failed to unmarshal share settings: %w", err) + } + + return &link, nil +} + +// GetSharesByUserID retrieves all non-expired shares for an owner user id. +func (s *SQLStore) GetSharesByUserID(userID uint64) ([]*share.Share, error) { + now := time.Now().Unix() + query := `SELECT hash, user_id, source, path, expire, downloads, + password_hash, token, user_downloads, share_settings, version + FROM shares WHERE user_id = ? AND (expire = 0 OR expire > ?) + ORDER BY path` + + rows, err := s.db.Query(query, shareUserIDDB(userID), now) + if err != nil { + return nil, fmt.Errorf("failed to get shares by user id: %w", err) + } + defer rows.Close() + + return s.scanShares(rows) +} + +// GetSharesBySourcePath retrieves shares for a specific source and path +func (s *SQLStore) GetSharesBySourcePath(source, path string) ([]*share.Share, error) { + query := `SELECT hash, user_id, source, path, expire, downloads, + password_hash, token, user_downloads, share_settings, version + FROM shares WHERE source = ? AND path = ? ORDER BY hash` + + rows, err := s.db.Query(query, source, path) + if err != nil { + return nil, fmt.Errorf("failed to get shares by source/path: %w", err) + } + defer rows.Close() + + return s.scanShares(rows) +} + +// GetSharesBySourcePathUser retrieves shares for a specific source, path, and owner user id. +func (s *SQLStore) GetSharesBySourcePathUser(source, path string, userID uint64) ([]*share.Share, error) { + now := time.Now().Unix() + query := `SELECT hash, user_id, source, path, expire, downloads, + password_hash, token, user_downloads, share_settings, version + FROM shares WHERE source = ? AND path = ? AND user_id = ? + AND (expire = 0 OR expire > ?) ORDER BY hash` + + rows, err := s.db.Query(query, source, path, shareUserIDDB(userID), now) + if err != nil { + return nil, fmt.Errorf("failed to get shares: %w", err) + } + defer rows.Close() + + return s.scanShares(rows) +} + +// GetPermanentShare retrieves a permanent share (expire = 0) for source, path, and owner. +func (s *SQLStore) GetPermanentShare(source, path string, userID uint64) (*share.Share, error) { + query := `SELECT hash, user_id, source, path, expire, downloads, + password_hash, token, user_downloads, share_settings, version + FROM shares WHERE source = ? AND path = ? AND user_id = ? AND expire = 0 + LIMIT 1` + + var link share.Share + var userIDStr string + var userDownloadsJSON, shareSettingsJSON []byte + + err := s.db.QueryRow(query, source, path, shareUserIDDB(userID)).Scan( + &link.Hash, + &userIDStr, + &link.SourcePath, + &link.Path, + &link.Expire, + &link.Downloads, + &link.PasswordHash, + &link.Token, + &userDownloadsJSON, + &shareSettingsJSON, + &link.Version, + ) + + if err == sql.ErrNoRows { + return nil, fmt.Errorf("permanent share not found") + } + if err != nil { + return nil, fmt.Errorf("failed to get permanent share: %w", err) + } + if err := scanShareUserID(userIDStr, &link.UserID); err != nil { + return nil, err + } + + if userDownloadsJSON != nil { + if err := json.Unmarshal(userDownloadsJSON, &link.UserDownloads); err != nil { + return nil, fmt.Errorf("failed to unmarshal user downloads: %w", err) + } + } + if err := unmarshalShareSettings(shareSettingsJSON, &link); err != nil { + return nil, fmt.Errorf("failed to unmarshal share settings: %w", err) + } + + return &link, nil +} + +// ListAllShares retrieves all non-expired shares +func (s *SQLStore) ListAllShares() ([]*share.Share, error) { + now := time.Now().Unix() + query := `SELECT hash, user_id, source, path, expire, downloads, + password_hash, token, user_downloads, share_settings, version + FROM shares WHERE expire = 0 OR expire > ? ORDER BY path` + + rows, err := s.db.Query(query, now) + if err != nil { + return nil, fmt.Errorf("failed to list shares: %w", err) + } + defer rows.Close() + + return s.scanShares(rows) +} + +// SaveShare inserts or updates a share +func (s *SQLStore) SaveShare(link *share.Share) error { + userDownloadsJSON, err := json.Marshal(link.UserDownloads) + if err != nil { + return fmt.Errorf("failed to marshal user downloads: %w", err) + } + shareSettingsJSON, err := marshalShareSettings(link) + if err != nil { + return fmt.Errorf("failed to marshal share settings: %w", err) + } + + query := `INSERT OR REPLACE INTO shares + (hash, user_id, source, path, expire, downloads, password_hash, + token, user_downloads, share_settings, version) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + + _, err = s.db.Exec(query, + link.Hash, + shareUserIDDB(link.UserID), + link.SourcePath, + link.Path, + link.Expire, + link.Downloads, + link.PasswordHash, + link.Token, + userDownloadsJSON, + shareSettingsJSON, + link.Version, + ) + if err != nil { + return fmt.Errorf("failed to save share: %w", err) + } + + return nil +} + +// DeleteShare deletes a share by hash +func (s *SQLStore) DeleteShare(hash string) error { + query := `DELETE FROM shares WHERE hash = ?` + result, err := s.db.Exec(query, hash) + if err != nil { + return fmt.Errorf("failed to delete share: %w", err) + } + + rowsAffected, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("failed to get rows affected: %w", err) + } + + if rowsAffected == 0 { + return fmt.Errorf("share not found") + } + + return nil +} + +// DeleteExpiredShares deletes all expired shares +func (s *SQLStore) DeleteExpiredShares() (int64, error) { + now := time.Now().Unix() + query := `DELETE FROM shares WHERE expire > 0 AND expire <= ?` + result, err := s.db.Exec(query, now) + if err != nil { + return 0, fmt.Errorf("failed to delete expired shares: %w", err) + } + + return result.RowsAffected() +} + +// UpdateSharePath updates the path for a specific share +func (s *SQLStore) UpdateSharePath(hash, newPath string) error { + query := `UPDATE shares SET path = ? WHERE hash = ?` + _, err := s.db.Exec(query, newPath, hash) + if err != nil { + return fmt.Errorf("failed to update share path: %w", err) + } + return nil +} + +// UpdateSharesPaths updates paths for shares when a resource is moved +func (s *SQLStore) UpdateSharesPaths(oldSource, oldPath, newSource, newPath string) error { + query := `UPDATE shares SET source = ?, path = ? WHERE source = ? AND path = ?` + _, err := s.db.Exec(query, newSource, newPath, oldSource, oldPath) + if err != nil { + return fmt.Errorf("failed to update shares paths: %w", err) + } + return nil +} + +func (s *SQLStore) scanShares(rows *sql.Rows) ([]*share.Share, error) { + var shares []*share.Share + for rows.Next() { + var link share.Share + var userIDStr string + var userDownloadsJSON, shareSettingsJSON []byte + + err := rows.Scan( + &link.Hash, + &userIDStr, + &link.SourcePath, + &link.Path, + &link.Expire, + &link.Downloads, + &link.PasswordHash, + &link.Token, + &userDownloadsJSON, + &shareSettingsJSON, + &link.Version, + ) + if err != nil { + return nil, fmt.Errorf("failed to scan share: %w", err) + } + if err := scanShareUserID(userIDStr, &link.UserID); err != nil { + return nil, err + } + + if userDownloadsJSON != nil { + if err := json.Unmarshal(userDownloadsJSON, &link.UserDownloads); err != nil { + return nil, fmt.Errorf("failed to unmarshal user downloads: %w", err) + } + } + if err := unmarshalShareSettings(shareSettingsJSON, &link); err != nil { + return nil, fmt.Errorf("failed to unmarshal share settings: %w", err) + } + + shares = append(shares, &link) + } + + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("error iterating shares: %w", err) + } + + return shares, nil +} diff --git a/backend/internal/database/sqldb/shares_test.go b/backend/internal/database/sqldb/shares_test.go new file mode 100644 index 0000000000..a117a51494 --- /dev/null +++ b/backend/internal/database/sqldb/shares_test.go @@ -0,0 +1,70 @@ +package sqldb + +import ( + "path/filepath" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" +) + +func TestUnmarshalShareSettingsEmpty(t *testing.T) { + link := &share.Share{} + if err := unmarshalShareSettings(nil, link); err != nil { + t.Fatalf("nil settings: %v", err) + } + if err := unmarshalShareSettings([]byte{}, link); err != nil { + t.Fatalf("empty settings: %v", err) + } +} + +func TestSaveSharePreservesShareLimits(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "shares.db") + store, _, err := NewSQLStore(dbPath) + if err != nil { + t.Fatalf("NewSQLStore: %v", err) + } + + original := &share.Share{ + ShareSettings: share.ShareSettings{ + ShareLimits: share.ShareLimits{ + SourceName: "default", + AllowedUsernames: []string{"alice", "bob"}, + DownloadsLimit: 5, + MaxBandwidth: 100, + PerUserDownloadLimit: true, + }, + }, + ShareColumns: share.ShareColumns{ + Hash: "test-hash-limits", + Path: "/docs/file.txt", + Expire: 0, + }, + SourcePath: "/data", + UserID: 1, + Version: 1, + } + + if err = store.SaveShare(original); err != nil { + t.Fatalf("SaveShare: %v", err) + } + + loaded, err := store.GetShareByHash("test-hash-limits") + if err != nil { + t.Fatalf("GetShareByHash: %v", err) + } + if loaded.SourceName != "default" { + t.Fatalf("SourceName = %q, want default", loaded.SourceName) + } + if len(loaded.AllowedUsernames) != 2 || loaded.AllowedUsernames[0] != "alice" || loaded.AllowedUsernames[1] != "bob" { + t.Fatalf("AllowedUsernames = %#v", loaded.AllowedUsernames) + } + if loaded.DownloadsLimit != 5 { + t.Fatalf("DownloadsLimit = %d, want 5", loaded.DownloadsLimit) + } + if loaded.MaxBandwidth != 100 { + t.Fatalf("MaxBandwidth = %d, want 100", loaded.MaxBandwidth) + } + if !loaded.PerUserDownloadLimit { + t.Fatal("expected PerUserDownloadLimit to be preserved") + } +} diff --git a/backend/internal/database/sqldb/sqldb.go b/backend/internal/database/sqldb/sqldb.go new file mode 100644 index 0000000000..d67734b77c --- /dev/null +++ b/backend/internal/database/sqldb/sqldb.go @@ -0,0 +1,123 @@ +package sqldb + +import ( + "database/sql" + "fmt" + "os" + "path/filepath" + "time" + + "github.com/gtsteffaniak/go-logger/logger" + // SQLite driver is imported in driver_cgo.go or driver_nocgo.go based on build tags +) + +// SQLStore provides access to the SQLite database +type SQLStore struct { + db *sql.DB +} + +// NewSQLStoreOpts configures NewSQLStoreWithOptions. +type NewSQLStoreOpts struct { + // SkipQuickSetup skips creating the default admin user. Use when users will be + SkipQuickSetup bool +} + +// NewSQLStore creates a new SQLStore and initializes the database +func NewSQLStore(dbPath string) (*SQLStore, bool, error) { + return NewSQLStoreWithOptions(dbPath, NewSQLStoreOpts{}) +} + +// NewSQLStoreWithOptions creates a new SQLStore with optional behavior (see NewSQLStoreOpts). +func NewSQLStoreWithOptions(dbPath string, opts NewSQLStoreOpts) (*SQLStore, bool, error) { + // Check if database exists BEFORE opening it + existingDb := dbExists(dbPath) + + // Ensure parent directory exists + dir := filepath.Dir(dbPath) + if err := os.MkdirAll(dir, 0755); err != nil { + return nil, existingDb, fmt.Errorf("failed to create database directory: %w", err) + } + + // Open SQLite database with the appropriate driver + db, err := sql.Open(SqliteDriver, fmt.Sprintf("file:%s?cache=shared&mode=rwc&_journal_mode=WAL", dbPath)) + if err != nil { + return nil, existingDb, fmt.Errorf("failed to open database: %w", err) + } + + // Configure connection pool + db.SetMaxOpenConns(25) + db.SetMaxIdleConns(5) + db.SetConnMaxLifetime(5 * time.Minute) + + // Enable foreign keys + _, err = db.Exec("PRAGMA foreign_keys = ON") + if err != nil { + db.Close() + return nil, existingDb, fmt.Errorf("failed to enable foreign keys: %w", err) + } + + // Create schema if needed + err = createSchema(db) + if err != nil { + db.Close() + return nil, existingDb, err + } + + // Initialize or check schema version + err = initializeSchemaVersion(db) + if err != nil { + db.Close() + return nil, existingDb, err + } + + // Run migrations if needed + version, err := getSchemaVersion(db) + if err != nil { + db.Close() + return nil, existingDb, err + } + + if version < currentSchemaVersion { + logger.Infof("Running database migrations from version %d to %d", version, currentSchemaVersion) + err = runMigrations(db, version) + if err != nil { + db.Close() + return nil, existingDb, err + } + } + + store := &SQLStore{db: db} + + logger.Debugf("SQLite database initialized at %s", dbPath) + + return store, existingDb, nil +} + +// Close closes the database connection +func (s *SQLStore) Close() error { + return s.db.Close() +} + +// DB returns the underlying *sql.DB for advanced operations +func (s *SQLStore) DB() *sql.DB { + return s.db +} + +// dbExists checks if a database file exists +func dbExists(path string) bool { + stat, err := os.Stat(path) + if err != nil { + return false + } + return stat.Size() > 0 +} + +// currentTimestamp returns the current Unix timestamp +func currentTimestamp() int64 { + return time.Now().Unix() +} + +// BeginTx starts a new transaction +func (s *SQLStore) BeginTx() (*sql.Tx, error) { + return s.db.Begin() +} diff --git a/backend/internal/database/sqldb/tokens.go b/backend/internal/database/sqldb/tokens.go new file mode 100644 index 0000000000..674a7fbbd2 --- /dev/null +++ b/backend/internal/database/sqldb/tokens.go @@ -0,0 +1,139 @@ +package sqldb + +import ( + "fmt" + "strconv" + "time" +) + +// SaveRevokedToken adds a token hash to the revoked tokens table +func (s *SQLStore) SaveRevokedToken(tokenHash string) error { + query := `INSERT OR IGNORE INTO revoked_tokens (token_hash, revoked_at) VALUES (?, ?)` + _, err := s.db.Exec(query, tokenHash, time.Now().Unix()) + if err != nil { + return fmt.Errorf("failed to save revoked token: %w", err) + } + return nil +} + +// IsTokenRevoked checks if a token hash is in the revoked tokens table +func (s *SQLStore) IsTokenRevoked(tokenHash string) (bool, error) { + query := `SELECT 1 FROM revoked_tokens WHERE token_hash = ?` + var exists int + err := s.db.QueryRow(query, tokenHash).Scan(&exists) + if err != nil { + if err.Error() == "sql: no rows in result set" { + return false, nil + } + return false, fmt.Errorf("failed to check revoked token: %w", err) + } + return true, nil +} + +// GetAllRevokedTokens retrieves all revoked token hashes +func (s *SQLStore) GetAllRevokedTokens() (map[string]struct{}, error) { + query := `SELECT token_hash FROM revoked_tokens` + rows, err := s.db.Query(query) + if err != nil { + return nil, fmt.Errorf("failed to get revoked tokens: %w", err) + } + defer rows.Close() + + revokedTokens := make(map[string]struct{}) + for rows.Next() { + var tokenHash string + if err := rows.Scan(&tokenHash); err != nil { + return nil, fmt.Errorf("failed to scan revoked token: %w", err) + } + revokedTokens[tokenHash] = struct{}{} + } + + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("error iterating revoked tokens: %w", err) + } + + return revokedTokens, nil +} + +// DeleteRevokedToken removes a token hash from the revoked tokens table +func (s *SQLStore) DeleteRevokedToken(tokenHash string) error { + query := `DELETE FROM revoked_tokens WHERE token_hash = ?` + _, err := s.db.Exec(query, tokenHash) + if err != nil { + return fmt.Errorf("failed to delete revoked token: %w", err) + } + return nil +} + +// SaveHashedToken saves a token hash to owner user_id mapping (decimal text). +func (s *SQLStore) SaveHashedToken(tokenHash string, userID uint64) error { + query := `INSERT OR REPLACE INTO hashed_tokens (token_hash, user_id) VALUES (?, ?)` + _, err := s.db.Exec(query, tokenHash, strconv.FormatUint(userID, 10)) + if err != nil { + return fmt.Errorf("failed to save hashed token: %w", err) + } + return nil +} + +// GetUserIDByTokenHash returns the owner user id for a token hash. +func (s *SQLStore) GetUserIDByTokenHash(tokenHash string) (uint64, error) { + query := `SELECT user_id FROM hashed_tokens WHERE token_hash = ?` + var idStr string + err := s.db.QueryRow(query, tokenHash).Scan(&idStr) + if err != nil { + if err.Error() == "sql: no rows in result set" { + return 0, fmt.Errorf("token not found") + } + return 0, fmt.Errorf("failed to get user id by token: %w", err) + } + return strconv.ParseUint(idStr, 10, 64) +} + +// GetAllHashedTokens retrieves all token hash → owner user_id mappings. +func (s *SQLStore) GetAllHashedTokens() (map[string]uint64, error) { + query := `SELECT token_hash, user_id FROM hashed_tokens` + rows, err := s.db.Query(query) + if err != nil { + return nil, fmt.Errorf("failed to get hashed tokens: %w", err) + } + defer rows.Close() + + hashedTokens := make(map[string]uint64) + for rows.Next() { + var tokenHash, idStr string + if err := rows.Scan(&tokenHash, &idStr); err != nil { + return nil, fmt.Errorf("failed to scan hashed token: %w", err) + } + uid, err := strconv.ParseUint(idStr, 10, 64) + if err != nil { + return nil, fmt.Errorf("invalid user_id in hashed_tokens: %w", err) + } + hashedTokens[tokenHash] = uid + } + + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("error iterating hashed tokens: %w", err) + } + + return hashedTokens, nil +} + +// DeleteHashedToken removes a token hash mapping +func (s *SQLStore) DeleteHashedToken(tokenHash string) error { + query := `DELETE FROM hashed_tokens WHERE token_hash = ?` + _, err := s.db.Exec(query, tokenHash) + if err != nil { + return fmt.Errorf("failed to delete hashed token: %w", err) + } + return nil +} + +// DeleteHashedTokensByUserID removes all token hashes for an owner user id. +func (s *SQLStore) DeleteHashedTokensByUserID(userID uint64) error { + query := `DELETE FROM hashed_tokens WHERE user_id = ?` + _, err := s.db.Exec(query, strconv.FormatUint(userID, 10)) + if err != nil { + return fmt.Errorf("failed to delete hashed tokens by user: %w", err) + } + return nil +} diff --git a/backend/internal/database/sqldb/users.go b/backend/internal/database/sqldb/users.go new file mode 100644 index 0000000000..7d26bd941a --- /dev/null +++ b/backend/internal/database/sqldb/users.go @@ -0,0 +1,416 @@ +package sqldb + +import ( + "database/sql" + "encoding/json" + "fmt" + "strconv" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +// User SQL operations + +// UserData holds all the non-queryable user fields in JSON +type UserData struct { + Password string `json:"password,omitempty"` + // BackendScopes: persisted source access (Name = backend path). JSON key "scopes" is historical on-disk. + BackendScopes []users.BackendScope `json:"backendScopes"` + Tokens map[string]users.AuthToken `json:"tokens,omitempty"` + TOTPSecret string `json:"totpSecret,omitempty"` + TOTPNonce string `json:"totpNonce,omitempty"` + LoginMethod users.LoginMethod `json:"loginMethod"` + OtpEnabled bool `json:"otpEnabled"` + Version int `json:"version"` + ShowFirstLogin bool `json:"showFirstLogin"` + PinnedItems users.PinnedItems `json:"pinnedItems,omitempty"` + Profile json.RawMessage `json:"profile,omitempty"` + Settings json.RawMessage `json:"settings,omitempty"` + BackendSourcePermissions map[string]users.SourceFilePermissions `json:"backendSourcePermissions,omitempty"` + Share bool `json:"share,omitempty"` + // FilePermissions is read only for v3 users pending startup migration to v4. + FilePermissions *users.Permissions `json:"filePermissions,omitempty"` +} + +func applyLegacyFilePermissionsFromJSON(user *users.User, data *UserData) { + if data.FilePermissions == nil { + return + } + fp := data.FilePermissions + user.Permissions.Modify = fp.Modify + user.Permissions.Share = fp.Share + user.Permissions.Delete = fp.Delete + user.Permissions.Create = fp.Create + user.Permissions.Download = fp.Download +} + +func applyProfileSettingsOverlay(user *users.User, settingsJSON json.RawMessage) error { + if user == nil || len(settingsJSON) == 0 || string(settingsJSON) == "null" { + return nil + } + var raw map[string]json.RawMessage + if err := json.Unmarshal(settingsJSON, &raw); err != nil { + return fmt.Errorf("parse profile settings overlay: %w", err) + } + if v, ok := raw["sidebarLinks"]; ok { + var links []users.SidebarLink + if err := json.Unmarshal(v, &links); err != nil { + return fmt.Errorf("parse sidebarLinks: %w", err) + } + user.SidebarLinks = links + } + if v, ok := raw["showFirstLogin"]; ok { + var showFirstLogin bool + if err := json.Unmarshal(v, &showFirstLogin); err != nil { + return fmt.Errorf("parse showFirstLogin: %w", err) + } + user.ShowFirstLogin = showFirstLogin + } + if v, ok := raw["passkeyCredentials"]; ok { + var creds []users.WebAuthnCredential + if err := json.Unmarshal(v, &creds); err != nil { + return fmt.Errorf("parse passkeyCredentials: %w", err) + } + user.PasskeyCredentials = creds + } + if v, ok := raw["sorting"]; ok { + var sorting users.Sorting + if err := json.Unmarshal(v, &sorting); err != nil { + return fmt.Errorf("parse sorting: %w", err) + } + user.Sorting = sorting + } + return nil +} + +func finishUserLoad(user *users.User, userDataJSON []byte) error { + var userData UserData + if err := json.Unmarshal(userDataJSON, &userData); err != nil { + return fmt.Errorf("failed to unmarshal user data: %w", err) + } + user.Password = userData.Password + user.BackendScopes = userData.BackendScopes + user.Tokens = userData.Tokens + users.IndexTokensForLookup(user.Tokens) + user.TOTPSecret = userData.TOTPSecret + user.TOTPNonce = userData.TOTPNonce + user.LoginMethod = userData.LoginMethod + user.OtpEnabled = userData.OtpEnabled + user.Version = userData.Version + user.ShowFirstLogin = userData.ShowFirstLogin + user.PinnedItems = userData.PinnedItems + user.BackendSourcePermissions = userData.BackendSourcePermissions + if len(userData.Profile) > 0 { + if err := settings.ApplyProfileToUser(user, userData.Profile); err != nil { + return fmt.Errorf("apply user profile: %w", err) + } + if err := applyProfileSettingsOverlay(user, userData.Settings); err != nil { + return err + } + } else if len(userData.Settings) > 0 { + var legacySettings users.NonAdminEditable + if err := json.Unmarshal(userData.Settings, &legacySettings); err != nil { + return fmt.Errorf("parse legacy settings: %w", err) + } + user.NonAdminEditable = legacySettings + } + if userData.Share { + user.Permissions.Share = true + } + if user.Version < users.SourcePermissionsMigrationVersion { + applyLegacyFilePermissionsFromJSON(user, &userData) + } + users.MergeLegacySourcePermissionsIntoScopes(user) + users.SyncBackendSourcePermissionsMap(user) + users.EnsureSourcePermissionsForScopes( + user, + settings.DefaultSourceFilePermissions(), + settings.AdminSourceFilePermissions(), + ) + return nil +} + +func userDataForPersist(user *users.User) UserData { + profileJSON, err := settings.ProfileJSONFromUser(user) + if err != nil { + profileJSON = nil + } + legacySettings := user.NonAdminEditable + var settingsJSON json.RawMessage + if user.Version >= users.ProfileStorageVersion { + legacySettings = users.NonAdminEditable{ + SidebarLinks: user.SidebarLinks, + ShowFirstLogin: user.ShowFirstLogin, + PasskeyCredentials: user.PasskeyCredentials, + Sorting: user.Sorting, + } + } + settingsJSON, err = json.Marshal(legacySettings) + if err != nil { + settingsJSON = nil + } + return UserData{ + Password: user.Password, + BackendScopes: user.BackendScopes, + Tokens: users.TokensForPersist(user.Tokens), + TOTPSecret: user.TOTPSecret, + TOTPNonce: user.TOTPNonce, + LoginMethod: user.LoginMethod, + OtpEnabled: user.OtpEnabled, + Version: user.Version, + ShowFirstLogin: user.ShowFirstLogin, + PinnedItems: user.PinnedItems, + Profile: profileJSON, + Settings: settingsJSON, + BackendSourcePermissions: user.BackendSourcePermissions, + Share: user.Permissions.Share, + } +} + +func scanUint64UserID(s string, dest *uint64) error { + if s == "" { + *dest = 0 + return nil + } + u, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return fmt.Errorf("parse user_id: %w", err) + } + *dest = u + return nil +} + +func userIDDBString(id uint64) string { + return strconv.FormatUint(id, 10) +} + +// GetUserByID retrieves a user by stable numeric id (JWT belongsTo, APIs). +func (s *SQLStore) GetUserByID(id uint64) (*users.User, error) { + if id == 0 { + return nil, fmt.Errorf("user not found") + } + query := `SELECT username, user_id, perm_api, perm_admin, perm_realtime, user_data + FROM users WHERE user_id = ?` + + var user users.User + var userDataJSON []byte + var idStr string + + err := s.db.QueryRow(query, userIDDBString(id)).Scan( + &user.Username, + &idStr, + &user.Permissions.Api, + &user.Permissions.Admin, + &user.Permissions.Realtime, + &userDataJSON, + ) + + if err == sql.ErrNoRows { + return nil, fmt.Errorf("user not found") + } + if err != nil { + return nil, fmt.Errorf("failed to get user: %w", err) + } + if err := scanUint64UserID(idStr, &user.ID); err != nil { + return nil, err + } + + if err := finishUserLoad(&user, userDataJSON); err != nil { + return nil, err + } + return &user, nil +} + +// GetUserByUsername retrieves a user by username +func (s *SQLStore) GetUserByUsername(username string) (*users.User, error) { + query := `SELECT username, user_id, perm_api, perm_admin, perm_realtime, user_data + FROM users WHERE username = ?` + + var user users.User + var userDataJSON []byte + var idStr string + + err := s.db.QueryRow(query, username).Scan( + &user.Username, + &idStr, + &user.Permissions.Api, + &user.Permissions.Admin, + &user.Permissions.Realtime, + &userDataJSON, + ) + + if err == sql.ErrNoRows { + return nil, fmt.Errorf("user not found") + } + if err != nil { + return nil, fmt.Errorf("failed to get user: %w", err) + } + if err := scanUint64UserID(idStr, &user.ID); err != nil { + return nil, err + } + + if err := finishUserLoad(&user, userDataJSON); err != nil { + return nil, err + } + return &user, nil +} + +// ListUsers retrieves all users +func (s *SQLStore) ListUsers() ([]*users.User, error) { + query := `SELECT username, user_id, perm_api, perm_admin, perm_realtime, user_data + FROM users ORDER BY username` + + rows, err := s.db.Query(query) + if err != nil { + return nil, fmt.Errorf("failed to list users: %w", err) + } + defer rows.Close() + + var usersList []*users.User + for rows.Next() { + var u users.User + var userDataJSON []byte + var idStr string + if err := rows.Scan( + &u.Username, + &idStr, + &u.Permissions.Api, + &u.Permissions.Admin, + &u.Permissions.Realtime, + &userDataJSON, + ); err != nil { + return nil, fmt.Errorf("failed to scan user: %w", err) + } + if err := scanUint64UserID(idStr, &u.ID); err != nil { + return nil, err + } + if err := finishUserLoad(&u, userDataJSON); err != nil { + return nil, err + } + usersList = append(usersList, &u) + } + + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("error iterating users: %w", err) + } + + return usersList, nil +} + +// CreateUser inserts a new user. user.ID must be non-zero (state.CreateUser and migration assign ids). +func (s *SQLStore) CreateUser(user *users.User) error { + if user.ID == 0 { + return fmt.Errorf("user id must be set before insert") + } + + userDataJSON, err := json.Marshal(userDataForPersist(user)) + if err != nil { + return fmt.Errorf("failed to marshal user data: %w", err) + } + + query := `INSERT INTO users (user_id, username, perm_api, perm_admin, perm_realtime, user_data) + VALUES (?, ?, ?, ?, ?, ?)` + + _, err = s.db.Exec(query, + userIDDBString(user.ID), + user.Username, + user.Permissions.Api, + user.Permissions.Admin, + user.Permissions.Realtime, + userDataJSON, + ) + if err != nil { + if err.Error() == "UNIQUE constraint failed: users.username" { + return fmt.Errorf("user with provided username already exists") + } + if err.Error() == "UNIQUE constraint failed: users.user_id" { + return fmt.Errorf("user with provided id already exists") + } + return fmt.Errorf("failed to insert user: %w", err) + } + + return nil +} + +// UpdateUser updates an existing user by username +func (s *SQLStore) UpdateUser(user *users.User) error { + userDataJSON, err := json.Marshal(userDataForPersist(user)) + if err != nil { + return fmt.Errorf("failed to marshal user data: %w", err) + } + + query := `UPDATE users SET username = ?, perm_api = ?, perm_admin = ?, + perm_realtime = ?, user_data = ? WHERE user_id = ?` + + result, err := s.db.Exec(query, + user.Username, + user.Permissions.Api, + user.Permissions.Admin, + user.Permissions.Realtime, + userDataJSON, + userIDDBString(user.ID), + ) + if err != nil { + return fmt.Errorf("failed to update user: %w", err) + } + + rowsAffected, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("failed to get rows affected: %w", err) + } + if rowsAffected == 0 { + return fmt.Errorf("user not found") + } + + return nil +} + +// UpdateUserUsername updates the row for user.ID, including a new username (oldName is unused; kept for callers). +func (s *SQLStore) UpdateUserUsername(oldName string, user *users.User) error { + _ = oldName + return s.UpdateUser(user) +} + +// DeleteUserByID deletes a user by stable id (non-zero only). +func (s *SQLStore) DeleteUserByID(id uint64) error { + if id == 0 { + return fmt.Errorf("user not found") + } + query := `DELETE FROM users WHERE user_id = ?` + result, err := s.db.Exec(query, userIDDBString(id)) + if err != nil { + return fmt.Errorf("failed to delete user: %w", err) + } + + rowsAffected, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("failed to get rows affected: %w", err) + } + + if rowsAffected == 0 { + return fmt.Errorf("user not found") + } + + return nil +} + +// DeleteUserByUsername deletes a user by username +func (s *SQLStore) DeleteUserByUsername(username string) error { + query := `DELETE FROM users WHERE username = ?` + result, err := s.db.Exec(query, username) + if err != nil { + return fmt.Errorf("failed to delete user: %w", err) + } + + rowsAffected, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("failed to get rows affected: %w", err) + } + + if rowsAffected == 0 { + return fmt.Errorf("user not found") + } + + return nil +} diff --git a/backend/internal/database/sqldb/users_test.go b/backend/internal/database/sqldb/users_test.go new file mode 100644 index 0000000000..389bb97725 --- /dev/null +++ b/backend/internal/database/sqldb/users_test.go @@ -0,0 +1,162 @@ +package sqldb + +import ( + "encoding/json" + "path/filepath" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func TestFinishUserLoad_legacyProfileRowPreservesAbsentSettingsFields(t *testing.T) { + userDataJSON := []byte(`{ + "backendScopes": [], + "loginMethod": "password", + "version": 5, + "showFirstLogin": true, + "profile": {"ui":{"darkMode":true}}, + "settings": {"darkMode": false} + }`) + + var loaded users.User + if err := finishUserLoad(&loaded, userDataJSON); err != nil { + t.Fatal(err) + } + if !loaded.ShowFirstLogin { + t.Fatal("expected top-level showFirstLogin to be preserved when settings omits it") + } + if !loaded.DarkMode { + t.Fatal("expected profile darkMode=true") + } + if len(loaded.PasskeyCredentials) != 0 { + t.Fatalf("expected no passkeys when settings omits passkeyCredentials, got %#v", loaded.PasskeyCredentials) + } + + withPasskeys := []byte(`{ + "backendScopes": [], + "loginMethod": "password", + "version": 5, + "showFirstLogin": true, + "profile": {"ui":{"darkMode":true}}, + "settings": {"passkeyCredentials":[{"id":"Y3JlZC0x"}]} + }`) + loaded = users.User{} + if err := finishUserLoad(&loaded, withPasskeys); err != nil { + t.Fatal(err) + } + if len(loaded.PasskeyCredentials) != 1 { + t.Fatalf("expected passkey from settings overlay, got %#v", loaded.PasskeyCredentials) + } + + explicitFalse := []byte(`{ + "backendScopes": [], + "loginMethod": "password", + "version": 5, + "showFirstLogin": true, + "profile": {"ui":{"darkMode":true}}, + "settings": {"showFirstLogin": false} + }`) + loaded = users.User{} + if err := finishUserLoad(&loaded, explicitFalse); err != nil { + t.Fatal(err) + } + if loaded.ShowFirstLogin { + t.Fatal("expected settings.showFirstLogin=false to override top-level true") + } + + explicitEmptySidebar := []byte(`{ + "backendScopes": [], + "loginMethod": "password", + "version": 5, + "profile": {"ui":{"darkMode":true}}, + "settings": {"sidebarLinks":[]} + }`) + loaded = users.User{FrontendUser: users.FrontendUser{NonAdminEditable: users.NonAdminEditable{ + SidebarLinks: []users.SidebarLink{{Name: "Docs", Target: "/docs"}}, + }}} + if err := finishUserLoad(&loaded, explicitEmptySidebar); err != nil { + t.Fatal(err) + } + if len(loaded.SidebarLinks) != 0 { + t.Fatalf("expected explicit empty sidebarLinks to clear links, got %#v", loaded.SidebarLinks) + } +} + +func TestUserDataRoundTrip_profileSettingsOverlay(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "users.db") + store, _, err := NewSQLStore(dbPath) + if err != nil { + t.Fatal(err) + } + + original := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "legacy-v5", + LoginMethod: users.LoginMethodPassword, + ShowFirstLogin: true, + NonAdminEditable: users.NonAdminEditable{ + DarkMode: true, + SidebarLinks: []users.SidebarLink{ + {Name: "Home", Target: "/files"}, + }, + Sorting: users.Sorting{By: "name", Asc: true}, + }, + }, + Version: users.ProfileStorageVersion, + PasskeyCredentials: []users.WebAuthnCredential{ + {ID: "pk-1"}, + }, + } + original.ID = 42 + + if err = store.CreateUser(original); err != nil { + t.Fatal(err) + } + + loaded, err := store.GetUserByUsername("legacy-v5") + if err != nil { + t.Fatal(err) + } + if !loaded.ShowFirstLogin { + t.Fatal("expected showFirstLogin preserved on round-trip") + } + if len(loaded.SidebarLinks) != 1 || loaded.SidebarLinks[0].Name != "Home" { + t.Fatalf("sidebarLinks=%#v", loaded.SidebarLinks) + } + if len(loaded.PasskeyCredentials) != 1 { + t.Fatalf("passkeyCredentials=%#v", loaded.PasskeyCredentials) + } + if loaded.Sorting.By != "name" || !loaded.Sorting.Asc { + t.Fatalf("sorting=%#v", loaded.Sorting) + } + + var persisted UserData + raw, err := json.Marshal(userDataForPersist(original)) + if err != nil { + t.Fatal(err) + } + if err = json.Unmarshal(raw, &persisted); err != nil { + t.Fatal(err) + } + + legacyMissingOverlay := UserData{ + BackendScopes: persisted.BackendScopes, + LoginMethod: persisted.LoginMethod, + Version: users.ProfileStorageVersion, + ShowFirstLogin: true, + Profile: persisted.Profile, + Settings: json.RawMessage(`{"darkMode":false}`), + } + legacyRaw, err := json.Marshal(legacyMissingOverlay) + if err != nil { + t.Fatal(err) + } + + var legacyLoaded users.User + if err = finishUserLoad(&legacyLoaded, legacyRaw); err != nil { + t.Fatal(err) + } + if !legacyLoaded.ShowFirstLogin { + t.Fatal("legacy row without settings overlay fields should keep top-level showFirstLogin") + } +} diff --git a/backend/internal/database/users/conversions.go b/backend/internal/database/users/conversions.go new file mode 100644 index 0000000000..a6ab40be83 --- /dev/null +++ b/backend/internal/database/users/conversions.go @@ -0,0 +1,216 @@ +package users + +import ( + "fmt" + "strings" +) + +// ResolveSourceKey maps a string that is either: +// - the configured source filesystem path (canonical Bolt / in-memory form for +// SourceScope.Name and source-type SidebarLink.SourceName), or +// - the source display name (JSON form from clients). +// +// Path is checked first so absolute paths are unambiguous. Used on write paths +// (normalize to Path) and read paths (normalize API to display Name). +func ResolveSourceKey(key string) (SourceInfo, bool) { + if sourceConfig == nil || key == "" { + return SourceInfo{}, false + } + if info, ok := sourceConfig.GetSourceByPath(key); ok { + return info, true + } + return sourceConfig.GetSourceByName(key) +} + +// GetSourceNames returns all source names the user has access to (assumes backend-style scopes) +func (u *User) GetSourceNames() []string { + if sourceConfig == nil { + return []string{} + } + + allSources := sourceConfig.GetAllSources() + sources := []string{} + // Preserves order of sources + for _, source := range allSources { + _, err := u.GetScopeForSourcePath(source.Path) + if err == nil { + sources = append(sources, source.Name) + } + } + return sources +} + +// APIScopesToBackend maps json "scopes" payloads (source display name or filesystem path + scope path + permissions). +// Omitted scope permissions become deny-all; callers must pre-fill defaults before conversion when needed. +func APIScopesToBackend(apiScopes []FrontendScope) ([]BackendScope, error) { + if len(apiScopes) == 0 { + return []BackendScope{}, nil + } + if sourceConfig == nil { + return nil, fmt.Errorf("source config not initialized") + } + + newScopes := []BackendScope{} + for _, scope := range apiScopes { + source, ok := ResolveSourceKey(scope.Name) + if !ok { + continue + } + if scope.Scope == "" { + scope.Scope = source.DefaultUserScope + } + scope.Scope = normalizeScope(scope.Scope) + newScopes = append(newScopes, BackendScope{ + Path: source.Path, + Scope: scope.Scope, + Permissions: frontendScopePermissions(scope), + }) + } + return newScopes, nil +} + +// GetFrontendScopes returns API-style scopes from BackendScopes (source display names + permissions). +func (u *User) GetFrontendScopes() []FrontendScope { + if sourceConfig == nil { + return []FrontendScope{} + } + + newScopes := []FrontendScope{} + for _, scope := range u.BackendScopes { + source, ok := sourceConfig.GetSourceByPath(scope.Path) + if !ok { + continue + } + perms := scope.Permissions + newScopes = append(newScopes, FrontendScope{ + Name: source.Name, + Scope: scope.Scope, + Permissions: &perms, + }) + } + return newScopes +} + +// GetBackendSidebarLinks normalizes source links for Bolt: SourceName is the filesystem path. +func (u *User) GetBackendSidebarLinks() ([]SidebarLink, error) { + if sourceConfig == nil { + return nil, fmt.Errorf("source config not initialized") + } + + newLinks := []SidebarLink{} + for _, link := range u.SidebarLinks { + if strings.HasPrefix(link.Category, "source") { + if link.SourceName == "" { + return nil, fmt.Errorf("source link missing sourceName (link name: %v)", link.Name) + } + // Validate source exists + sourceInfo, ok := sourceConfig.GetSourceByName(link.SourceName) + sourceInfo2, ok2 := sourceConfig.GetSourceByPath(link.SourceName) + if !ok && !ok2 { + return nil, fmt.Errorf("source not found: %v (link name: %v)", link.SourceName, link.Name) + } + if ok { + link.SourceName = sourceInfo.Path + } else { + link.SourceName = sourceInfo2.Path + } + } + newLinks = append(newLinks, link) + } + return newLinks, nil +} + +// normalizeScope ensures scope starts with / and doesn't end with / (except for root) +func normalizeScope(scope string) string { + if !strings.HasPrefix(scope, "/") { + scope = "/" + scope + } + if scope != "/" && strings.HasSuffix(scope, "/") { + scope = strings.TrimSuffix(scope, "/") + } + return scope +} + +// APISourcePermsToBackend maps API sourcePermissions (display name keys) to backend path keys. +func APISourcePermsToBackend(apiPerms map[string]SourceFilePermissions) (map[string]SourceFilePermissions, error) { + if len(apiPerms) == 0 { + return map[string]SourceFilePermissions{}, nil + } + if sourceConfig == nil { + return nil, fmt.Errorf("source config not initialized") + } + out := make(map[string]SourceFilePermissions, len(apiPerms)) + for key, perms := range apiPerms { + source, ok := ResolveSourceKey(key) + if !ok { + continue + } + out[source.Path] = perms + } + return out, nil +} + +// GetFrontendSourcePermissions returns API-style sourcePermissions from BackendSourcePermissions. +func (u *User) GetFrontendSourcePermissions() map[string]SourceFilePermissions { + if sourceConfig == nil || len(u.BackendSourcePermissions) == 0 { + return map[string]SourceFilePermissions{} + } + out := make(map[string]SourceFilePermissions, len(u.BackendSourcePermissions)) + for path, perms := range u.BackendSourcePermissions { + source, ok := sourceConfig.GetSourceByPath(path) + if !ok { + continue + } + out[source.Name] = perms + } + return out +} + +// FilePermsForSourcePath returns per-source file permissions for a backend source path. +func (u *User) FilePermsForSourcePath(sourcePath string) (SourceFilePermissions, bool) { + for _, scope := range u.BackendScopes { + if scope.Path == sourcePath { + perms := scope.Permissions + if perms.IsUnset() { + if u.BackendSourcePermissions != nil { + if legacy, ok := u.BackendSourcePermissions[sourcePath]; ok { + return legacy, true + } + } + } + return perms, true + } + } + if u.BackendSourcePermissions != nil { + perms, ok := u.BackendSourcePermissions[sourcePath] + return perms, ok + } + return DenyAllSourceFilePermissions(), false +} + +// FilePermsForSourceName resolves a source display name and returns per-source file permissions. +func (u *User) FilePermsForSourceName(sourceName string) (SourceFilePermissions, error) { + if sourceNameResolver == nil { + return DenyAllSourceFilePermissions(), fmt.Errorf("source name resolver not initialized") + } + sourcePath, err := sourceNameResolver(sourceName) + if err != nil { + return DenyAllSourceFilePermissions(), err + } + perms, ok := u.FilePermsForSourcePath(sourcePath) + if !ok { + return DenyAllSourceFilePermissions(), nil + } + return perms, nil +} + +// IntersectSourceFilePermissions returns the intersection of two SourceFilePermissions (token caps). +func IntersectSourceFilePermissions(a, b SourceFilePermissions) SourceFilePermissions { + return SourceFilePermissions{ + View: a.View && b.View, + Download: a.Download && b.Download, + Modify: a.Modify && b.Modify, + Delete: a.Delete && b.Delete, + Create: a.Create && b.Create, + } +} diff --git a/backend/internal/database/users/conversions_source_permissions_test.go b/backend/internal/database/users/conversions_source_permissions_test.go new file mode 100644 index 0000000000..c73008b74c --- /dev/null +++ b/backend/internal/database/users/conversions_source_permissions_test.go @@ -0,0 +1,59 @@ +package users + +import "testing" + +func TestAPISourcePermsToBackendAndFrontendRoundTrip(t *testing.T) { + had := SourceConfigLoaded() + t.Cleanup(func() { + if !had { + SetSourceConfig(nil) + SetSourceNameResolver(nil) + } + }) + SetSourceNameResolver(func(name string) (string, error) { + if name == "media" { + return "/vol/media", nil + } + return "", nil + }) + SetSourceConfig(&SourceConfigProvider{ + GetSourceByPath: func(path string) (SourceInfo, bool) { + if path == "/vol/media" { + return SourceInfo{Path: path, Name: "media"}, true + } + return SourceInfo{}, false + }, + GetSourceByName: func(name string) (SourceInfo, bool) { + if name == "media" { + return SourceInfo{Path: "/vol/media", Name: "media"}, true + } + return SourceInfo{}, false + }, + }) + + api := map[string]SourceFilePermissions{ + "media": {View: true, Download: true, Modify: false, Create: true, Delete: false}, + } + backend, err := APISourcePermsToBackend(api) + if err != nil { + t.Fatal(err) + } + if !backend["/vol/media"].View || !backend["/vol/media"].Create { + t.Fatalf("backend perms: %+v", backend) + } + + user := &User{ + BackendScopes: []BackendScope{{ + Path: "/vol/media", + Scope: "/", + Permissions: backend["/vol/media"], + }}, + } + front := user.GetFrontendScopes() + if len(front) != 1 || front[0].Permissions == nil { + t.Fatalf("frontend scopes: %+v", front) + } + if !front[0].Permissions.View || !front[0].Permissions.Create { + t.Fatalf("frontend perms: %+v", front[0].Permissions) + } +} diff --git a/backend/internal/database/users/migrate_source_permissions.go b/backend/internal/database/users/migrate_source_permissions.go new file mode 100644 index 0000000000..fd159f9784 --- /dev/null +++ b/backend/internal/database/users/migrate_source_permissions.go @@ -0,0 +1,47 @@ +package users + +// SourcePermissionsMigrationVersion is the user version after per-source file permissions migration. +const SourcePermissionsMigrationVersion = 4 + +// MigrateToSourcePermissions copies global file-operation permissions to each BackendScope source. +// Returns true if the user was modified. Idempotent when Version >= SourcePermissionsMigrationVersion. +func MigrateToSourcePermissions(user *User) bool { + if user.Version >= SourcePermissionsMigrationVersion { + return false + } + legacy := SourceFilePermissions{ + View: true, + Download: user.Permissions.Download, + Modify: user.Permissions.Modify, + Delete: user.Permissions.Delete, + Create: user.Permissions.Create, + } + for i, scope := range user.BackendScopes { + user.BackendScopes[i].Permissions = legacy + _ = scope + } + SyncBackendSourcePermissionsMap(user) + user.Permissions = GlobalPermissionsOnly(user.Permissions) + user.SourcePermissions = nil + user.Version = SourcePermissionsMigrationVersion + return true +} + +// SeedSourcePermissionsForPath adds default per-source permissions for a newly assigned source scope. +func SeedSourcePermissionsForPath(user *User, sourcePath string, defaults SourceFilePermissions) bool { + if user.Version < SourcePermissionsMigrationVersion { + return false + } + for i, scope := range user.BackendScopes { + if scope.Path != sourcePath { + continue + } + if !scope.Permissions.IsUnset() { + return false + } + user.BackendScopes[i].Permissions = defaults + SyncBackendSourcePermissionsMap(user) + return true + } + return false +} diff --git a/backend/internal/database/users/migrate_source_permissions_test.go b/backend/internal/database/users/migrate_source_permissions_test.go new file mode 100644 index 0000000000..f9f61d055a --- /dev/null +++ b/backend/internal/database/users/migrate_source_permissions_test.go @@ -0,0 +1,81 @@ +package users + +import "testing" + +func TestMigrateToSourcePermissions(t *testing.T) { + user := &User{ + FrontendUser: FrontendUser{ + Permissions: Permissions{ + Download: true, + Modify: true, + Delete: false, + Create: true, + Share: true, + }, + }, + BackendScopes: []BackendScope{{Path: "/data/a", Scope: "/"}}, + Version: 3, + } + if !MigrateToSourcePermissions(user) { + t.Fatal("expected migration to modify user") + } + if user.Version != SourcePermissionsMigrationVersion { + t.Fatalf("version = %d, want %d", user.Version, SourcePermissionsMigrationVersion) + } + perms := user.BackendScopes[0].Permissions + if !perms.View || !perms.Download || !perms.Modify || perms.Delete || !perms.Create { + t.Fatalf("unexpected perms: %+v", perms) + } + if user.Permissions.Download || user.Permissions.Modify || user.Permissions.Create { + t.Fatalf("global file ops should be cleared: %+v", user.Permissions) + } + if !user.Permissions.Share { + t.Fatal("global share should remain") + } + if MigrateToSourcePermissions(user) { + t.Fatal("second migration should be no-op") + } +} + +func TestSeedSourcePermissionsForPath(t *testing.T) { + user := &User{ + Version: SourcePermissionsMigrationVersion, + BackendScopes: []BackendScope{ + {Path: "/data/a", Scope: "/", Permissions: SourceFilePermissions{View: true}}, + }, + } + defaults := SourceFilePermissions{View: true, Download: true} + if SeedSourcePermissionsForPath(user, "/data/a", defaults) { + t.Fatal("should not overwrite existing perms") + } + user.BackendScopes = append(user.BackendScopes, BackendScope{Path: "/data/b", Scope: "/"}) + if !SeedSourcePermissionsForPath(user, "/data/b", defaults) { + t.Fatal("expected seed for new source") + } + found := false + for _, scope := range user.BackendScopes { + if scope.Path == "/data/b" && scope.Permissions.Download { + found = true + } + } + if !found { + t.Fatal("expected defaults applied on new scope path") + } +} + +func TestMigrateToSourcePermissions_viewTrueWhenLegacyDownloadOnly(t *testing.T) { + user := &User{ + FrontendUser: FrontendUser{ + Permissions: Permissions{Download: true, Share: true}, + }, + BackendScopes: []BackendScope{{Path: "/data", Scope: "/"}}, + Version: 2, + } + if !MigrateToSourcePermissions(user) { + t.Fatal("expected migration") + } + p := user.BackendScopes[0].Permissions + if !p.View || !p.Download || p.Modify { + t.Fatalf("unexpected perms: %+v", p) + } +} diff --git a/backend/database/users/nonadmin_test.go b/backend/internal/database/users/nonadmin_test.go similarity index 63% rename from backend/database/users/nonadmin_test.go rename to backend/internal/database/users/nonadmin_test.go index 2854e60280..6f7af10280 100644 --- a/backend/database/users/nonadmin_test.go +++ b/backend/internal/database/users/nonadmin_test.go @@ -5,47 +5,40 @@ import ( "testing" ) -func TestNonAdminEditableContainsOtpEnabled(t *testing.T) { - // Test that OtpEnabled is included in NonAdminEditable struct - structType := reflect.TypeOf(NonAdminEditable{}) +func TestFrontendUserContainsOtpEnabled(t *testing.T) { + structType := reflect.TypeOf(FrontendUser{}) - // Check if OtpEnabled field exists otpEnabledField, exists := structType.FieldByName("OtpEnabled") if !exists { - t.Fatal("OtpEnabled field should exist in NonAdminEditable struct") + t.Fatal("OtpEnabled field should exist on FrontendUser") } - // Check the JSON tag expectedTag := "otpEnabled" if otpEnabledField.Tag.Get("json") != expectedTag { t.Errorf("Expected JSON tag '%s', got '%s'", expectedTag, otpEnabledField.Tag.Get("json")) } - // Check the field type if otpEnabledField.Type.Kind() != reflect.Bool { t.Errorf("Expected OtpEnabled to be bool, got %s", otpEnabledField.Type.Kind()) } } +func TestNonAdminEditableDoesNotDuplicateOtpEnabled(t *testing.T) { + structType := reflect.TypeOf(NonAdminEditable{}) + if _, exists := structType.FieldByName("OtpEnabled"); exists { + t.Fatal("OtpEnabled should not be duplicated on NonAdminEditable") + } +} + func TestGetNonAdminEditableFieldNames(t *testing.T) { - // This is a helper function that should be tested - // We'll test it indirectly by checking if OtpEnabled is in the list names := getNonAdminEditableFieldNames() - // Check that OtpEnabled is in the list - found := false for _, name := range names { if name == "OtpEnabled" { - found = true - break + t.Error("OtpEnabled should not be in NonAdminEditable field names") } } - if !found { - t.Error("OtpEnabled should be in the list of non-admin editable field names") - } - - // Check that some other expected fields are present expectedFields := []string{"DarkMode", "Locale", "ViewMode", "SingleClick"} for _, expected := range expectedFields { found := false @@ -61,7 +54,6 @@ func TestGetNonAdminEditableFieldNames(t *testing.T) { } } -// Helper function to get field names (copied from bolt/users.go for testing) func getNonAdminEditableFieldNames() []string { var names []string t := reflect.TypeOf(NonAdminEditable{}) diff --git a/backend/internal/database/users/permissions_test.go b/backend/internal/database/users/permissions_test.go new file mode 100644 index 0000000000..a891a6b9b7 --- /dev/null +++ b/backend/internal/database/users/permissions_test.go @@ -0,0 +1,38 @@ +package users + +import "testing" + +func TestSourceFilePermissionsIsUnset(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + perms SourceFilePermissions + unset bool + }{ + {name: "all false", perms: SourceFilePermissions{}, unset: true}, + {name: "configured deny-all", perms: DenyAllSourceFilePermissions(), unset: false}, + {name: "view only", perms: SourceFilePermissions{View: true}, unset: false}, + {name: "download only", perms: SourceFilePermissions{Download: true}, unset: false}, + {name: "full", perms: SourceFilePermissions{View: true, Download: true, Modify: true, Create: true, Delete: true}, unset: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.perms.IsUnset(); got != tt.unset { + t.Fatalf("IsUnset() = %v, want %v", got, tt.unset) + } + }) + } +} + +func TestPermissionsHasAnyFilePermission(t *testing.T) { + t.Parallel() + + if (Permissions{}).HasAnyFilePermission() { + t.Fatal("expected empty permissions to have no file caps") + } + if !(Permissions{View: true}).HasAnyFilePermission() { + t.Fatal("expected view to count as file cap") + } +} diff --git a/backend/database/users/pinned_items.go b/backend/internal/database/users/pinned_items.go similarity index 100% rename from backend/database/users/pinned_items.go rename to backend/internal/database/users/pinned_items.go diff --git a/backend/database/users/pinned_items_test.go b/backend/internal/database/users/pinned_items_test.go similarity index 94% rename from backend/database/users/pinned_items_test.go rename to backend/internal/database/users/pinned_items_test.go index f7c8ba118b..4e629cf2c4 100644 --- a/backend/database/users/pinned_items_test.go +++ b/backend/internal/database/users/pinned_items_test.go @@ -26,11 +26,9 @@ func TestPinnedItemsAddRemove(t *testing.T) { func TestPinnedNamesForDirectory(t *testing.T) { u := &User{ - NonAdminEditable: NonAdminEditable{ - PinnedItems: PinnedItems{ - "/data/files": { - "/photos/": {"vacation.jpg", "notes.txt"}, - }, + PinnedItems: PinnedItems{ + "/data/files": { + "/photos/": {"vacation.jpg", "notes.txt"}, }, }, } diff --git a/backend/internal/database/users/repair_source_permissions.go b/backend/internal/database/users/repair_source_permissions.go new file mode 100644 index 0000000000..5647a12f94 --- /dev/null +++ b/backend/internal/database/users/repair_source_permissions.go @@ -0,0 +1,49 @@ +package users + +// EnsureSourcePermissionsForScopes repairs per-source permissions on each BackendScope. +// Re-keys legacy map/name entries and seeds missing scopes. +// Returns true if the user was modified. +func EnsureSourcePermissionsForScopes(user *User, defaults, adminDefaults SourceFilePermissions) bool { + if user.Version < SourcePermissionsMigrationVersion { + return false + } + changed := MergeLegacySourcePermissionsIntoScopes(user) + seed := defaults + if user.Permissions.Admin { + seed = adminDefaults + } + if sourceConfig != nil { + for key, perms := range user.BackendSourcePermissions { + source, ok := sourceConfig.GetSourceByName(key) + if !ok { + continue + } + if _, atPath := user.BackendSourcePermissions[source.Path]; atPath && key == source.Path { + continue + } + if user.BackendSourcePermissions == nil { + user.BackendSourcePermissions = make(map[string]SourceFilePermissions) + } + user.BackendSourcePermissions[source.Path] = perms + if key != source.Path { + delete(user.BackendSourcePermissions, key) + } + changed = true + } + } + for i, scope := range user.BackendScopes { + if !scope.Permissions.IsUnset() { + continue + } + if legacy, ok := user.BackendSourcePermissions[scope.Path]; ok { + user.BackendScopes[i].Permissions = legacy + } else { + user.BackendScopes[i].Permissions = seed + } + changed = true + } + if changed { + SyncBackendSourcePermissionsMap(user) + } + return changed +} diff --git a/backend/internal/database/users/repair_source_permissions_test.go b/backend/internal/database/users/repair_source_permissions_test.go new file mode 100644 index 0000000000..a44f586ec8 --- /dev/null +++ b/backend/internal/database/users/repair_source_permissions_test.go @@ -0,0 +1,97 @@ +package users + +import "testing" + +func TestEnsureSourcePermissionsForScopes_seedsMissingPaths(t *testing.T) { + user := &User{ + Version: SourcePermissionsMigrationVersion, + BackendScopes: []BackendScope{ + {Path: "/data/a", Scope: "/"}, + {Path: "/data/b", Scope: "/"}, + }, + } + defaults := SourceFilePermissions{View: true, Download: true} + adminDefaults := AdminSourceFilePermissionsForTest() + + if !EnsureSourcePermissionsForScopes(user, defaults, adminDefaults) { + t.Fatal("expected repair to seed missing permissions") + } + if !user.BackendSourcePermissions["/data/a"].View { + t.Fatal("expected view on /data/a") + } + if !user.BackendSourcePermissions["/data/b"].View { + t.Fatal("expected view on /data/b") + } +} + +func TestEnsureSourcePermissionsForScopes_rekeysSourceName(t *testing.T) { + had := SourceConfigLoaded() + t.Cleanup(func() { + if !had { + SetSourceConfig(nil) + } + }) + SetSourceConfig(&SourceConfigProvider{ + GetSourceByPath: func(path string) (SourceInfo, bool) { + if path == "/Users/dl" { + return SourceInfo{Path: path, Name: "Downloads"}, true + } + return SourceInfo{}, false + }, + GetSourceByName: func(name string) (SourceInfo, bool) { + if name == "Downloads" { + return SourceInfo{Path: "/Users/dl", Name: "Downloads"}, true + } + return SourceInfo{}, false + }, + }) + + user := &User{ + Version: SourcePermissionsMigrationVersion, + BackendScopes: []BackendScope{ + {Path: "/Users/dl", Scope: "/"}, + }, + BackendSourcePermissions: map[string]SourceFilePermissions{ + "Downloads": {View: true, Download: true, Modify: true}, + }, + } + defaults := SourceFilePermissions{View: true} + adminDefaults := AdminSourceFilePermissionsForTest() + + if !EnsureSourcePermissionsForScopes(user, defaults, adminDefaults) { + t.Fatal("expected rekey to change user") + } + perms := user.BackendScopes[0].Permissions + if !perms.Modify { + t.Fatal("expected modify preserved after rekey") + } + if _, stale := user.BackendSourcePermissions["Downloads"]; stale { + t.Fatal("expected stale name key removed") + } +} + +func TestEnsureSourcePermissionsForScopes_adminGetsFullPerms(t *testing.T) { + user := &User{ + Version: SourcePermissionsMigrationVersion, + FrontendUser: FrontendUser{ + Permissions: Permissions{Admin: true}, + }, + BackendScopes: []BackendScope{ + {Path: "/data/a", Scope: "/"}, + }, + } + defaults := SourceFilePermissions{View: true, Download: false, Modify: false} + adminDefaults := AdminSourceFilePermissionsForTest() + + EnsureSourcePermissionsForScopes(user, defaults, adminDefaults) + perms := user.BackendSourcePermissions["/data/a"] + if !perms.View || !perms.Download || !perms.Modify || !perms.Create || !perms.Delete { + t.Fatalf("admin seed = %+v, want full perms", perms) + } +} + +func AdminSourceFilePermissionsForTest() SourceFilePermissions { + return SourceFilePermissions{ + View: true, Download: true, Modify: true, Create: true, Delete: true, + } +} diff --git a/backend/internal/database/users/scope_permissions.go b/backend/internal/database/users/scope_permissions.go new file mode 100644 index 0000000000..5ce16a6bcb --- /dev/null +++ b/backend/internal/database/users/scope_permissions.go @@ -0,0 +1,68 @@ +package users + +// GlobalPermissionsOnly returns API-facing global permissions (admin, api, share, realtime). +func GlobalPermissionsOnly(p Permissions) Permissions { + return Permissions{ + Admin: p.Admin, + Api: p.Api, + Share: p.Share, + Realtime: p.Realtime, + } +} + +func frontendScopePermissions(fs FrontendScope) SourceFilePermissions { + if fs.Permissions == nil { + return DenyAllSourceFilePermissions() + } + return *fs.Permissions +} + +// MergeLegacySourcePermissionsIntoScopes copies deprecated sourcePermissions / backendSourcePermissions +// into BackendScopes[].Permissions when scopes lack file permissions. +func MergeLegacySourcePermissionsIntoScopes(user *User) bool { + if user == nil { + return false + } + changed := false + legacyByPath := user.BackendSourcePermissions + if legacyByPath == nil { + legacyByPath = make(map[string]SourceFilePermissions) + } + if sourceConfig != nil && len(user.SourcePermissions) > 0 { + for key, perms := range user.SourcePermissions { + source, ok := ResolveSourceKey(key) + if !ok { + continue + } + if _, exists := legacyByPath[source.Path]; !exists { + legacyByPath[source.Path] = perms + changed = true + } + } + } + for i, scope := range user.BackendScopes { + if !scope.Permissions.IsUnset() { + continue + } + if legacy, ok := legacyByPath[scope.Path]; ok { + user.BackendScopes[i].Permissions = legacy + changed = true + } + } + if changed { + SyncBackendSourcePermissionsMap(user) + } + return changed +} + +// SyncBackendSourcePermissionsMap rebuilds the legacy path-keyed map from scope permissions. +func SyncBackendSourcePermissionsMap(user *User) { + if user == nil { + return + } + m := make(map[string]SourceFilePermissions, len(user.BackendScopes)) + for _, scope := range user.BackendScopes { + m[scope.Path] = scope.Permissions + } + user.BackendSourcePermissions = m +} diff --git a/backend/internal/database/users/sidebar_link.go b/backend/internal/database/users/sidebar_link.go new file mode 100644 index 0000000000..14913cf098 --- /dev/null +++ b/backend/internal/database/users/sidebar_link.go @@ -0,0 +1,38 @@ +package users + +import "strings" + +// SidebarLinkCategory identifies sidebar link presentation types. +type SidebarLinkCategory string + +const ( + SidebarLinkSource SidebarLinkCategory = "source" + SidebarLinkSourceMinimal SidebarLinkCategory = "source-minimal" + SidebarLinkSourceAlt SidebarLinkCategory = "source-alt" + SidebarLinkSourceHybrid SidebarLinkCategory = "source-hybrid" + SidebarLinkSourceHybrid2 SidebarLinkCategory = "source-hybrid-2" + SidebarLinkTool SidebarLinkCategory = "tool" + SidebarLinkCustom SidebarLinkCategory = "custom" +) + +// NormalizeSidebarLinkCategory returns a known category string, preserving source-* variants. +func NormalizeSidebarLinkCategory(category string) string { + c := strings.TrimSpace(category) + if c == "" { + return string(SidebarLinkSource) + } + switch SidebarLinkCategory(c) { + case SidebarLinkSource, SidebarLinkSourceMinimal, SidebarLinkSourceAlt, + SidebarLinkSourceHybrid, SidebarLinkSourceHybrid2, SidebarLinkTool, SidebarLinkCustom: + return c + } + if strings.HasPrefix(c, "source") { + return c + } + return c +} + +// IsSourceSidebarCategory reports whether the category is a source-style sidebar link. +func IsSourceSidebarCategory(category string) bool { + return strings.HasPrefix(NormalizeSidebarLinkCategory(category), "source") +} diff --git a/backend/database/users/storage.go b/backend/internal/database/users/storage.go similarity index 53% rename from backend/database/users/storage.go rename to backend/internal/database/users/storage.go index 7642a78d3b..d84fb4fdcd 100644 --- a/backend/database/users/storage.go +++ b/backend/internal/database/users/storage.go @@ -1,33 +1,51 @@ package users import ( + "fmt" "sync" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/database/crud" + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/crud" ) // StorageBackend is the interface to implement for a users storage. +// All lookups and deletes use stable numeric user ids. type StorageBackend interface { - GetBy(interface{}) (*User, error) + GetBy(id uint64) (*User, error) Gets() ([]*User, error) Save(u *User, changePass bool, disableScopeChange bool) error Update(u *User, adminActor bool, fields ...string) error - DeleteByID(uint) error - DeleteByUsername(string) error + DeleteByID(id uint64) error } // Store is an interface for user storage. type Store interface { - Get(id interface{}) (user *User, err error) + Get(id uint64) (user *User, err error) Gets() ([]*User, error) Update(user *User, adminActor bool, fields ...string) error Save(user *User, changePass bool, disableScopeChange bool) error - Delete(id interface{}) error - LastUpdate(id uint) int64 - AddApiToken(userID uint, name string, tokenString string, metadata AuthToken) error - DeleteApiToken(userID uint, name string) error + Delete(id uint64) error + LastUpdate(id uint64) int64 + AddApiToken(userID uint64, name string, tokenString string, metadata AuthToken) error + DeleteApiToken(userID uint64, name string) error +} + +// usernameToID is set from state (or tests) so packages like auth can resolve +// login names to ids without importing state (avoids import cycles). +var usernameToID func(string) (uint64, error) + +// SetUsernameToID registers login name → stable id resolution. Call from state.Initialize after users load. +func SetUsernameToID(fn func(string) (uint64, error)) { + usernameToID = fn +} + +// ResolveUsernameToID maps a login name to stable user id using the resolver from SetUsernameToID. +func ResolveUsernameToID(username string) (uint64, error) { + if usernameToID == nil { + return 0, fmt.Errorf("users: login name resolver not configured") + } + return usernameToID(username) } // crudBackend implements crud.CrudBackend[User] for users storage. @@ -37,8 +55,16 @@ type crudBackend struct { func (c *crudBackend) GetByID(id any) (*User, error) { switch v := id.(type) { - case string, uint: + case uint64: + if v == 0 { + return nil, errors.ErrNotExist + } return c.back.GetBy(v) + case uint: + if v == 0 { + return nil, errors.ErrNotExist + } + return c.back.GetBy(uint64(v)) default: return nil, errors.ErrInvalidDataType } @@ -55,10 +81,10 @@ func (c *crudBackend) Save(obj *User) error { func (c *crudBackend) DeleteByID(id any) error { switch v := id.(type) { - case string: - return c.back.DeleteByUsername(v) - case uint: + case uint64: return c.back.DeleteByID(v) + case uint: + return c.back.DeleteByID(uint64(v)) default: return errors.ErrInvalidDataType } @@ -68,7 +94,7 @@ func (c *crudBackend) DeleteByID(id any) error { type Storage struct { Generic *crud.Storage[User] back StorageBackend - updated map[uint]int64 + updated map[uint64]int64 mux sync.RWMutex } @@ -77,19 +103,16 @@ func NewStorage(back StorageBackend) *Storage { return &Storage{ Generic: crud.NewStorage[User](&crudBackend{back: back}), back: back, - updated: map[uint]int64{}, + updated: map[uint64]int64{}, } } -// Get allows you to get a user by its name or username. The provided -// id must be a string for username lookup or a uint for id lookup. If id -// is neither, a ErrInvalidDataType will be returned. -func (s *Storage) Get(id interface{}) (user *User, err error) { - user, err = s.back.GetBy(id) - if err != nil { - return +// Get returns a user by stable numeric id. +func (s *Storage) Get(id uint64) (user *User, err error) { + if id == 0 { + return nil, errors.ErrNotExist } - return user, err + return s.back.GetBy(id) } // Gets gets a list of all users. @@ -109,12 +132,14 @@ func (s *Storage) Update(user *User, adminIActor bool, fields ...string) error { } s.mux.Lock() - s.updated[user.ID] = time.Now().Unix() + if user.ID != 0 { + s.updated[user.ID] = time.Now().Unix() + } s.mux.Unlock() return nil } -func (s *Storage) AddApiToken(userID uint, name string, tokenString string, metadata AuthToken) error { +func (s *Storage) AddApiToken(userID uint64, name string, tokenString string, metadata AuthToken) error { user, err := s.Get(userID) if err != nil { return err @@ -123,8 +148,15 @@ func (s *Storage) AddApiToken(userID uint, name string, tokenString string, meta if user.Tokens == nil { user.Tokens = make(map[string]AuthToken) } + if existing, ok := user.Tokens[name]; ok && existing.Name != "" { + return fmt.Errorf("token with name %q already exists", name) + } + if existing, ok := user.Tokens[tokenString]; ok && existing.Name != name { + return fmt.Errorf("token value collides with an existing token key") + } + metadata.Name = name metadata.Token = tokenString - user.Tokens[name] = metadata + StoreToken(user.Tokens, metadata) err = s.Update(user, true, "Tokens") if err != nil { return err @@ -133,7 +165,7 @@ func (s *Storage) AddApiToken(userID uint, name string, tokenString string, meta return nil } -func (s *Storage) DeleteApiToken(userID uint, name string) error { +func (s *Storage) DeleteApiToken(userID uint64, name string) error { user, err := s.Get(userID) if err != nil { return err @@ -142,7 +174,7 @@ func (s *Storage) DeleteApiToken(userID uint, name string) error { if user.Tokens == nil { user.Tokens = make(map[string]AuthToken) } - delete(user.Tokens, name) + RemoveTokenByName(user.Tokens, name) err = s.Update(user, true, "Tokens") if err != nil { return err @@ -156,22 +188,16 @@ func (s *Storage) Save(user *User, changePass, disableScopeChange bool) error { return s.back.Save(user, changePass, disableScopeChange) } -// Delete allows you to delete a user by its name or username. The provided -// id must be a string for username lookup or a uint for id lookup. If id -// is neither, a ErrInvalidDataType will be returned. -func (s *Storage) Delete(id interface{}) error { - switch id := id.(type) { - case string: - return s.back.DeleteByUsername(id) - case uint: - return s.back.DeleteByID(id) - default: +// Delete removes a user by stable numeric id. +func (s *Storage) Delete(id uint64) error { + if id == 0 { return errors.ErrInvalidDataType } + return s.back.DeleteByID(id) } -// LastUpdate gets the timestamp for the last update of an user. -func (s *Storage) LastUpdate(id uint) int64 { +// LastUpdate gets the timestamp for the last update of a user by id. +func (s *Storage) LastUpdate(id uint64) int64 { s.mux.RLock() defer s.mux.RUnlock() if val, ok := s.updated[id]; ok { diff --git a/backend/internal/database/users/storage_test.go b/backend/internal/database/users/storage_test.go new file mode 100644 index 0000000000..0ab431a278 --- /dev/null +++ b/backend/internal/database/users/storage_test.go @@ -0,0 +1,108 @@ +package users + +import ( + "fmt" + "strings" + "testing" +) + +// Interface is implemented by storage +var _ Store = &Storage{} + +type mockStorageBackend struct { + users map[uint64]*User +} + +func (m *mockStorageBackend) GetBy(id uint64) (*User, error) { + user, ok := m.users[id] + if !ok { + return nil, fmt.Errorf("user not found: %d", id) + } + return user, nil +} + +func (m *mockStorageBackend) Gets() ([]*User, error) { + out := make([]*User, 0, len(m.users)) + for _, user := range m.users { + out = append(out, user) + } + return out, nil +} + +func (m *mockStorageBackend) Save(u *User, _changePass, _disableScopeChange bool) error { + m.users[u.ID] = u + return nil +} + +func (m *mockStorageBackend) Update(u *User, _adminActor bool, _fields ...string) error { + m.users[u.ID] = u + return nil +} + +func (m *mockStorageBackend) DeleteByID(id uint64) error { + delete(m.users, id) + return nil +} + +func newStorageWithUser(t *testing.T, tokens map[string]AuthToken) (*Storage, uint64) { + t.Helper() + const userID uint64 = 42 + backend := &mockStorageBackend{ + users: map[uint64]*User{ + userID: { + ID: userID, + FrontendUser: FrontendUser{ + Username: "alice", + }, + Tokens: tokens, + }, + }, + } + return NewStorage(backend), userID +} + +func TestAddApiTokenSuccess(t *testing.T) { + storage, userID := newStorageWithUser(t, nil) + + err := storage.AddApiToken(userID, "ci-key", "jwt-abc-123", AuthToken{}) + if err != nil { + t.Fatalf("AddApiToken: %v", err) + } + + user, err := storage.Get(userID) + if err != nil { + t.Fatalf("Get: %v", err) + } + name, ok := TokenNameByRaw(user.Tokens, "jwt-abc-123") + if !ok || name != "ci-key" { + t.Fatalf("TokenNameByRaw: got (%q, %v)", name, ok) + } +} + +func TestAddApiTokenRejectsDuplicateName(t *testing.T) { + tokens := make(map[string]AuthToken) + StoreToken(tokens, AuthToken{Name: "ci-key", Token: "jwt-existing"}) + storage, userID := newStorageWithUser(t, tokens) + + err := storage.AddApiToken(userID, "ci-key", "jwt-new", AuthToken{}) + if err == nil { + t.Fatal("expected name collision error") + } + if !strings.Contains(err.Error(), `token with name "ci-key" already exists`) { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestAddApiTokenRejectsTokenValueCollision(t *testing.T) { + tokens := make(map[string]AuthToken) + StoreToken(tokens, AuthToken{Name: "existing-key", Token: "jwt-shared"}) + storage, userID := newStorageWithUser(t, tokens) + + err := storage.AddApiToken(userID, "new-key", "jwt-shared", AuthToken{}) + if err == nil { + t.Fatal("expected token value collision error") + } + if !strings.Contains(err.Error(), "token value collides with an existing token key") { + t.Fatalf("unexpected error: %v", err) + } +} diff --git a/backend/internal/database/users/token_permissions.go b/backend/internal/database/users/token_permissions.go new file mode 100644 index 0000000000..f787cadcab --- /dev/null +++ b/backend/internal/database/users/token_permissions.go @@ -0,0 +1,30 @@ +package users + +// SanitizeTokenPermissions returns only global permission flags suitable for API token metadata and JWT claims. +func SanitizeTokenPermissions(p Permissions) Permissions { + return GlobalPermissionsOnly(p) +} + +// IntersectGlobalPermissions returns global flags present on both owner and token caps. +func IntersectGlobalPermissions(owner, caps Permissions) Permissions { + ownerGlobal := GlobalPermissionsOnly(owner) + capsGlobal := GlobalPermissionsOnly(caps) + return Permissions{ + Admin: ownerGlobal.Admin && capsGlobal.Admin, + Api: ownerGlobal.Api && capsGlobal.Api, + Share: ownerGlobal.Share && capsGlobal.Share, + Realtime: ownerGlobal.Realtime && capsGlobal.Realtime, + } +} + +// HasAnyGlobalPermission reports whether any global permission flag is set. +func HasAnyGlobalPermission(p Permissions) bool { + g := GlobalPermissionsOnly(p) + return g.Admin || g.Api || g.Share || g.Realtime +} + +// IsMinimalApiToken reports whether the token inherits the owner's globals at auth time +// rather than embedding its own global permission caps in the JWT. +func IsMinimalApiToken(t AuthToken) bool { + return t.BelongsTo == 0 || !HasAnyGlobalPermission(t.Permissions) +} diff --git a/backend/internal/database/users/token_permissions_test.go b/backend/internal/database/users/token_permissions_test.go new file mode 100644 index 0000000000..1ee319ed7e --- /dev/null +++ b/backend/internal/database/users/token_permissions_test.go @@ -0,0 +1,50 @@ +package users + +import "testing" + +func TestSanitizeTokenPermissionsStripsFileOps(t *testing.T) { + got := SanitizeTokenPermissions(Permissions{ + Admin: true, + Api: true, + Modify: true, + View: true, + Download: true, + }) + if got.Modify || got.View || got.Download || got.Create || got.Delete { + t.Fatalf("file ops should be stripped, got %#v", got) + } + if !got.Admin || !got.Api { + t.Fatalf("globals should remain, got %#v", got) + } +} + +func TestIntersectGlobalPermissions(t *testing.T) { + owner := Permissions{Admin: true, Api: true, Share: true, Realtime: false} + caps := Permissions{Admin: true, Api: false, Share: true, Realtime: true, Modify: true} + got := IntersectGlobalPermissions(owner, caps) + want := Permissions{Admin: true, Api: false, Share: true, Realtime: false} + if got != want { + t.Fatalf("got %#v, want %#v", got, want) + } +} + +func TestHasAnyGlobalPermission(t *testing.T) { + if HasAnyGlobalPermission(Permissions{Modify: true}) { + t.Fatal("file ops alone should not count as global") + } + if !HasAnyGlobalPermission(Permissions{Api: true}) { + t.Fatal("expected api to count as global") + } +} + +func TestIsMinimalApiToken(t *testing.T) { + if !IsMinimalApiToken(AuthToken{}) { + t.Fatal("empty token should be minimal") + } + if IsMinimalApiToken(AuthToken{BelongsTo: 1, Permissions: Permissions{Admin: true}}) { + t.Fatal("custom token with global caps should not be minimal") + } + if !IsMinimalApiToken(AuthToken{BelongsTo: 1, Permissions: Permissions{Modify: true}}) { + t.Fatal("token without global caps should be minimal") + } +} diff --git a/backend/internal/database/users/tokens.go b/backend/internal/database/users/tokens.go new file mode 100644 index 0000000000..d66732cffb --- /dev/null +++ b/backend/internal/database/users/tokens.go @@ -0,0 +1,84 @@ +package users + +// StoreToken indexes a token by both its display name and raw JWT string for O(1) lookup either way. +func StoreToken(tokens map[string]AuthToken, token AuthToken) { + if tokens == nil || token.Name == "" { + return + } + tokens[token.Name] = token + if token.Token != "" && token.Token != token.Name { + tokens[token.Token] = token + } +} + +// RemoveTokenByName deletes both the name key and raw-token key for a stored API token. +func RemoveTokenByName(tokens map[string]AuthToken, name string) { + if tokens == nil { + return + } + tok, ok := tokens[name] + if !ok { + return + } + delete(tokens, name) + if tok.Token != "" { + delete(tokens, tok.Token) + } +} + +// IndexTokensForLookup adds raw-token keys for tokens loaded from persistence (name-keyed only). +func IndexTokensForLookup(tokens map[string]AuthToken) { + if len(tokens) == 0 { + return + } + for key, tok := range tokens { + if key != tok.Name { + continue + } + if tok.Token != "" && tok.Token != key { + tokens[tok.Token] = tok + } + } +} + +// TokensForPersist returns only name-keyed entries suitable for JSON storage. +func TokensForPersist(tokens map[string]AuthToken) map[string]AuthToken { + if len(tokens) == 0 { + return nil + } + out := make(map[string]AuthToken) + for key, tok := range tokens { + if tok.Name != "" && key == tok.Name { + out[key] = tok + } + } + if len(out) == 0 { + return nil + } + return out +} + +// TokenNameByRaw returns the token name when raw matches a stored JWT key. +func TokenNameByRaw(tokens map[string]AuthToken, raw string) (string, bool) { + if tokens == nil || raw == "" { + return "", false + } + tok, ok := tokens[raw] + if !ok || tok.Name == "" { + return "", false + } + return tok.Name, true +} + +// EachNamedToken invokes fn for every token keyed by name (skips raw JWT alias keys). +func EachNamedToken(tokens map[string]AuthToken, fn func(name string, token AuthToken)) { + if tokens == nil || fn == nil { + return + } + for key, tok := range tokens { + if key != tok.Name { + continue + } + fn(key, tok) + } +} diff --git a/backend/internal/database/users/tokens_test.go b/backend/internal/database/users/tokens_test.go new file mode 100644 index 0000000000..5db38b3f02 --- /dev/null +++ b/backend/internal/database/users/tokens_test.go @@ -0,0 +1,55 @@ +package users + +import "testing" + +func TestStoreTokenDualKeys(t *testing.T) { + tokens := make(map[string]AuthToken) + tok := AuthToken{Name: "ci-key", Token: "jwt-abc-123"} + StoreToken(tokens, tok) + + if len(tokens) != 2 { + t.Fatalf("expected 2 map keys, got %d", len(tokens)) + } + if _, ok := tokens["ci-key"]; !ok { + t.Fatal("missing name key") + } + if _, ok := tokens["jwt-abc-123"]; !ok { + t.Fatal("missing raw token key") + } + + name, ok := TokenNameByRaw(tokens, "jwt-abc-123") + if !ok || name != "ci-key" { + t.Fatalf("TokenNameByRaw: got (%q, %v)", name, ok) + } +} + +func TestRemoveTokenByNameClearsBothKeys(t *testing.T) { + tokens := make(map[string]AuthToken) + StoreToken(tokens, AuthToken{Name: "a", Token: "raw-a"}) + RemoveTokenByName(tokens, "a") + if len(tokens) != 0 { + t.Fatalf("expected empty map, got %d entries", len(tokens)) + } +} + +func TestIndexTokensForLookup(t *testing.T) { + tokens := map[string]AuthToken{ + "my-key": {Name: "my-key", Token: "jwt-xyz"}, + } + IndexTokensForLookup(tokens) + if _, ok := tokens["jwt-xyz"]; !ok { + t.Fatal("expected raw key after index") + } +} + +func TestTokensForPersistStripsRawKeys(t *testing.T) { + tokens := make(map[string]AuthToken) + StoreToken(tokens, AuthToken{Name: "n", Token: "raw"}) + persisted := TokensForPersist(tokens) + if len(persisted) != 1 { + t.Fatalf("expected 1 persisted entry, got %d", len(persisted)) + } + if _, ok := persisted["raw"]; ok { + t.Fatal("raw token key should not be persisted") + } +} diff --git a/backend/internal/database/users/username_test.go b/backend/internal/database/users/username_test.go new file mode 100644 index 0000000000..eae806bcf0 --- /dev/null +++ b/backend/internal/database/users/username_test.go @@ -0,0 +1,23 @@ +package users + +import ( + "strings" + "testing" +) + +func TestValidateUsernameReserved(t *testing.T) { + cases := []string{"anonymous", "Anonymous", " ANONYMOUS "} + for _, username := range cases { + if err := ValidateUsername(username); err == nil { + t.Fatalf("expected reserved username error for %q", username) + } else if !strings.Contains(err.Error(), "reserved") { + t.Fatalf("unexpected error for %q: %v", username, err) + } + } +} + +func TestValidateUsernameAcceptsNormalName(t *testing.T) { + if err := ValidateUsername("alice"); err != nil { + t.Fatalf("expected valid username, got %v", err) + } +} diff --git a/backend/database/users/users.go b/backend/internal/database/users/users.go similarity index 66% rename from backend/database/users/users.go rename to backend/internal/database/users/users.go index 126a4e61e2..cd374d8cbc 100644 --- a/backend/database/users/users.go +++ b/backend/internal/database/users/users.go @@ -7,8 +7,11 @@ import ( jwt "github.com/golang-jwt/jwt/v4" ) +// ProfileStorageVersion is the user version after nested profile JSON in user_data. +const ProfileStorageVersion = 5 + // CurrentUserMigrationVersion is persisted for newly created accounts and after legacy migrations finish. -const CurrentUserMigrationVersion = 3 +const CurrentUserMigrationVersion = ProfileStorageVersion type LoginMethod string @@ -20,6 +23,25 @@ const ( LoginMethodJwt LoginMethod = "jwt" ) +// AnonymousUserName is the username for unauthenticated requests (user_id 0). +const AnonymousUserName = "anonymous" + +var reservedUsernames = map[string]struct{}{ + strings.ToLower(AnonymousUserName): {}, +} + +// ValidateUsername rejects empty and reserved login names. +func ValidateUsername(username string) error { + username = strings.TrimSpace(username) + if username == "" { + return fmt.Errorf("username is empty") + } + if _, reserved := reservedUsernames[strings.ToLower(username)]; reserved { + return fmt.Errorf("username %q is reserved", username) + } + return nil +} + // WebAuthnCredentialFlags mirrors the boolean flags from authenticator data. type WebAuthnCredentialFlags struct { UserPresent bool `json:"userPresent"` @@ -54,7 +76,8 @@ type AuthToken struct { Key string `json:"key,omitempty"` // for backward compatibility Token string `json:"token,omitempty"` Name string `json:"name,omitempty"` - BelongsTo uint `json:"belongsTo,omitempty"` + Username string `json:"username,omitempty"` + BelongsTo uint64 `json:"belongsTo,omitempty"` // numeric user id in JWT claims (bolt-era small ids still work) IssuedAt int64 `json:"issuedAt,omitempty"` ExpiresAt int64 `json:"expiresAt,omitempty"` Permissions Permissions `json:"Permissions,omitempty"` @@ -68,12 +91,47 @@ type MinimalAuthToken struct { type Permissions struct { Api bool `json:"api"` // allow api access Admin bool `json:"admin"` // allow admin access - Modify bool `json:"modify"` // allow modifying files + 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 - Delete bool `json:"delete"` // allow deleting files - Create bool `json:"create"` // allow creating or uploading files - Download bool `json:"download"` // allow downloading files + 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 + View bool `json:"view,omitempty"` // deprecated: legacy user migration only; not used for API tokens +} + +// 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) +} + +// MarkSourceFilePermissionsConfigured marks permissions as explicitly set (including deny-all). +func MarkSourceFilePermissionsConfigured(p SourceFilePermissions) SourceFilePermissions { + p.Configured = true + return p +} + +// DenyAllSourceFilePermissions returns a SourceFilePermissions with all flags false and Configured set. +func DenyAllSourceFilePermissions() SourceFilePermissions { + return MarkSourceFilePermissionsConfigured(SourceFilePermissions{}) +} + +// IsUnset reports whether no permission bit is set and the value was never explicitly configured. +func (p SourceFilePermissions) IsUnset() bool { + if p.Configured { + return false + } + return !p.View && !p.Download && !p.Modify && !p.Delete && !p.Create +} + +// HasAnyFilePermission reports whether any file-operation flag is set on token/global claims. +func (p Permissions) HasAnyFilePermission() bool { + return p.View || p.Download || p.Modify || p.Delete || p.Create } // SortingSettings represents the sorting settings. @@ -91,39 +149,60 @@ type Preview struct { Office bool `json:"office"` // show thumbnail preview image for office files PopUp bool `json:"popup"` // show larger popup preview when hovering over thumbnail AutoplayMedia bool `json:"autoplayMedia"` // autoplay media files in preview - DefaultMediaPlayer bool `json:"defaultMediaPlayer"` // disable html5 media player and use the default media player Folder bool `json:"folder"` // show thumbnail preview image for folder files Models bool `json:"models"` // show live thumbnails for 3D models files } -// source filesystem path -> index directory path -> pinned item names (unique within the directory) -type PinnedItems map[string]map[string][]string - -// User describes a persisted account. Scopes and source sidebar links store filesystem paths in Name/SourceName; -// JSON responses use display names only (see http prepForFrontend). -type User struct { +// FrontendUser holds fields safe to return from user APIs (embedded on User). +type FrontendUser struct { NonAdminEditable - DisableSettings bool `json:"disableSettings"` - ID uint `storm:"id,increment" json:"id"` - Username string `storm:"unique" json:"username"` - Scopes []SourceScope `json:"scopes"` - Scope string `json:"scope,omitempty"` - LockPassword bool `json:"lockPassword"` - Permissions Permissions `json:"permissions"` - ApiKeys map[string]AuthToken `json:"apiKeys,omitempty"` // deprecated: use Tokens instead - Tokens map[string]AuthToken `json:"tokens,omitempty"` - TOTPSecret string `json:"totpSecret,omitempty"` - TOTPNonce string `json:"totpNonce,omitempty"` - LoginMethod LoginMethod `json:"loginMethod"` - OtpEnabled bool `json:"otpEnabled"` // true if TOTP is enabled, false otherwise - Version int `json:"version"` - // legacy for migration purposes... og filebrowser has perm attribute - Perm Permissions `json:"perm,omitzero"` // deprecated: use Permissions instead + 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"` } -type SourceScope struct { - Name string `json:"name"` // Bolt: filesystem path; JSON API: display name after prepForFrontend - Scope string `json:"scope"` // index path within that source +// PinnedItems maps source filesystem path -> index directory path -> pinned item names. +type PinnedItems map[string]map[string][]string + +// UserLegacyFields holds v1.x user JSON keys migrated on startup (Bolt/SQLite user_data). +type UserLegacyFields struct { + ApiKeys map[string]AuthToken `json:"apiKeys,omitempty"` +} + +// User is the persisted user: profile/settings in user_data, plus BackendScopes for source access. +type User struct { + FrontendUser + ID uint64 `json:"id,omitempty"` + // BackendScopes is the authoritative, persisted access list (SourceScope.Name = backend source path). + // SQLite stores this inside user_data JSON under the key "scopes" (see sqldb.UserData). + BackendScopes []BackendScope `json:"backendScopes,omitempty"` + BackendSourcePermissions map[string]SourceFilePermissions `json:"backendSourcePermissions,omitempty"` // key = source path + Tokens map[string]AuthToken `json:"tokens,omitempty"` + TOTPSecret string `json:"totpSecret,omitempty"` + TOTPNonce string `json:"totpNonce,omitempty"` + PasskeyCredentials []WebAuthnCredential `json:"passkeyCredentials,omitempty"` + PinnedItems PinnedItems `json:"pinnedItems,omitempty"` + Version int `json:"version"` + UserLegacyFields `json:",inline"` +} + +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 + 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 + Permissions SourceFilePermissions `json:"permissions,omitempty"` } // json tags must match variable name with smaller case first letter @@ -158,14 +237,12 @@ type NonAdminEditable struct { ShowCopyPath bool `json:"showCopyPath"` // show copy path action in the context menu ShowToolsInSidebar bool `json:"showToolsInSidebar"` // when false, sidebar hides links with category "tool" (default: true) DebugOffice bool `json:"debugOffice"` // debug onlyoffice editor - OtpEnabled bool `json:"otpEnabled"` // allow non-admin users to disable their own OTP SidebarLinks []SidebarLink `json:"sidebarLinks"` // customizable sidebar links HideFilesInTree bool `json:"hideFilesInTree"` // hide files in the sidebar tree navigation, when true, will show only directories. DeleteAfterArchive bool `json:"deleteAfterArchive"` // delete source files after successful creation/extraction of archives PreferEditorForMarkdown bool `json:"preferEditorForMarkdown"` // prefer editor first for markdown files instead of the Markdown Viewer ShowFirstLogin bool `json:"showFirstLogin"` PasskeyCredentials []WebAuthnCredential `json:"passkeyCredentials,omitempty"` - PinnedItems PinnedItems `json:"pinnedItems,omitempty"` } type FileLoading struct { @@ -207,7 +284,7 @@ type SourceConfigProvider struct { GetSourceByPath func(path string) (SourceInfo, bool) GetSourceByName func(name string) (SourceInfo, bool) GetAllSources func() []SourceInfo - GetDefaultScopes func() []SourceScope + GetDefaultScopes func() []BackendScope } // Global variables set by the settings package @@ -228,6 +305,11 @@ func SetSourceConfig(config *SourceConfigProvider) { sourceConfig = config } +// GetSourceConfig returns the current source configuration provider, or nil if unset. +func GetSourceConfig() *SourceConfigProvider { + return sourceConfig +} + // SourceConfigLoaded reports whether SetSourceConfig has been called (needed for ResolveSourceKey). func SourceConfigLoaded() bool { return sourceConfig != nil @@ -236,8 +318,8 @@ func SourceConfigLoaded() bool { // GetScopeForSourcePath returns the scope for a given source path (backend-style) // This method works with backend-style scopes where Name is the source path func (u *User) GetScopeForSourcePath(sourcePath string) (string, error) { - for _, scope := range u.Scopes { - if scope.Name == sourcePath { + for _, scope := range u.BackendScopes { + if scope.Path == sourcePath { return scope.Scope, nil } } @@ -261,8 +343,8 @@ func (u *User) GetScopeForSourceName(sourceName string) (string, error) { // HasSourceByPath checks if the user has access to a given source path func (u *User) HasSourceByPath(sourcePath string) bool { - for _, scope := range u.Scopes { - if scope.Name == sourcePath { + for _, scope := range u.BackendScopes { + if scope.Path == sourcePath { return true } } @@ -271,9 +353,9 @@ func (u *User) HasSourceByPath(sourcePath string) bool { // GetSourcePaths returns all source paths the user has access to func (u *User) GetSourcePaths() []string { - paths := make([]string, 0, len(u.Scopes)) - for _, scope := range u.Scopes { - paths = append(paths, scope.Name) + paths := make([]string, 0, len(u.BackendScopes)) + for _, scope := range u.BackendScopes { + paths = append(paths, scope.Path) } return paths } diff --git a/backend/database/users/webauthn.go b/backend/internal/database/users/webauthn.go similarity index 100% rename from backend/database/users/webauthn.go rename to backend/internal/database/users/webauthn.go diff --git a/backend/common/errors/errors.go b/backend/internal/errors/errors.go similarity index 96% rename from backend/common/errors/errors.go rename to backend/internal/errors/errors.go index 1435d912d7..c38eed4fbd 100644 --- a/backend/common/errors/errors.go +++ b/backend/internal/errors/errors.go @@ -25,6 +25,7 @@ var ( ErrNotViewable = errors.New("directory or item is not viewable") ErrWrongLoginMethod = errors.New("user attempted to login with wrong login method") ErrDownloadNotAllowed = errors.New("downloads are not allowed for this share") + ErrUseMediaStream = errors.New("use /media/stream for audio and video") ErrUploadNotAllowed = errors.New("upload permission not allowed for this share") ErrPasskeyMFARequired = errors.New("passkey MFA is required") ErrPasskeyVerification = errors.New("passkey verification failed") diff --git a/backend/events/eventRouter.go b/backend/internal/events/eventRouter.go similarity index 100% rename from backend/events/eventRouter.go rename to backend/internal/events/eventRouter.go diff --git a/backend/ffmpeg/cache.go b/backend/internal/ffmpeg/cache.go similarity index 55% rename from backend/ffmpeg/cache.go rename to backend/internal/ffmpeg/cache.go index 4dc0128a1f..63c5f59f7a 100644 --- a/backend/ffmpeg/cache.go +++ b/backend/internal/ffmpeg/cache.go @@ -3,12 +3,12 @@ package ffmpeg import ( "time" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" "github.com/gtsteffaniak/go-cache/cache" ) var ( - MediaCache = cache.NewCache[[]utils.SubtitleTrack](24 * time.Hour) // subtitles get cached for 24 hours - SubtitleContentCache = cache.NewCache[string](24 * time.Hour) // subtitle content gets cached for 24 hours - MetadataCache = cache.NewCache[float64](24 * time.Hour) // media duration gets cached for 24 hours + MediaCache = cache.NewCache[[]utils.SubtitleTrack](24 * time.Hour) // subtitle track lists from ffprobe + SubtitleContentCache = cache.NewCache[string](24 * time.Hour) // extracted embedded subtitle content + MetadataCache = cache.NewCache[float64](24 * time.Hour) // media duration from ffprobe ) diff --git a/backend/internal/ffmpeg/heic_orientation.go b/backend/internal/ffmpeg/heic_orientation.go new file mode 100644 index 0000000000..8b67c9a1fb --- /dev/null +++ b/backend/internal/ffmpeg/heic_orientation.go @@ -0,0 +1,138 @@ +package ffmpeg + +import ( + "bytes" + "context" + "image" + "image/jpeg" + "math" + "os/exec" + "strconv" + "strings" + + "github.com/kovidgoyal/imaging" +) + +// GetHEICDisplayMatrixRotation returns the largest rotation (degrees) ffmpeg reports for a +// HEIC display matrix. The second return value is false when the probe could not run or +// parse stderr — callers must not treat that as “no rotation was applied”. +func (s *Service) GetHEICDisplayMatrixRotation(ctx context.Context, heicPath string) (float64, bool) { + if s == nil { + return 0, false + } + ffmpegPath := s.FFmpegPath() + if ffmpegPath == "" || heicPath == "" { + return 0, false + } + + cmd := exec.CommandContext(ctx, ffmpegPath, "-hide_banner", "-i", heicPath, "-f", "null", "-") + var stderr bytes.Buffer + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + return 0, false + } + + rotation, ok := parseDisplayMatrixRotation(stderr.String()) + return rotation, ok +} + +func parseDisplayMatrixRotation(stderr string) (float64, bool) { + var best float64 + var found bool + for _, line := range strings.Split(stderr, "\n") { + if !strings.Contains(line, "Display Matrix:") { + continue + } + const prefix = "rotation of " + idx := strings.Index(line, prefix) + if idx < 0 { + continue + } + fields := strings.Fields(line[idx+len(prefix):]) + if len(fields) == 0 { + continue + } + token := strings.TrimSuffix(fields[0], "degrees") + deg, err := strconv.ParseFloat(token, 64) + if err != nil { + continue + } + found = true + if math.Abs(deg) > math.Abs(best) { + best = deg + } + } + return best, found +} + +func isNormalOrientation(orientation string) bool { + switch orientation { + case "", "Horizontal (normal)", "Top-left", "1": + return true + default: + return false + } +} + +func isPureRotationOrientation(orientation string) bool { + switch orientation { + case "Rotate 90 CW", "Right-top", "6", + "Rotate 270 CW", "Left-bottom", "8", + "Rotate 180", "Bottom-right", "3": + return true + default: + return false + } +} + +// orientationNeedsPostCorrection reports whether to rotate/flip JPEG bytes after ffmpeg decode. +func orientationNeedsPostCorrection(orientation string, displayRotation float64, displayKnown bool) bool { + if isNormalOrientation(orientation) { + return false + } + if isPureRotationOrientation(orientation) { + if !displayKnown { + // Probe failed: trust ffmpeg's display-matrix decode rather than risk double-rotation. + return false + } + return displayRotation == 0 + } + return true +} + +func applyOrientationToJPEG(jpegBytes []byte, orientation string) []byte { + if len(jpegBytes) < 100 || isNormalOrientation(orientation) { + return jpegBytes + } + + img, err := imaging.Decode(bytes.NewReader(jpegBytes)) + if err != nil { + return jpegBytes + } + + var out image.Image + switch orientation { + case "Rotate 90 CW", "Right-top", "6": + out = imaging.Rotate270(img) + case "Rotate 180", "Bottom-right", "3": + out = imaging.Rotate180(img) + case "Rotate 270 CW", "Left-bottom", "8": + out = imaging.Rotate90(img) + case "Mirror horizontal", "Top-right", "2": + out = imaging.FlipH(img) + case "Mirror vertical", "Bottom-left", "4": + out = imaging.FlipV(img) + case "Mirror horizontal and rotate 270 CW", "Right-bottom", "7": + out = imaging.Transverse(img) + case "Mirror horizontal and rotate 90 CW", "Left-top", "5": + out = imaging.Transpose(img) + default: + return jpegBytes + } + + var buf bytes.Buffer + if err := jpeg.Encode(&buf, out, &jpeg.Options{Quality: 90}); err != nil { + return jpegBytes + } + return buf.Bytes() +} diff --git a/backend/internal/ffmpeg/heic_orientation_test.go b/backend/internal/ffmpeg/heic_orientation_test.go new file mode 100644 index 0000000000..4709b1204d --- /dev/null +++ b/backend/internal/ffmpeg/heic_orientation_test.go @@ -0,0 +1,52 @@ +package ffmpeg + +import "testing" + +func TestParseDisplayMatrixRotation(t *testing.T) { + stderr := `Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'test.heic': + Stream group #0:0[0x31]: Tile Grid: hevc + Side data: + Display Matrix: rotation of -90.00 degrees + Stream #0:48[0x32]: Video: hevc + Side data: + Display Matrix: rotation of -0.00 degrees` + + got, ok := parseDisplayMatrixRotation(stderr) + if !ok { + t.Fatal("parseDisplayMatrixRotation() ok = false, want true") + } + if got != -90 { + t.Fatalf("parseDisplayMatrixRotation() = %v, want -90", got) + } +} + +func TestParseDisplayMatrixRotation_malformedLine(t *testing.T) { + _, ok := parseDisplayMatrixRotation("Display Matrix: rotation of\n") + if ok { + t.Fatal("expected ok=false for malformed stderr") + } +} + +func TestOrientationNeedsPostCorrection(t *testing.T) { + tests := []struct { + orientation string + displayRotation float64 + displayKnown bool + want bool + }{ + {"Horizontal (normal)", 0, true, false}, + {"Rotate 90 CW", -90, true, false}, + {"Rotate 90 CW", 0, true, true}, + {"Rotate 90 CW", 0, false, false}, + {"Mirror vertical", 0, true, true}, + {"Mirror vertical", -90, true, true}, + } + + for _, tt := range tests { + got := orientationNeedsPostCorrection(tt.orientation, tt.displayRotation, tt.displayKnown) + if got != tt.want { + t.Errorf("orientationNeedsPostCorrection(%q, %v, %v) = %v, want %v", + tt.orientation, tt.displayRotation, tt.displayKnown, got, tt.want) + } + } +} diff --git a/backend/internal/ffmpeg/image.go b/backend/internal/ffmpeg/image.go new file mode 100644 index 0000000000..a78c37135b --- /dev/null +++ b/backend/internal/ffmpeg/image.go @@ -0,0 +1,169 @@ +package ffmpeg + +import ( + "context" + "fmt" + "os" + "strconv" + "strings" + + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + "github.com/gtsteffaniak/filebrowser/backend/internal/imagemeta" + goffmpeg "github.com/gtsteffaniak/go-ffmpeg" +) + +// GetImageOrientation extracts the EXIF orientation from an image file. +func (s *Service) GetImageOrientation(imagePath string) (string, error) { + if orientation := imagemeta.GetOrientation(context.Background(), imagePath); orientation != "" { + return orientation, nil + } + return "Horizontal (normal)", nil +} + +// GetHEICOrientation returns the display orientation for HEIC/HEIF files. +func (s *Service) GetHEICOrientation(heicPath string) (string, error) { + return s.GetImageOrientation(heicPath) +} + +// GetOrientationFilter converts EXIF orientation to an FFmpeg filter suffix. +func (s *Service) GetOrientationFilter(orientation string) string { + switch orientation { + case "Rotate 90 CW", "Right-top": + return ",transpose=1" + case "Rotate 180", "Bottom-right": + return ",transpose=1,transpose=1" + case "Rotate 270 CW", "Left-bottom": + return ",transpose=2" + case "Mirror horizontal", "Top-right": + return ",hflip" + case "Mirror vertical", "Bottom-left": + return ",vflip" + case "Mirror horizontal and rotate 270 CW", "Right-bottom": + return ",transpose=0" + case "Mirror horizontal and rotate 90 CW", "Left-top": + return ",transpose=3" + case "Horizontal (normal)", "Top-left": + return "" + case "1": + return "" + case "2": + return ",hflip" + case "3": + return ",transpose=1,transpose=1" + case "4": + return ",vflip" + case "5": + return ",transpose=3" + case "6": + return ",transpose=1" + case "7": + return ",transpose=0" + case "8": + return ",transpose=2" + default: + return "" + } +} + +// ConvertHEICToJPEG decodes HEIC/HEIF to JPEG. Tile-grid iPhone HEIC cannot use ffmpeg -vf, +// so decode is filter-free and any remaining orientation is applied in Go afterward. +func (s *Service) ConvertHEICToJPEG(ctx context.Context, heicPath string, targetWidth, targetHeight int, quality string) ([]byte, error) { + if s == nil || s.inner == nil { + return nil, fmt.Errorf("ffmpeg service not available") + } + if ctx.Err() != nil { + return nil, ctx.Err() + } + + orientation, err := s.GetHEICOrientation(heicPath) + if err != nil { + orientation = "Horizontal (normal)" + } + + jpegBytes, err := s.runHEICConversion(ctx, heicPath, targetWidth, targetHeight, quality, "") + if err != nil { + return nil, fmt.Errorf("ffmpeg image conversion failed: %w", err) + } + + displayRotation, displayKnown := s.GetHEICDisplayMatrixRotation(ctx, heicPath) + if orientationNeedsPostCorrection(orientation, displayRotation, displayKnown) { + jpegBytes = applyOrientationToJPEG(jpegBytes, orientation) + } + return jpegBytes, nil +} + +// ConvertImageToJPEG converts any supported image to JPEG using ffmpeg. +func (s *Service) ConvertImageToJPEG(ctx context.Context, imagePath string, targetWidth, targetHeight int, quality string) ([]byte, error) { + return s.convertToJPEG(ctx, imagePath, targetWidth, targetHeight, quality, true) +} + +func (s *Service) convertToJPEG(ctx context.Context, inputPath string, targetWidth, targetHeight int, quality string, applyOrientation bool) ([]byte, error) { + if s == nil || s.inner == nil { + return nil, fmt.Errorf("ffmpeg service not available") + } + if ctx.Err() != nil { + return nil, ctx.Err() + } + + orientationFilter := "" + if applyOrientation { + orientation, err := s.GetImageOrientation(inputPath) + if err != nil { + orientation = "Horizontal (normal)" + } + orientationFilter = strings.TrimPrefix(s.GetOrientationFilter(orientation), ",") + } + + jpegBytes, err := s.runHEICConversion(ctx, inputPath, targetWidth, targetHeight, quality, orientationFilter) + if err == nil { + return jpegBytes, nil + } + if ctx.Err() != nil { + return nil, ctx.Err() + } + if orientationFilter != "" { + if jpegBytes, retryErr := s.runHEICConversion(ctx, inputPath, targetWidth, targetHeight, quality, ""); retryErr == nil { + return jpegBytes, nil + } + } + return nil, fmt.Errorf("ffmpeg image conversion failed: %w", err) +} + +func (s *Service) runHEICConversion(ctx context.Context, inputPath string, targetWidth, targetHeight int, quality, orientationFilter string) ([]byte, error) { + outputDir := s.cacheDir + if err := os.MkdirAll(outputDir, fileutils.PermDir); err != nil { + return nil, fmt.Errorf("failed to create cache directory: %w", err) + } + + tmp, err := os.CreateTemp(outputDir, "ffmpeg_convert_*.jpg") + if err != nil { + return nil, fmt.Errorf("failed to create temp file: %w", err) + } + outputFile := tmp.Name() + _ = tmp.Close() + defer os.Remove(outputFile) + + opts := goffmpeg.ConvertHEICOptions{ + InputPath: inputPath, + OutputPath: outputFile, + Width: targetWidth, + Height: targetHeight, + Quality: parseQuality(quality), + OrientationFilter: orientationFilter, + } + if err := s.inner.ConvertHEIC(ctx, opts); err != nil { + return nil, err + } + return os.ReadFile(outputFile) +} + +func parseQuality(quality string) int { + n, err := strconv.Atoi(quality) + if err != nil || n < 1 { + return 5 + } + if n > 10 { + return 10 + } + return n +} diff --git a/backend/ffmpeg/image_test.go b/backend/internal/ffmpeg/image_test.go similarity index 96% rename from backend/ffmpeg/image_test.go rename to backend/internal/ffmpeg/image_test.go index cca8dde982..a1d667b718 100644 --- a/backend/ffmpeg/image_test.go +++ b/backend/internal/ffmpeg/image_test.go @@ -124,13 +124,12 @@ func TestGetImageOrientation(t *testing.T) { } defer os.RemoveAll(tempDir) - service := NewFFmpegService(2, false, "/tmp/test_cache") + service := &Service{} t.Run("Non-existent file", func(t *testing.T) { nonExistentFile := filepath.Join(tempDir, "non_existent.heic") orientation, err := service.GetImageOrientation(nonExistentFile) - // Should return default orientation when exiftool fails if err != nil { t.Errorf("Expected no error for non-existent file, got: %v", err) } @@ -142,7 +141,6 @@ func TestGetImageOrientation(t *testing.T) { t.Run("Empty file path", func(t *testing.T) { orientation, err := service.GetImageOrientation("") - // Should return default orientation when exiftool fails if err != nil { t.Errorf("Expected no error for empty file path, got: %v", err) } diff --git a/backend/internal/ffmpeg/metadata.go b/backend/internal/ffmpeg/metadata.go new file mode 100644 index 0000000000..e94f0b2590 --- /dev/null +++ b/backend/internal/ffmpeg/metadata.go @@ -0,0 +1,121 @@ +package ffmpeg + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + goffmpeg "github.com/gtsteffaniak/go-ffmpeg" +) + +var blockedMediaPathPrefixes = []string{ + "pipe:", + "concat:", + "subfile:", + "crypto:", + "data:", +} + +// resolveLocalMediaPath restricts ffprobe to absolute local files (no remote protocols). +func resolveLocalMediaPath(mediaPath string) (string, os.FileInfo, error) { + trimmed := strings.TrimSpace(mediaPath) + if trimmed == "" { + return "", nil, fmt.Errorf("media path is empty") + } + if strings.Contains(trimmed, "://") { + return "", nil, fmt.Errorf("remote media URLs are not allowed") + } + lower := strings.ToLower(trimmed) + for _, prefix := range blockedMediaPathPrefixes { + if strings.HasPrefix(lower, prefix) { + return "", nil, fmt.Errorf("remote media protocols are not allowed") + } + } + + clean := filepath.Clean(trimmed) + if !filepath.IsAbs(clean) { + return "", nil, fmt.Errorf("media path must be absolute") + } + + info, err := os.Stat(clean) + if err != nil { + return "", nil, fmt.Errorf("failed to stat file: %w", err) + } + if info.IsDir() { + return "", nil, fmt.Errorf("media path is a directory") + } + return clean, info, nil +} + +// FileProbeInfo holds ffprobe results for a local media file. +type FileProbeInfo struct { + Duration float64 + VideoCodec string + AudioCodec string + FormatName string +} + +// ProbeFile extracts duration and codec info from a media file. +func (s *Service) ProbeFile(ctx context.Context, mediaPath string) (*FileProbeInfo, error) { + if s == nil || s.inner == nil { + return nil, fmt.Errorf("ffmpeg service not available") + } + + localPath, _, err := resolveLocalMediaPath(mediaPath) + if err != nil { + return nil, err + } + + if err = s.Acquire(ctx); err != nil { + return nil, err + } + defer s.Release() + + info, err := s.inner.ProbeStream(ctx, goffmpeg.ProbeStreamOptions{ + URL: localPath, + StreamType: goffmpeg.StreamFile, + Timeout: 30 * time.Second, + }) + if err != nil { + return nil, err + } + + return &FileProbeInfo{ + Duration: info.Duration, + VideoCodec: info.VideoCodec, + AudioCodec: info.AudioCodec, + FormatName: info.FormatName, + }, nil +} + +// GetMediaDuration extracts the duration of a media file in seconds. +func (s *Service) GetMediaDuration(ctx context.Context, mediaPath string) (float64, error) { + if s == nil || s.inner == nil { + return 0, fmt.Errorf("ffmpeg service not available") + } + + localPath, fileInfo, err := resolveLocalMediaPath(mediaPath) + if err != nil { + return 0, err + } + cacheKey := fmt.Sprintf("%s:%d", localPath, fileInfo.ModTime().Unix()) + if duration, found := MetadataCache.Get(cacheKey); found { + return duration, nil + } + + if err = s.Acquire(ctx); err != nil { + return 0, err + } + defer s.Release() + + duration, err := s.inner.GetMediaDuration(ctx, localPath) + if err != nil { + return 0, err + } + + MetadataCache.Set(cacheKey, duration) + return duration, nil +} diff --git a/backend/internal/ffmpeg/metadata_test.go b/backend/internal/ffmpeg/metadata_test.go new file mode 100644 index 0000000000..49f0f3d5f8 --- /dev/null +++ b/backend/internal/ffmpeg/metadata_test.go @@ -0,0 +1,53 @@ +package ffmpeg + +import ( + "os" + "path/filepath" + "testing" +) + +func TestResolveLocalMediaPath(t *testing.T) { + t.Parallel() + + tmpFile, err := os.CreateTemp(t.TempDir(), "probe-*") + if err != nil { + t.Fatalf("CreateTemp() error = %v", err) + } + tmpPath := tmpFile.Name() + tmpFile.Close() + + tests := []struct { + name string + path string + wantErr bool + }{ + {name: "absolute local file", path: tmpPath}, + {name: "empty path", path: "", wantErr: true}, + {name: "remote url", path: "http://example.com/video.mp4", wantErr: true}, + {name: "rtsp url", path: "rtsp://camera/stream", wantErr: true}, + {name: "pipe protocol", path: "pipe:0", wantErr: true}, + {name: "relative path", path: "video.mp4", wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got, info, err := resolveLocalMediaPath(tt.path) + if tt.wantErr { + if err == nil { + t.Fatalf("resolveLocalMediaPath(%q) error = nil, want error", tt.path) + } + return + } + if err != nil { + t.Fatalf("resolveLocalMediaPath(%q) error = %v", tt.path, err) + } + if got != filepath.Clean(tt.path) { + t.Fatalf("resolveLocalMediaPath(%q) = %q, want %q", tt.path, got, filepath.Clean(tt.path)) + } + if info == nil || info.IsDir() { + t.Fatalf("resolveLocalMediaPath(%q) returned invalid file info", tt.path) + } + }) + } +} diff --git a/backend/internal/ffmpeg/service.go b/backend/internal/ffmpeg/service.go new file mode 100644 index 0000000000..50ca5ad054 --- /dev/null +++ b/backend/internal/ffmpeg/service.go @@ -0,0 +1,204 @@ +package ffmpeg + +import ( + "context" + "fmt" + "io" + "os" + "strings" + + goffmpeg "github.com/gtsteffaniak/go-ffmpeg" + "github.com/gtsteffaniak/go-ffmpeg/capabilities" + "github.com/gtsteffaniak/go-ffmpeg/ops" + "github.com/gtsteffaniak/go-logger/logger" +) + +// Service wraps go-ffmpeg for filebrowser media operations. +type Service struct { + inner *goffmpeg.Service + cacheDir string +} + +// FFmpegService is kept for existing callers. +type FFmpegService = Service + +var global *Service + +// InitOptions configures startup initialization. +type InitOptions struct { + FFmpegPath string + MaxConcurrent int + CacheDir string + SkipHWTests bool + HardwareAcceleration bool +} + +// Initialize creates the global ffmpeg service and runs capability detection. +func Initialize(ctx context.Context, opts InitOptions) error { + if opts.MaxConcurrent < 1 { + opts.MaxConcurrent = 4 + } + if opts.CacheDir == "" { + opts.CacheDir = os.TempDir() + } + + if opts.HardwareAcceleration { + logger.Info("Detecting ffmpeg hardware codec support...") + } + + svc, err := goffmpeg.New(ctx, goffmpeg.Config{ + FFmpegPath: opts.FFmpegPath, + MaxConcurrent: opts.MaxConcurrent, + Logger: goffmpeg.NopLogger(), + SkipHWTests: opts.SkipHWTests, + }) + if err != nil { + global = nil + return err + } + + global = &Service{ + inner: svc, + cacheDir: opts.CacheDir, + } + + logCapabilities(svc, opts.HardwareAcceleration) + return nil +} + +// Get returns the initialized service, or nil when ffmpeg is unavailable. +func Get() *Service { + return global +} + +// Enabled reports whether ffmpeg initialized successfully. +func Enabled() bool { + return global != nil && global.inner != nil +} + +// FFmpegPath returns the resolved ffmpeg binary path. +func (s *Service) FFmpegPath() string { + if s == nil || s.inner == nil { + return "" + } + return s.inner.FFmpegPath() +} + +// FFprobePath returns the resolved ffprobe binary path. +func (s *Service) FFprobePath() string { + if s == nil || s.inner == nil { + return "" + } + return s.inner.FFprobePath() +} + +func (s *Service) Acquire(ctx context.Context) error { + if s == nil || s.inner == nil { + return fmt.Errorf("ffmpeg service not available") + } + return s.inner.Acquire(ctx) +} + +func (s *Service) Release() { + if s == nil || s.inner == nil { + return + } + s.inner.Release() +} + +// VideoPreview extracts a JPEG preview frame to w. +func (s *Service) VideoPreview(ctx context.Context, w io.Writer, videoPath string, percentageSeek int) error { + if s == nil || s.inner == nil { + return fmt.Errorf("ffmpeg service not available") + } + if err := s.Acquire(ctx); err != nil { + return err + } + defer s.Release() + + return s.inner.VideoPreview(ctx, w, ops.PreviewOptions{ + Input: videoPath, + SeekPercent: float64(percentageSeek), + Quality: 10, + }) +} + +// ExtractSubtitle returns embedded subtitle content as WebVTT. +func (s *Service) ExtractSubtitle(ctx context.Context, videoPath string, streamIndex int) (string, error) { + if s == nil || s.inner == nil { + return "", fmt.Errorf("ffmpeg service not available") + } + + fileInfo, err := os.Stat(videoPath) + if err != nil { + return "", fmt.Errorf("failed to stat file: %w", err) + } + cacheKey := fmt.Sprintf("subtitle_content:%s:%d:%d", videoPath, streamIndex, fileInfo.ModTime().Unix()) + if content, ok := SubtitleContentCache.Get(cacheKey); ok { + return content, nil + } + + if err = s.Acquire(ctx); err != nil { + return "", err + } + defer s.Release() + + content, err := s.inner.ExtractSubtitle(ctx, videoPath, streamIndex) + if err != nil { + return "", err + } + + SubtitleContentCache.Set(cacheKey, content) + return content, nil +} + +func logCapabilities(svc *goffmpeg.Service, detectHardware bool) { + caps := svc.Capabilities() + if caps == nil { + return + } + + logger.Debugf("Media Enabled: version %s @ %s", caps.FFmpegVersion, caps.FFmpegPath) + + if !detectHardware { + return + } + + hw := hardwareCodecSummary(svc) + if hw == "" { + logger.Warning("no ffmpeg hardware codec support found") + return + } + logger.Debugf("supported ffmpeg hardware codecs: %s", hw) +} + +func hardwareCodecSummary(svc *goffmpeg.Service) string { + seen := make(map[string]struct{}) + var parts []string + + add := func(entry string) { + if entry == "" { + return + } + if _, ok := seen[entry]; ok { + return + } + seen[entry] = struct{}{} + parts = append(parts, entry) + } + + for _, opt := range svc.AvailableEncodeOptions() { + if opt.Accel == capabilities.AccelNone { + continue + } + add(fmt.Sprintf("%s encode via %s (%s)", opt.Codec, opt.Encoder, capabilities.AccelLabel(opt.Accel))) + } + for _, opt := range svc.AvailableDecodeOptions() { + if opt.Accel == capabilities.AccelNone { + continue + } + add(fmt.Sprintf("%s decode via %s (%s)", opt.Codec, opt.Decoder, capabilities.AccelLabel(opt.Accel))) + } + + return strings.Join(parts, ", ") +} diff --git a/backend/internal/ffmpeg/subtitles.go b/backend/internal/ffmpeg/subtitles.go new file mode 100644 index 0000000000..9d2d6b7762 --- /dev/null +++ b/backend/internal/ffmpeg/subtitles.go @@ -0,0 +1,58 @@ +package ffmpeg + +import ( + "context" + "strconv" + "time" + + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + goffmpeg "github.com/gtsteffaniak/go-ffmpeg" + "github.com/gtsteffaniak/go-logger/logger" +) + +// DetectEmbeddedSubtitles detects embedded subtitle streams. +func DetectEmbeddedSubtitles(videoPath string, modtime time.Time) []utils.SubtitleTrack { + key := "embedded_subtitles:" + videoPath + ":" + modtime.Format(time.RFC3339) + if cached, ok := MediaCache.Get(key); ok { + return cached + } + + svc := Get() + if svc == nil || svc.inner == nil { + return nil + } + + tracks, err := svc.inner.DetectSubtitles(context.Background(), videoPath) + if err != nil { + logger.Debug("ffprobe failed for file: " + videoPath + ", error: " + err.Error()) + return nil + } + + subtitles := mapSubtitleTracks(tracks) + MediaCache.Set(key, subtitles) + return subtitles +} + +func mapSubtitleTracks(tracks []goffmpeg.SubtitleTrack) []utils.SubtitleTrack { + subtitles := make([]utils.SubtitleTrack, 0, len(tracks)) + for _, stream := range tracks { + index := stream.Index + track := utils.SubtitleTrack{ + Index: &index, + Codec: stream.Codec, + Language: stream.Language, + Title: stream.Title, + Embedded: true, + } + baseName := "Embedded Subtitle " + strconv.Itoa(stream.Index) + if track.Title != "" { + track.Name = baseName + " (" + track.Title + ")" + } else if track.Language != "" { + track.Name = baseName + " (" + track.Language + ")" + } else { + track.Name = baseName + } + subtitles = append(subtitles, track) + } + return subtitles +} diff --git a/backend/internal/ffmpeg/subtitles_test.go b/backend/internal/ffmpeg/subtitles_test.go new file mode 100644 index 0000000000..33b75fa981 --- /dev/null +++ b/backend/internal/ffmpeg/subtitles_test.go @@ -0,0 +1,62 @@ +package ffmpeg + +import ( + "testing" + + goffmpeg "github.com/gtsteffaniak/go-ffmpeg" +) + +func TestMapSubtitleTracks_uniqueNames(t *testing.T) { + tracks := mapSubtitleTracks([]goffmpeg.SubtitleTrack{ + {Index: 0, Title: "English", Language: "eng"}, + {Index: 1, Title: "English", Language: "eng"}, + }) + if len(tracks) != 2 { + t.Fatalf("len(tracks) = %d, want 2", len(tracks)) + } + if tracks[0].Name == tracks[1].Name { + t.Fatalf("duplicate subtitle names: %q", tracks[0].Name) + } + if tracks[0].Index == nil || *tracks[0].Index != 0 { + t.Fatalf("tracks[0].Index = %v, want 0", tracks[0].Index) + } + if tracks[1].Index == nil || *tracks[1].Index != 1 { + t.Fatalf("tracks[1].Index = %v, want 1", tracks[1].Index) + } +} + +func TestMapSubtitleTracks_nameFormats(t *testing.T) { + tests := []struct { + name string + stream goffmpeg.SubtitleTrack + wantName string + }{ + { + name: "title only", + stream: goffmpeg.SubtitleTrack{Index: 3, Title: "Director's Commentary"}, + wantName: "Embedded Subtitle 3 (Director's Commentary)", + }, + { + name: "language only", + stream: goffmpeg.SubtitleTrack{Index: 5, Language: "deu"}, + wantName: "Embedded Subtitle 5 (deu)", + }, + { + name: "no title or language", + stream: goffmpeg.SubtitleTrack{Index: 7}, + wantName: "Embedded Subtitle 7", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := mapSubtitleTracks([]goffmpeg.SubtitleTrack{tt.stream}) + if len(got) != 1 { + t.Fatalf("len = %d, want 1", len(got)) + } + if got[0].Name != tt.wantName { + t.Fatalf("Name = %q, want %q", got[0].Name, tt.wantName) + } + }) + } +} diff --git a/backend/icons/generator.go b/backend/internal/icons/generator.go similarity index 97% rename from backend/icons/generator.go rename to backend/internal/icons/generator.go index e360133110..55e0c8174b 100644 --- a/backend/icons/generator.go +++ b/backend/internal/icons/generator.go @@ -10,9 +10,9 @@ import ( "path/filepath" "strings" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/preview" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/preview" "github.com/gtsteffaniak/go-logger/logger" "github.com/kovidgoyal/imaging" ) diff --git a/backend/icons/manifest.go b/backend/internal/icons/manifest.go similarity index 91% rename from backend/icons/manifest.go rename to backend/internal/icons/manifest.go index e908be79d5..102ac807c6 100644 --- a/backend/icons/manifest.go +++ b/backend/internal/icons/manifest.go @@ -3,7 +3,7 @@ package icons import ( "strings" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" ) // PWAManifest represents the web app manifest structure @@ -43,7 +43,7 @@ func pwaManifestName(name string) string { return name } -// generatePWAManifest creates the PWA manifest structure. +// generatePWAManifest creates the PWA manifest structure func generatePWAManifest(name, description, baseURL, themeColor, pwaIcon192, pwaIcon256, pwaIcon512 string) PWAManifest { return PWAManifest{ Name: pwaManifestName(name), @@ -82,7 +82,7 @@ func generatePWAManifest(name, description, baseURL, themeColor, pwaIcon192, pwa // favicon (custom SVG uses a raster sidecar as the raster source). func InitializePWAManifest() { config := &settings.Config - staticURL := config.Server.BaseURL + "public/static" + staticURL := config.Http.BaseURL + "public/static" title := config.Frontend.Name description := config.Frontend.Description defaultThemeColor := "#455a64" @@ -91,5 +91,5 @@ func InitializePWAManifest() { pwaIcon256 := staticURL + "/icons/pwa-icon-256.png" pwaIcon512 := staticURL + "/icons/pwa-icon-512.png" - CachedManifest = generatePWAManifest(title, description, config.Server.BaseURL, defaultThemeColor, pwaIcon192, pwaIcon256, pwaIcon512) + CachedManifest = generatePWAManifest(title, description, config.Http.BaseURL, defaultThemeColor, pwaIcon192, pwaIcon256, pwaIcon512) } diff --git a/backend/icons/manifest_share.go b/backend/internal/icons/manifest_share.go similarity index 95% rename from backend/icons/manifest_share.go rename to backend/internal/icons/manifest_share.go index f95e02632c..4e85fd89cf 100644 --- a/backend/icons/manifest_share.go +++ b/backend/internal/icons/manifest_share.go @@ -3,7 +3,7 @@ package icons import ( "strings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" ) const maxManifestTextLen = 256 @@ -36,7 +36,7 @@ func ShareRootFromStartURL(baseURL, startURL string) (shareRoot, normalizedStart return "", "", false } if subPath != "" { - if _, err := utils.SanitizeUserPath(subPath); err != nil { + if _, err := utils.SanitizePath(subPath); err != nil { return "", "", false } } @@ -58,7 +58,6 @@ func ShareHashFromHTTPPath(path, baseURL string) string { prefixes := []string{ strings.TrimSuffix(baseURL, "/") + "/public/share/", "/public/share/", - "/share/", } for _, prefix := range prefixes { if !strings.HasPrefix(path, prefix) { diff --git a/backend/icons/manifest_share_test.go b/backend/internal/icons/manifest_share_test.go similarity index 98% rename from backend/icons/manifest_share_test.go rename to backend/internal/icons/manifest_share_test.go index 9c6fa18308..8cddb0b5b2 100644 --- a/backend/icons/manifest_share_test.go +++ b/backend/internal/icons/manifest_share_test.go @@ -31,7 +31,6 @@ func TestShareHashFromHTTPPath(t *testing.T) { paths := []string{ "/testing/public/share/hash1234567890abcdef/", "/public/share/hash1234567890abcdef/files", - "/share/hash1234567890abcdef/", } for _, path := range paths { hash := ShareHashFromHTTPPath(path, baseURL) diff --git a/backend/internal/imagemeta/common.go b/backend/internal/imagemeta/common.go new file mode 100644 index 0000000000..18439b8055 --- /dev/null +++ b/backend/internal/imagemeta/common.go @@ -0,0 +1,6 @@ +package imagemeta + +// IsJPEG reports whether data begins with a JPEG SOI marker. +func IsJPEG(data []byte) bool { + return len(data) >= 2 && data[0] == 0xff && data[1] == 0xd8 +} diff --git a/backend/internal/imagemeta/embedded.go b/backend/internal/imagemeta/embedded.go new file mode 100644 index 0000000000..a26e890871 --- /dev/null +++ b/backend/internal/imagemeta/embedded.go @@ -0,0 +1,158 @@ +//go:build !386 && !arm + +package imagemeta + +import ( + "context" + "io" + "os" + "path/filepath" + "strings" + + extimagemeta "github.com/evanoberholster/imagemeta" + "github.com/evanoberholster/imagemeta/meta/exif" +) + +var rawImageExtensions = map[string]struct{}{ + ".cr2": {}, ".cr3": {}, ".nef": {}, ".nrw": {}, ".arw": {}, ".srf": {}, ".sr2": {}, + ".orf": {}, ".rw2": {}, ".raw": {}, ".dng": {}, ".raf": {}, ".pef": {}, ".ptx": {}, + ".rwl": {}, ".3fr": {}, ".fff": {}, ".erf": {}, ".mrw": {}, ".dcr": {}, ".kdc": {}, + ".dc2": {}, ".x3f": {}, ".iiq": {}, ".nkc": {}, ".r3d": {}, +} + +func isRawImageExtension(ext string) bool { + _, ok := rawImageExtensions[strings.ToLower(ext)] + return ok +} + +func isHEICExtension(ext string) bool { + switch strings.ToLower(ext) { + case ".heic", ".heif", ".heics": + return true + default: + return false + } +} + +// ExtractEmbeddedPreview returns embedded JPEG preview bytes when present. +// Returns nil, nil when no preview exists or the file cannot be read. +func ExtractEmbeddedPreview(ctx context.Context, path string) ([]byte, error) { + if ctx.Err() != nil || path == "" { + return nil, ctx.Err() + } + + ext := strings.ToLower(filepath.Ext(path)) + if !isRawImageExtension(ext) && !isHEICExtension(ext) { + return nil, nil + } + + f, err := os.Open(path) + if err != nil { + return nil, nil + } + defer f.Close() + + var data []byte + switch { + case ext == ".cr3": + data, err = extimagemeta.PreviewCR3(f) + case isRawImageExtension(ext): + data, err = extractTIFFEmbeddedPreview(f) + case isHEICExtension(ext): + // imagemeta only extracts ISO-BMFF previews for CR3; HEIC falls back to FFmpeg. + return nil, nil + } + if err != nil || len(data) == 0 { + return nil, nil + } + if !IsJPEG(data) { + return nil, nil + } + return data, nil +} + +func extractTIFFEmbeddedPreview(f *os.File) ([]byte, error) { + if _, err := f.Seek(0, io.SeekStart); err != nil { + return nil, err + } + + ex, err := extimagemeta.Decode(f) + if err != nil { + return nil, err + } + + for _, c := range previewCandidates(ex) { + if c.length == 0 { + continue + } + data, readErr := readFileRange(f, c.offset, c.length) + if readErr != nil || len(data) == 0 { + continue + } + if IsJPEG(data) { + return data, nil + } + } + return nil, nil +} + +type previewCandidate struct { + offset, length uint32 +} + +func previewCandidates(ex exif.Exif) []previewCandidate { + var out []previewCandidate + + if ex.MakerNote.Canon != nil { + info := ex.MakerNote.Canon.PreviewImageInfo + if info.PreviewImageLength > 0 && info.PreviewImageStart > 0 { + out = append(out, previewCandidate{ + offset: info.PreviewImageStart, + length: info.PreviewImageLength, + }) + } + } + + appendIFD := func(ifd *exif.ImageIFD) { + if ifd == nil { + return + } + if ifd.ImageLength > 0 && ifd.ImageOffset > 0 { + out = append(out, previewCandidate{offset: ifd.ImageOffset, length: ifd.ImageLength}) + } + } + appendIFD(ex.IFD1) + appendIFD(ex.IFD2) + + if ex.IFD0.ThumbnailLength > 0 && ex.IFD0.ThumbnailOffset > 0 { + out = append(out, previewCandidate{ + offset: ex.IFD0.ThumbnailOffset, + length: ex.IFD0.ThumbnailLength, + }) + } + if ex.IFD0.ImageLength > 0 && ex.IFD0.ImageOffset > 0 { + out = append(out, previewCandidate{ + offset: ex.IFD0.ImageOffset, + length: ex.IFD0.ImageLength, + }) + } + + return out +} + +const maxPreviewReadSize = 100 * 1024 * 1024 // embedded previews are never larger + +func readFileRange(f *os.File, offset, length uint32) ([]byte, error) { + if length == 0 { + return nil, nil + } + if length > maxPreviewReadSize { + return nil, nil + } + data := make([]byte, length) + n, err := f.ReadAt(data, int64(offset)) + if err != nil && err != io.EOF { + return nil, err + } + return data[:n], nil +} diff --git a/backend/internal/imagemeta/imagemeta_test.go b/backend/internal/imagemeta/imagemeta_test.go new file mode 100644 index 0000000000..63d725a13d --- /dev/null +++ b/backend/internal/imagemeta/imagemeta_test.go @@ -0,0 +1,97 @@ +//go:build !386 && !arm + +package imagemeta + +import ( + "os" + "testing" + + "github.com/evanoberholster/imagemeta/meta/exif/tag" +) + +func TestIsJPEG(t *testing.T) { + tests := []struct { + name string + data []byte + want bool + }{ + {"empty", nil, false}, + {"jpeg soi", []byte{0xff, 0xd8, 0xff, 0xe0}, true}, + {"not jpeg", []byte{0x89, 0x50, 0x4e, 0x47}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := IsJPEG(tt.data); got != tt.want { + t.Errorf("IsJPEG() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestIsRawImageExtension(t *testing.T) { + if !isRawImageExtension(".cr2") { + t.Fatal("expected .cr2 to be raw") + } + if isRawImageExtension(".jpg") { + t.Fatal("expected .jpg not to be raw") + } +} + +func TestOrientationStringMapping(t *testing.T) { + cases := map[uint32]string{ + 1: "Horizontal (normal)", + 6: "Rotate 90 CW", + 8: "Rotate 270 CW", + } + for value, want := range cases { + if got := tag.ValueNameFor(tag.IFD0, tag.TagOrientation, value); got != want { + t.Errorf("orientation %d = %q, want %q", value, got, want) + } + } +} + +func TestGetOrientationMissingFile(t *testing.T) { + if got := GetOrientation(t.Context(), "/nonexistent/file.cr2"); got != "" { + t.Fatalf("GetOrientation() = %q, want empty", got) + } +} + +func TestExtractEmbeddedPreviewMissingFile(t *testing.T) { + data, err := ExtractEmbeddedPreview(t.Context(), "/nonexistent/file.cr2") + if err != nil { + t.Fatalf("ExtractEmbeddedPreview() err = %v", err) + } + if data != nil { + t.Fatalf("ExtractEmbeddedPreview() = %v, want nil", data) + } +} + +func TestReadFileRangeRejectsOversizedLength(t *testing.T) { + f, err := os.CreateTemp(t.TempDir(), "preview-*") + if err != nil { + t.Fatal(err) + } + defer f.Close() + + if _, err = f.Write([]byte{0xff, 0xd8}); err != nil { + t.Fatal(err) + } + + data, err := readFileRange(f, 0, maxPreviewReadSize+1) + if err != nil { + t.Fatalf("readFileRange() err = %v, want nil", err) + } + if data != nil { + t.Fatalf("readFileRange() = %v, want nil", data) + } +} + +func TestExtractEmbeddedPreviewSkipsJPEG(t *testing.T) { + data, err := ExtractEmbeddedPreview(t.Context(), "/nonexistent/file.jpg") + if err != nil { + t.Fatalf("ExtractEmbeddedPreview() err = %v", err) + } + if data != nil { + t.Fatalf("ExtractEmbeddedPreview() = %v, want nil", data) + } +} diff --git a/backend/internal/imagemeta/orientation.go b/backend/internal/imagemeta/orientation.go new file mode 100644 index 0000000000..102e38ac62 --- /dev/null +++ b/backend/internal/imagemeta/orientation.go @@ -0,0 +1,48 @@ +//go:build !386 && !arm + +package imagemeta + +import ( + "context" + "os" + "path/filepath" + "strings" + + extimagemeta "github.com/evanoberholster/imagemeta" + "github.com/evanoberholster/imagemeta/meta/exif" + "github.com/evanoberholster/imagemeta/meta/exif/tag" +) + +// GetOrientation returns the display orientation string for a file (e.g. "Rotate 90 CW", +// "Horizontal (normal)"). Returns empty string when orientation cannot be read. +func GetOrientation(ctx context.Context, path string) string { + if ctx.Err() != nil || path == "" { + return "" + } + + f, err := os.Open(path) + if err != nil { + return "" + } + defer f.Close() + + ext := strings.ToLower(filepath.Ext(path)) + var ex exif.Exif + switch ext { + case ".heic", ".heif", ".heics": + ex, err = extimagemeta.DecodeHeif(f) + default: + ex, err = extimagemeta.Decode(f) + } + if err != nil { + return "" + } + if ctx.Err() != nil { + return "" + } + + if ex.IFD0.Orientation == 0 { + return "" + } + return tag.ValueNameFor(tag.IFD0, tag.TagOrientation, uint32(ex.IFD0.Orientation)) +} diff --git a/backend/internal/imagemeta/stub.go b/backend/internal/imagemeta/stub.go new file mode 100644 index 0000000000..489690da39 --- /dev/null +++ b/backend/internal/imagemeta/stub.go @@ -0,0 +1,15 @@ +//go:build 386 || arm + +package imagemeta + +import "context" + +// ExtractEmbeddedPreview is unavailable on 32-bit platforms (imagemeta dependency omitted). +func ExtractEmbeddedPreview(ctx context.Context, path string) ([]byte, error) { + return nil, nil +} + +// GetOrientation is unavailable on 32-bit platforms (imagemeta dependency omitted). +func GetOrientation(ctx context.Context, path string) string { + return "" +} diff --git a/backend/internal/imagemeta/stub_test.go b/backend/internal/imagemeta/stub_test.go new file mode 100644 index 0000000000..2a95e12dc2 --- /dev/null +++ b/backend/internal/imagemeta/stub_test.go @@ -0,0 +1,33 @@ +//go:build 386 || arm + +package imagemeta + +import ( + "context" + "testing" +) + +func TestIsJPEG(t *testing.T) { + if !IsJPEG([]byte{0xff, 0xd8, 0xff, 0xe0}) { + t.Fatal("expected JPEG SOI") + } + if IsJPEG([]byte{0x89, 0x50}) { + t.Fatal("expected non-JPEG") + } +} + +func TestExtractEmbeddedPreviewUnavailable(t *testing.T) { + data, err := ExtractEmbeddedPreview(context.Background(), "/any/file.cr2") + if err != nil { + t.Fatalf("ExtractEmbeddedPreview() err = %v", err) + } + if data != nil { + t.Fatalf("ExtractEmbeddedPreview() = %v, want nil on 32-bit", data) + } +} + +func TestGetOrientationUnavailable(t *testing.T) { + if got := GetOrientation(context.Background(), "/any/file.cr2"); got != "" { + t.Fatalf("GetOrientation() = %q, want empty on 32-bit", got) + } +} diff --git a/backend/internal/ports/ports.go b/backend/internal/ports/ports.go new file mode 100644 index 0000000000..f4a7381bf3 --- /dev/null +++ b/backend/internal/ports/ports.go @@ -0,0 +1,42 @@ +// Package ports defines narrow interfaces for dependency injection. +// Domain packages depend on these interfaces; state.Store implements them. +package ports + +import ( + "github.com/gtsteffaniak/filebrowser/backend/internal/database/dbindex" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" +) + +// UserReader loads persisted users (read-only). +type UserReader interface { + GetUserByID(id uint64) (users.User, error) + GetUserByUsername(username string) (users.User, error) +} + +// UserWriter persists user changes. Handlers orchestrate writes; auth must not implement this. +type UserWriter interface { + CreateUser(user *users.User, plaintextPassword string) error + UpdateUser(user *users.User, plaintextPassword string, fields ...string) error + DeleteUser(id uint64) error +} + +// AccessGate enforces path-level access rules (no indexing types to avoid import cycles). +type AccessGate interface { + AccessPermitted(sourcePath string, indexPath utils.IndexPath, username string) bool + UpdateAccessRulesOnMove(sourcePath string, oldPath, newPath utils.IndexPath) (int, error) +} + +// ShareReader loads share metadata for file and activity operations. +type ShareReader interface { + GetShare(hash string) (share.Share, error) + IsShared(source, path string, userID uint64) bool +} + +// IndexMetaStore persists per-source index metadata (complexity, scanner state). +type IndexMetaStore interface { + GetIndexInfo(path string) (dbindex.IndexInfo, error) + SaveIndexInfo(info *dbindex.IndexInfo) error + ResetAllIndexComplexities() error +} diff --git a/backend/preview/buffer_pool.go b/backend/internal/preview/buffer_pool.go similarity index 100% rename from backend/preview/buffer_pool.go rename to backend/internal/preview/buffer_pool.go diff --git a/backend/preview/buffer_pool_test.go b/backend/internal/preview/buffer_pool_test.go similarity index 100% rename from backend/preview/buffer_pool_test.go rename to backend/internal/preview/buffer_pool_test.go diff --git a/backend/preview/doc.go b/backend/internal/preview/doc.go similarity index 98% rename from backend/preview/doc.go rename to backend/internal/preview/doc.go index 5e7069fa24..6ef77d9af2 100644 --- a/backend/preview/doc.go +++ b/backend/internal/preview/doc.go @@ -14,7 +14,7 @@ import ( "time" "github.com/gen2brain/go-fitz" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" ) func docEnabled() bool { diff --git a/backend/preview/docDefault.go b/backend/internal/preview/docDefault.go similarity index 87% rename from backend/preview/docDefault.go rename to backend/internal/preview/docDefault.go index afd5c77ba8..ffdd9040b0 100644 --- a/backend/preview/docDefault.go +++ b/backend/internal/preview/docDefault.go @@ -5,7 +5,7 @@ package preview import ( "context" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" ) func docEnabled() bool { diff --git a/backend/internal/preview/embed.go b/backend/internal/preview/embed.go new file mode 100644 index 0000000000..1c9f90b0c9 --- /dev/null +++ b/backend/internal/preview/embed.go @@ -0,0 +1,20 @@ +package preview + +import ( + "path/filepath" + "strings" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" +) + +func hasEmbeddedPreview(fileType, fileName string) bool { + ext := strings.ToLower(filepath.Ext(fileName)) + if iteminfo.IsRawImage(ext) { + return true + } + return strings.HasPrefix(fileType, "image/hei") +} + +func isJPEG(data []byte) bool { + return len(data) >= 2 && data[0] == 0xff && data[1] == 0xd8 +} diff --git a/backend/internal/preview/embed_test.go b/backend/internal/preview/embed_test.go new file mode 100644 index 0000000000..8ec5f93dbf --- /dev/null +++ b/backend/internal/preview/embed_test.go @@ -0,0 +1,21 @@ +package preview + +import "testing" + +func TestHasEmbeddedPreview(t *testing.T) { + if !hasEmbeddedPreview("image/x-canon-cr2", "photo.cr2") { + t.Fatal("expected raw CR2 to have embedded preview path") + } + if !hasEmbeddedPreview("image/heic", "photo.heic") { + t.Fatal("expected HEIC to have embedded preview path") + } + if hasEmbeddedPreview("image/jpeg", "photo.jpg") { + t.Fatal("expected JPEG to skip embedded preview path") + } +} + +func TestIsJPEGMarker(t *testing.T) { + if !isJPEG([]byte{0xff, 0xd8, 0xff}) { + t.Fatal("expected JPEG SOI marker") + } +} diff --git a/backend/internal/preview/heic_ffmpeg.go b/backend/internal/preview/heic_ffmpeg.go new file mode 100644 index 0000000000..10f8c07c22 --- /dev/null +++ b/backend/internal/preview/heic_ffmpeg.go @@ -0,0 +1,69 @@ +package preview + +import ( + "context" + "fmt" +) + +// convertHEICToJPEGWithFFmpeg decodes HEIC to JPEG at full resolution via ffmpeg. +// Tile-grid iPhone HEIC cannot use ffmpeg -vf scale; resize is done later by CreatePreview. +// Passing non-zero width/height would add -vf scale and fail on those files. +func (s *Service) convertHEICToJPEGWithFFmpeg(ctx context.Context, filePath string, previewSize string) ([]byte, error) { + if s.ffmpegService == nil { + return nil, fmt.Errorf("FFmpeg is not available") + } + + if ctx.Err() != nil { + return nil, ctx.Err() + } + + if err := s.ffmpegService.Acquire(ctx); err != nil { + return nil, err + } + defer s.ffmpegService.Release() + + var quality string + switch previewSize { + case "large": + quality = "2" + case "original": + quality = "1" + default: + quality = "5" + } + + return s.ffmpegService.ConvertHEICToJPEG(ctx, filePath, 0, 0, quality) +} + +// convertImageWithFFmpeg converts any image file (including problematic JPEGs) to resized JPEG using FFmpeg. +// This is used as a fallback for JPEG files that Go's standard decoder can't handle (extended sequential, etc.) +func (s *Service) convertImageWithFFmpeg(ctx context.Context, filePath string, previewSize string) ([]byte, error) { + if s.ffmpegService == nil { + return nil, fmt.Errorf("FFmpeg is not available for JPEG fallback") + } + + if ctx.Err() != nil { + return nil, ctx.Err() + } + + if err := s.ffmpegService.Acquire(ctx); err != nil { + return nil, err + } + defer s.ffmpegService.Release() + + var width, height int + var quality string + switch previewSize { + case "large": + width, height = 640, 640 + quality = "2" + case "original": + width, height = 0, 0 + quality = "1" + default: + width, height = 256, 256 + quality = "5" + } + + return s.ffmpegService.ConvertImageToJPEG(ctx, filePath, width, height, quality) +} diff --git a/backend/preview/image.go b/backend/internal/preview/image.go similarity index 99% rename from backend/preview/image.go rename to backend/internal/preview/image.go index 6e93595cec..cd414af000 100644 --- a/backend/preview/image.go +++ b/backend/internal/preview/image.go @@ -276,7 +276,7 @@ func (s *Service) resizeWithSize(in io.Reader, out io.Writer, fileSize int64, op } // applyOrientationToPreviewBytes applies EXIF orientation to image bytes using the imaging library. -// orientation is the string from exiftool -Orientation -s3 (e.g. "Rotate 90 CW", "Horizontal (normal)"). +// orientation is the EXIF orientation label (e.g. "Rotate 90 CW", "Horizontal (normal)"). // Returns rotated JPEG bytes or the original bytes on error/unknown orientation. No FFmpeg required. func applyOrientationToPreviewBytes(imageBytes []byte, orientation string) []byte { if len(imageBytes) < 100 { diff --git a/backend/preview/image_enum.go b/backend/internal/preview/image_enum.go similarity index 100% rename from backend/preview/image_enum.go rename to backend/internal/preview/image_enum.go diff --git a/backend/preview/image_test.go b/backend/internal/preview/image_test.go similarity index 99% rename from backend/preview/image_test.go rename to backend/internal/preview/image_test.go index e9f9d57929..50428d1c8d 100644 --- a/backend/preview/image_test.go +++ b/backend/internal/preview/image_test.go @@ -12,7 +12,7 @@ import ( "os" "testing" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" "github.com/spf13/afero" "github.com/stretchr/testify/require" "golang.org/x/image/bmp" diff --git a/backend/preview/memory_tracker.go b/backend/internal/preview/memory_tracker.go similarity index 100% rename from backend/preview/memory_tracker.go rename to backend/internal/preview/memory_tracker.go diff --git a/backend/preview/office.go b/backend/internal/preview/office.go similarity index 97% rename from backend/preview/office.go rename to backend/internal/preview/office.go index c81a8b77cc..87d02ce63b 100644 --- a/backend/preview/office.go +++ b/backend/internal/preview/office.go @@ -10,7 +10,7 @@ import ( "net/http" jwt "github.com/golang-jwt/jwt/v4" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" ) type officePreviewResponse struct { diff --git a/backend/preview/preview.go b/backend/internal/preview/preview.go similarity index 92% rename from backend/preview/preview.go rename to backend/internal/preview/preview.go index 393f8ba5db..053b12eb6d 100644 --- a/backend/preview/preview.go +++ b/backend/internal/preview/preview.go @@ -15,11 +15,12 @@ import ( "sync" "time" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/diskcache" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/ffmpeg" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/diskcache" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + "github.com/gtsteffaniak/filebrowser/backend/internal/imagemeta" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/ffmpeg" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" "github.com/gtsteffaniak/go-logger/logger" ) @@ -55,8 +56,6 @@ func NewPreviewGenerator(concurrencyLimit int, cacheDir string) *Service { if concurrencyLimit < 1 { concurrencyLimit = 1 } - // get round up half value of concurrencyLimit for FFmpeg operations - ffmpegConcurrencyLimit := (concurrencyLimit + 1) / 2 actualCacheDir := cacheDir if actualCacheDir == "" { @@ -85,8 +84,8 @@ func NewPreviewGenerator(concurrencyLimit int, cacheDir string) *Service { logger.Error(err) } - // Single FFmpeg service shared by video preview and HEIC/JPEG fallback - ffmpegService := ffmpeg.NewFFmpegService(ffmpegConcurrencyLimit, settings.Config.Integrations.Media.Debug, filepath.Join(actualCacheDir, "heic")) + // Single shared ffmpeg service initialized during config setup + ffmpegService := ffmpeg.Get() var imageSem, imageLargeSem chan struct{} @@ -450,15 +449,14 @@ func GeneratePreviewWithMD5(ctx context.Context, file iteminfo.ExtendedFileInfo, cacheKey := CacheKey(fileMD5, previewSize, seekPercentage) - // If this file type might have an embedded preview, try exiftool first before any type-specific path. + // If this file type might have an embedded preview, try extracting it before any type-specific path. var imageBytes []byte - fromExiftool := false + fromEmbeddedPreview := false if hasEmbeddedPreview(file.Type, file.Name) { - if exifBytes, _ := ExtractEmbeddedPreview(ctx, file.RealPath, file.Type); len(exifBytes) >= minPreviewSize { - imageBytes = exifBytes - fromExiftool = true - // Apply EXIF orientation from source file using exiftool + imaging (no FFmpeg). - if orient := GetOrientation(ctx, file.RealPath); orient != "" { + if previewBytes, _ := imagemeta.ExtractEmbeddedPreview(ctx, file.RealPath); len(previewBytes) >= minPreviewSize && isJPEG(previewBytes) { + imageBytes = previewBytes + fromEmbeddedPreview = true + if orient := imagemeta.GetOrientation(ctx, file.RealPath); orient != "" { if corrected := applyOrientationToPreviewBytes(imageBytes, orient); len(corrected) >= minPreviewSize { imageBytes = corrected } @@ -466,7 +464,7 @@ func GeneratePreviewWithMD5(ctx context.Context, file iteminfo.ExtendedFileInfo, } } - if !fromExiftool { + if !fromEmbeddedPreview { var err error imageBytes, err = service.generateRawPreview(ctx, file, previewSize, officeUrl, seekPercentage, hash) if err != nil { @@ -481,16 +479,10 @@ func GeneratePreviewWithMD5(ctx context.Context, file iteminfo.ExtendedFileInfo, return nil, ErrPreviewTooSmall } - // When we got bytes from exiftool, we still need to resize to small/large/xlarge (original is never converted). - // When we got bytes from type-specific path, HEIC/Image are already resized; others need resize below. + // When we got bytes from an embedded preview, we still need to resize to small/large/xlarge (original is never converted). + // When we got bytes from type-specific path, regular images are already resized; others need resize below. previewType := determinePreviewType(file) - if !fromExiftool && previewType == previewTypeHEIC { - if err := service.fileCache.Store(ctx, cacheKey, imageBytes); err != nil { - logger.Errorf("failed to cache HEIC image: %v", err) - } - return imageBytes, nil - } - if !fromExiftool && previewType == previewTypeImage { + if !fromEmbeddedPreview && previewType == previewTypeImage { if err := service.fileCache.Store(ctx, cacheKey, imageBytes); err != nil { logger.Errorf("failed to cache image: %v", err) } @@ -502,7 +494,7 @@ func GeneratePreviewWithMD5(ctx context.Context, file iteminfo.ExtendedFileInfo, return nil, ctx.Err() } - // Resize if needed (exiftool bytes, or videos, audio, documents). Original is never converted. + // Resize if needed (embedded preview bytes, or videos, audio, documents). Original is never converted. if previewSize != "original" { options, err := getPreviewOptions(previewSize) if err != nil { diff --git a/backend/internal/preview/testdata b/backend/internal/preview/testdata new file mode 120000 index 0000000000..b6dfbf1670 --- /dev/null +++ b/backend/internal/preview/testdata @@ -0,0 +1 @@ +../../../frontend/tests/playwright-files/myfolder/testdata \ No newline at end of file diff --git a/backend/preview/video.go b/backend/internal/preview/video.go similarity index 92% rename from backend/preview/video.go rename to backend/internal/preview/video.go index 503d2de8b6..15f7b52524 100644 --- a/backend/preview/video.go +++ b/backend/internal/preview/video.go @@ -26,7 +26,7 @@ func (s *Service) GenerateVideoPreview(ctx context.Context, videoPath string, pe } var buf bytes.Buffer - err := s.ffmpegService.GenerateVideoPreviewStreaming(ctx, videoPath, percentageSeek, &buf) + err := s.ffmpegService.VideoPreview(ctx, &buf, videoPath, percentageSeek) if err != nil { return nil, err } diff --git a/backend/internal/state/access.go b/backend/internal/state/access.go new file mode 100644 index 0000000000..f96cb7c4e8 --- /dev/null +++ b/backend/internal/state/access.go @@ -0,0 +1,144 @@ +package state + +import ( + "github.com/gtsteffaniak/filebrowser/backend/internal/database/access" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" +) + +// AccessPermitted reports whether username may access indexPath on sourcePath. +// When accessDb is not initialized, access is allowed. +func AccessPermitted(sourcePath string, indexPath utils.IndexPath, username string) bool { + if accessDb == nil { + return true + } + return accessDb.Permitted(sourcePath, indexPath, username) +} + +func AllowUser(sourcePath string, indexPath utils.IndexPath, username string) error { + return accessDb.AllowUser(sourcePath, indexPath, username) +} + +func AllowGroup(sourcePath string, indexPath utils.IndexPath, groupname string) error { + return accessDb.AllowGroup(sourcePath, indexPath, groupname) +} + +func DenyUser(sourcePath string, indexPath utils.IndexPath, username string) error { + return accessDb.DenyUser(sourcePath, indexPath, username) +} + +func DenyGroup(sourcePath string, indexPath utils.IndexPath, groupname string) error { + return accessDb.DenyGroup(sourcePath, indexPath, groupname) +} + +func DenyAll(sourcePath string, indexPath utils.IndexPath) error { + return accessDb.DenyAll(sourcePath, indexPath) +} + +func GetFrontendRules(sourcePath string, indexPath utils.IndexPath) (access.FrontendAccessRule, bool) { + return accessDb.GetFrontendRules(sourcePath, indexPath) +} + +func GetAllRules(sourcePath string) (map[string]access.FrontendAccessRule, error) { + return accessDb.GetAllRules(sourcePath) +} + +func GetRulesForUser(sourcePath, username string) map[string]access.FrontendAccessRule { + return accessDb.GetRulesForUser(sourcePath, username) +} + +func GetRulesForGroup(sourcePath, groupname string) map[string]access.FrontendAccessRule { + return accessDb.GetRulesForGroup(sourcePath, groupname) +} + +func RemoveUserCascade(sourcePath string, indexPath utils.IndexPath, username string, allow bool) (int, error) { + return accessDb.RemoveUserCascade(sourcePath, indexPath, username, allow) +} + +func RemoveGroupCascade(sourcePath string, indexPath utils.IndexPath, groupname string, allow bool) (int, error) { + return accessDb.RemoveGroupCascade(sourcePath, indexPath, groupname, allow) +} + +func RemoveAllowUser(sourcePath string, indexPath utils.IndexPath, username string) (bool, error) { + return accessDb.RemoveAllowUser(sourcePath, indexPath, username) +} + +func RemoveAllowGroup(sourcePath string, indexPath utils.IndexPath, groupname string) (bool, error) { + return accessDb.RemoveAllowGroup(sourcePath, indexPath, groupname) +} + +func RemoveDenyUser(sourcePath string, indexPath utils.IndexPath, username string) (bool, error) { + return accessDb.RemoveDenyUser(sourcePath, indexPath, username) +} + +func RemoveDenyGroup(sourcePath string, indexPath utils.IndexPath, groupname string) (bool, error) { + return accessDb.RemoveDenyGroup(sourcePath, indexPath, groupname) +} + +func RemoveDenyAll(sourcePath string, indexPath utils.IndexPath) (bool, error) { + return accessDb.RemoveDenyAll(sourcePath, indexPath) +} + +func GetUserGroups(username string) []string { + return accessDb.GetUserGroups(username) +} + +func GetAllGroups() []string { + return accessDb.GetAllGroups() +} + +func AddUserToGroup(group, username string) error { + return accessDb.AddUserToGroup(group, username) +} + +func RemoveUserFromGroup(group, username string) error { + return accessDb.RemoveUserFromGroup(group, username) +} + +func SyncUserGroups(username string, newGroups []string) error { + return accessDb.SyncUserGroups(username, newGroups) +} + +func UpdateRulePath(sourcePath string, oldPath, newPath utils.IndexPath) error { + return accessDb.UpdateRulePath(sourcePath, oldPath, newPath) +} + +func RemoveRuleByPathKey(sourcePath, pathKey string) { + accessDb.RemoveRuleByPathKey(sourcePath, pathKey) +} + +func AddApiToken(tokenString string, userID uint64) error { + return accessDb.AddApiToken(tokenString, userID) +} + +func RemoveApiToken(tokenString string) error { + return accessDb.RemoveApiToken(tokenString) +} + +func IsTokenRevoked(token string) bool { + if accessDb == nil { + return false + } + return accessDb.IsTokenRevoked(token) +} + +func RevokeToken(token string) error { + return accessDb.RevokeToken(token) +} + +// CheckChildItemAccess filters directory listings using in-memory access rules. +func CheckChildItemAccess(response *iteminfo.FileInfo, idx *indexing.Index, username string) error { + if accessDb == nil { + return nil + } + return accessDb.CheckChildItemAccess(response, idx, username) +} + +// UpdateAccessRulesOnMove rewrites access rule paths when a resource moves within one source. +func UpdateAccessRulesOnMove(sourcePath string, oldPath, newPath utils.IndexPath) (int, error) { + if accessDb == nil { + return 0, nil + } + return accessDb.UpdateRules(sourcePath, oldPath, newPath) +} diff --git a/backend/internal/state/activity.go b/backend/internal/state/activity.go new file mode 100644 index 0000000000..e6f894e3bc --- /dev/null +++ b/backend/internal/state/activity.go @@ -0,0 +1,73 @@ +package state + +import ( + "fmt" + "strconv" + + activityrec "github.com/gtsteffaniak/filebrowser/backend/internal/activity" + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// InitActivityRecorder starts the global activity recorder using the SQL store. +func InitActivityRecorder(cfg settings.Database) { + if sqlDb == nil { + return + } + activityrec.Initialize(sqlDb, cfg) +} + +// StopActivityRecorder flushes pending activity and stops the recorder. +func StopActivityRecorder() { + activityrec.Stop() +} + +// RecordActivity appends a pre-built audit entry to the activity buffer. +// Handlers should prefer activity.RecordDownload and other activity.Record* helpers +// that enrich entries from HTTP context; use this only when the entry is already complete. +func RecordActivity(entry activitydb.Entry) { + activityrec.Record(entry) +} + +// ListActivity returns paginated activity rows with total count. +func ListActivity(filter activitydb.QueryFilter) ([]activitydb.FrontendEntry, int, error) { + if sqlDb == nil { + return nil, 0, fmt.Errorf("sql store not initialized") + } + total, err := sqlDb.CountActivity(filter) + if err != nil { + return nil, 0, err + } + rows, err := sqlDb.ListActivity(filter) + if err != nil { + return nil, 0, err + } + items := make([]activitydb.FrontendEntry, 0, len(rows)) + for _, row := range rows { + username := activityActorUsername(row.Entry, row.ActorUsername) + items = append(items, row.PrepForFrontend(username)) + } + return items, total, nil +} + +func activityActorUsername(row activitydb.Entry, joinedUsername string) string { + if row.UserID == 0 { + return users.AnonymousUserName + } + if joinedUsername != "" { + return joinedUsername + } + if u, err := GetUserByID(row.UserID); err == nil { + return u.Username + } + return strconv.FormatUint(row.UserID, 10) +} + +// ListActivityStats returns aggregated activity buckets for charts. +func ListActivityStats(filter activitydb.QueryFilter) ([]activitydb.StatsBucket, error) { + if sqlDb == nil { + return nil, fmt.Errorf("sql store not initialized") + } + return sqlDb.ListActivityStats(filter) +} diff --git a/backend/internal/state/analytics.go b/backend/internal/state/analytics.go new file mode 100644 index 0000000000..6a2dc92e19 --- /dev/null +++ b/backend/internal/state/analytics.go @@ -0,0 +1,92 @@ +package state + +import ( + "encoding/json" + "fmt" + "sync" + + "github.com/google/uuid" +) + +const ( + installationIDSettingKey = "analytics.installation_id" + analyticsEnabledKey = "analytics.enabled" +) + +var ( + analyticsEnabledMu sync.RWMutex + analyticsEnabled bool +) + +// InitAnalyticsSettings loads persisted analytics preferences from SQLite. +// Default is disabled for new installations. +func InitAnalyticsSettings() error { + enabled, err := loadAnalyticsEnabledFromDB() + if err != nil { + return err + } + analyticsEnabledMu.Lock() + analyticsEnabled = enabled + analyticsEnabledMu.Unlock() + return nil +} + +// IsAnalyticsEnabled reports whether anonymous deployment analytics is enabled. +func IsAnalyticsEnabled() bool { + analyticsEnabledMu.RLock() + defer analyticsEnabledMu.RUnlock() + return analyticsEnabled +} + +// SetAnalyticsEnabled persists the admin analytics toggle. +func SetAnalyticsEnabled(enabled bool) error { + if err := sqlDb.SaveSetting(analyticsEnabledKey, enabled); err != nil { + return fmt.Errorf("save analytics enabled: %w", err) + } + analyticsEnabledMu.Lock() + analyticsEnabled = enabled + analyticsEnabledMu.Unlock() + return nil +} + +func loadAnalyticsEnabledFromDB() (bool, error) { + raw, err := sqlDb.GetSetting(analyticsEnabledKey) + if err != nil { + return false, nil + } + var enabled bool + if unmarshalErr := json.Unmarshal(raw, &enabled); unmarshalErr != nil { + return false, fmt.Errorf("parse analytics enabled: %w", unmarshalErr) + } + return enabled, nil +} + +// GetOrCreateInstallationID returns a stable UUID v4 for this deployment. +func GetOrCreateInstallationID() (string, error) { + raw, err := sqlDb.GetSetting(installationIDSettingKey) + if err == nil { + var id string + if unmarshalErr := json.Unmarshal(raw, &id); unmarshalErr == nil && id != "" { + return id, nil + } + } + + id := uuid.New().String() + if err := sqlDb.SaveSetting(installationIDSettingKey, id); err != nil { + return "", fmt.Errorf("save installation id: %w", err) + } + return id, nil +} + +// CountAccessRules returns the total number of persisted access rules. +func CountAccessRules() (int, error) { + allRules, err := sqlDb.GetAllAccessRules() + if err != nil { + return 0, err + } + total := 0 + for _, byPath := range allRules { + total += len(byPath) + } + return total, nil +} diff --git a/backend/internal/state/auth_admin_promotion_test.go b/backend/internal/state/auth_admin_promotion_test.go new file mode 100644 index 0000000000..3a6cfefa63 --- /dev/null +++ b/backend/internal/state/auth_admin_promotion_test.go @@ -0,0 +1,151 @@ +package state + +import ( + "os" + "path/filepath" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func TestAuthAdminPromotionWithConfigUserDefaults(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + configPath := writeAuthAdminTestConfig(t) + settings.Initialize(configPath) + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + if !settings.Env.ConfigUserDefaultsSpecified { + t.Fatal("expected config userDefaults paths to be tracked") + } + if enforced := GetEnforcedUserDefaults(); enforced != (settings.UserDefaultsEnforcement{}) { + t.Fatalf("expected empty enforcement on seed, got %+v", enforced) + } + + for _, tc := range []struct { + name string + username string + loginMethod users.LoginMethod + }{ + {name: "oidc", username: "johndoe", loginMethod: users.LoginMethodOidc}, + {name: "jwt", username: "testadmin", loginMethod: users.LoginMethodJwt}, + {name: "ldap", username: "ldapadmin", loginMethod: users.LoginMethodLdap}, + {name: "proxy", username: "proxyadmin", loginMethod: users.LoginMethodProxy}, + } { + t.Run(tc.name, func(t *testing.T) { + promoteAuthAdmin(t, tc.username, tc.loginMethod) + }) + } +} + +func TestAuthAdminPromotionWithEnforcedAdminDefault(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + configPath := filepath.Join(t.TempDir(), "config.yaml") + configYAML := `server: + sources: + - path: "../frontend/tests/playwright-files" + config: + defaultEnabled: true + createUserDir: true +auth: + methods: + password: + enabled: true +userDefaults: + ui: + darkMode: true +` + if err := os.WriteFile(configPath, []byte(configYAML), 0o600); err != nil { + t.Fatal(err) + } + + settings.Initialize(configPath) + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + if err := PatchUserDefaultsEnforced([]byte(`{"account":{"permissions":{"admin":true}}}`)); err != nil { + t.Fatal(err) + } + + promoteAuthAdmin(t, "jwt-admin", users.LoginMethodJwt) +} + +func writeAuthAdminTestConfig(t *testing.T) string { + t.Helper() + configPath := filepath.Join(t.TempDir(), "config.yaml") + configYAML := `server: + sources: + - path: "../frontend/tests/playwright-files" + config: + defaultEnabled: true + createUserDir: true +auth: + methods: + password: + enabled: true +userDefaults: + preview: + image: true + ui: + darkMode: true + listing: + singleClick: false + account: + permissions: + admin: false + share: false +` + if err := os.WriteFile(configPath, []byte(configYAML), 0o600); err != nil { + t.Fatal(err) + } + return configPath +} + +func promoteAuthAdmin(t *testing.T, username string, loginMethod users.LoginMethod) { + t.Helper() + + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: username, + LoginMethod: loginMethod, + }, + } + settings.ApplyUserDefaults(u) + if err := CreateUser(u, ""); err != nil { + t.Fatal(err) + } + + loaded, err := GetUserByUsername(username) + if err != nil { + t.Fatal(err) + } + if loaded.Permissions.Admin { + t.Fatal("expected non-admin user before auth admin sync") + } + + loaded.Permissions.Admin = true + if err = UpdateUser(&loaded, "", "permissions"); err != nil { + t.Fatalf("auth admin promotion failed: %v", err) + } + + reloaded, err := GetUserByUsername(username) + if err != nil { + t.Fatal(err) + } + if !reloaded.Permissions.Admin { + t.Fatal("expected admin after auth admin sync") + } +} diff --git a/backend/internal/state/doc.go b/backend/internal/state/doc.go new file mode 100644 index 0000000000..d2ea23a4b8 --- /dev/null +++ b/backend/internal/state/doc.go @@ -0,0 +1,24 @@ +// Package state is the single gateway for all persisted application data. +// +// Architecture (do not bypass or duplicate this layer): +// +// - sqlDb (*sqldb.SQLStore): the on-disk SQLite database. All durable writes go here first +// (or atomically with cache updates in the same critical section). +// +// - TTL user record cache (30m) with SQLite on miss; sharesByHash, accessDb, indexInfoByPath, … remain authoritative +// for reads at runtime after Open/Initialize. Handlers and business logic must call exported +// state.* functions or *state.Store methods—not sqlDb directly and not package globals in internal/web. +// +// - accessDb (*access.Storage): access rules, groups, and API token hashes held in memory with +// write-through to sqlDb. Use state.AccessPermitted and the other helpers in access.go. +// +// Dependency injection: internal/ports defines narrow interfaces; *state.Store implements them. +// cmd (via internal/app.WireServices) constructs domain services (files, auth, indexing, activity) +// with explicit store dependencies. Domain packages must not import state. +// +// Legacy persistence: only cmd/migrate.go reads the old Storm database format for one-time migration. +// +// When adding new persisted entities: extend sqlDb, add a cache + mutex here, expose state.Foo +// read/write helpers on Store, wire load/save in initialize/Close. + +package state diff --git a/backend/internal/state/indexing.go b/backend/internal/state/indexing.go new file mode 100644 index 0000000000..973c7c1f17 --- /dev/null +++ b/backend/internal/state/indexing.go @@ -0,0 +1,179 @@ +package state + +import ( + "fmt" + + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/dbindex" +) + +// Index info operations + +// GetIndexInfo retrieves index info by path +// Returns a value (not pointer) to prevent modifications to the cache +func GetIndexInfo(path string) (dbindex.IndexInfo, error) { + indexMux.RLock() + defer indexMux.RUnlock() + + info, exists := indexInfoByPath[path] + if !exists { + return dbindex.IndexInfo{}, errors.ErrNotExist + } + + // Return a value copy - automatically immutable + return copyIndexInfo(info), nil +} + +// GetIndexInfoBySource retrieves all index info for a source +// Returns values (not pointers) to prevent modifications to the cache +func GetIndexInfoBySource(source string) ([]dbindex.IndexInfo, error) { + indexMux.RLock() + defer indexMux.RUnlock() + + var infoList []dbindex.IndexInfo + for _, info := range indexInfoByPath { + if info.Source == source { + infoList = append(infoList, copyIndexInfo(info)) + } + } + return infoList, nil +} + +// GetAllIndexInfo retrieves all index info +// Returns values (not pointers) to prevent modifications to the cache +func GetAllIndexInfo() ([]dbindex.IndexInfo, error) { + indexMux.RLock() + defer indexMux.RUnlock() + + infoList := make([]dbindex.IndexInfo, 0, len(indexInfoByPath)) + for _, info := range indexInfoByPath { + infoList = append(infoList, copyIndexInfo(info)) + } + return infoList, nil +} + +// CreateIndexInfo creates new index info with write-through to SQL +func CreateIndexInfo(info *dbindex.IndexInfo) error { + indexMux.Lock() + defer indexMux.Unlock() + + // 1. Check if index info already exists in cache (state) + if _, exists := indexInfoByPath[info.Path]; exists { + return fmt.Errorf("index info for path %s already exists", info.Path) + } + + // 2. Write to database + err := sqlDb.SaveIndexInfo(info) + if err != nil { + return err + } + + // 3. Update cache to match database + indexInfoByPath[info.Path] = info + + return nil +} + +// UpdateIndexInfo updates existing index info with write-through to SQL +func UpdateIndexInfo(info *dbindex.IndexInfo) error { + indexMux.Lock() + defer indexMux.Unlock() + + // 1. Check if index info exists in cache (state) + if _, exists := indexInfoByPath[info.Path]; !exists { + return fmt.Errorf("index info for path %s not found in cache", info.Path) + } + + // 2. Write to database + err := sqlDb.SaveIndexInfo(info) + if err != nil { + return err + } + + // 3. Update cache to match database + indexInfoByPath[info.Path] = info + + return nil +} + +// SaveIndexInfo saves index info with write-through to SQL +// DEPRECATED: Use CreateIndexInfo or UpdateIndexInfo instead +// This function is kept for backward compatibility but should not be used for new code +func SaveIndexInfo(info *dbindex.IndexInfo) error { + indexMux.Lock() + defer indexMux.Unlock() + + // Write through to SQL + err := sqlDb.SaveIndexInfo(info) + if err != nil { + return err + } + + // Update cache + indexInfoByPath[info.Path] = info + + return nil +} + +// DeleteIndexInfo deletes index info by path +func DeleteIndexInfo(path string) error { + indexMux.Lock() + defer indexMux.Unlock() + + // 1. Check if index info exists in cache (state) + if _, exists := indexInfoByPath[path]; !exists { + return fmt.Errorf("index info for path %s not found in cache", path) + } + + // 2. Delete from database + err := sqlDb.DeleteIndexInfo(path) + if err != nil { + return err + } + + // 3. Remove from cache to match database + delete(indexInfoByPath, path) + + return nil +} + +// copyIndexInfo creates a deep copy of an index info object and returns a value +func copyIndexInfo(info *dbindex.IndexInfo) dbindex.IndexInfo { + infoCopy := *info + + // Deep copy the scanners map + if info.Scanners != nil { + infoCopy.Scanners = make(map[string]*dbindex.PersistedScannerInfo, len(info.Scanners)) + for k, v := range info.Scanners { + if v != nil { + scannerCopy := *v + infoCopy.Scanners[k] = &scannerCopy + } + } + } + + return infoCopy +} + +// ResetAllIndexComplexities zeroes complexity on every cached index and its scanners, then persists. +func ResetAllIndexComplexities() error { + indexMux.Lock() + defer indexMux.Unlock() + + for path, info := range indexInfoByPath { + if info == nil { + continue + } + info.Complexity = 0 + for _, scanner := range info.Scanners { + if scanner != nil { + scanner.Complexity = 0 + } + } + if err := sqlDb.SaveIndexInfo(info); err != nil { + return err + } + indexInfoByPath[path] = info + } + return nil +} diff --git a/backend/internal/state/jwt_user_defaults_test.go b/backend/internal/state/jwt_user_defaults_test.go new file mode 100644 index 0000000000..dc4ca83b61 --- /dev/null +++ b/backend/internal/state/jwt_user_defaults_test.go @@ -0,0 +1,45 @@ +package state + +import ( + "path/filepath" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func TestJwtAutoCreateUserPersistsCreateUserDirScope(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + jwtConfig := "../../../_docker/src/jwt/backend/config.yaml" + settings.Initialize(jwtConfig) + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "testadmin", + LoginMethod: users.LoginMethodJwt, + }, + } + settings.ApplyUserDefaults(u) + if err = CreateUser(u, ""); err != nil { + t.Fatal(err) + } + + loaded, err := GetUserByUsername("testadmin") + if err != nil { + t.Fatal(err) + } + if len(loaded.BackendScopes) != 1 { + t.Fatalf("scopes: %+v", loaded.BackendScopes) + } + if loaded.BackendScopes[0].Scope != "/testadmin" { + t.Fatalf("scope=%q want /testadmin after reload", loaded.BackendScopes[0].Scope) + } +} diff --git a/backend/internal/state/noauth_admin.go b/backend/internal/state/noauth_admin.go new file mode 100644 index 0000000000..6d20b57345 --- /dev/null +++ b/backend/internal/state/noauth_admin.go @@ -0,0 +1,124 @@ +package state + +import ( + "fmt" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/sqldb" + "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/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/go-logger/logger" +) + +func isUserLookupNotFound(err error) bool { + if err == nil { + return false + } + return err == errors.ErrNotExist || err.Error() == "user not found" +} + +func noAuthAdminUsername() string { + admin := settings.Config.Auth.AdminUsername + if admin == "" { + return "admin" + } + return admin +} + +// ResolveNoAuthUser returns the user noauth mode impersonates at runtime: auth.adminUsername when +// present, otherwise the sole user when exactly one account exists. +func ResolveNoAuthUser() (users.User, error) { + target := noAuthAdminUsername() + user, err := GetUserByUsername(target) + if err == nil { + return user, nil + } + if !isUserLookupNotFound(err) { + return users.User{}, err + } + + allUsers, err := GetAllUsers() + if err != nil { + return users.User{}, err + } + if len(allUsers) == 1 { + return allUsers[0], nil + } + return users.User{}, errors.ErrNotExist +} + +// EnsureNoAuthAdminUserAfterMigration runs once after Bolt→SQLite user import when noauth is enabled. +// It never renames or modifies existing users. A new admin account is created only when +// auth.adminUsername is missing and more than one user was migrated (a single migrated user is +// used at runtime via ResolveNoAuthUser). +func EnsureNoAuthAdminUserAfterMigration(store *sqldb.SQLStore) error { + if store == nil || !settings.Config.Auth.Methods.NoAuth { + return nil + } + + target := noAuthAdminUsername() + _, err := store.GetUserByUsername(target) + if err == nil { + return nil + } + if !isUserLookupNotFound(err) { + return fmt.Errorf("lookup noauth admin user %q: %w", target, err) + } + + allUsers, err := store.ListUsers() + if err != nil { + return fmt.Errorf("list users for noauth migration setup: %w", err) + } + if len(allUsers) <= 1 { + return nil + } + + if err := createNoAuthAdminUser(store); err != nil { + return fmt.Errorf("create noauth admin user: %w", err) + } + logger.Infof("noauth: created admin user %q after migration", target) + return nil +} + +func createNoAuthAdminUser(store *sqldb.SQLStore) error { + target := noAuthAdminUsername() + + user := &users.User{} + ApplyUserDefaults(user) + user.Username = target + + password := settings.Config.Auth.AdminPassword + if password == "" { + password = "admin" + } + hashedPassword, err := utils.HashPwd(password) + if err != nil { + return fmt.Errorf("hash admin password: %w", err) + } + user.Password = hashedPassword + user.LoginMethod = users.LoginMethodPassword + user.LockPassword = false + user.Permissions = settings.AdminPerms() + user.BackendScopes = []users.BackendScope{} + for _, val := range settings.Config.Server.Sources { + user.BackendScopes = append(user.BackendScopes, users.BackendScope{ + Path: val.Path, + Scope: "/", + }) + } + adminPerms := settings.AdminSourceFilePermissions() + for i := range user.BackendScopes { + user.BackendScopes[i].Permissions = adminPerms + } + users.SyncBackendSourcePermissionsMap(user) + user.Version = users.CurrentUserMigrationVersion + + nid, err := utils.RandomUint64ID() + if err != nil { + return fmt.Errorf("allocate admin user id: %w", err) + } + user.ID = nid + + return store.CreateUser(user) +} diff --git a/backend/internal/state/proxy_user_test.go b/backend/internal/state/proxy_user_test.go new file mode 100644 index 0000000000..41c3878652 --- /dev/null +++ b/backend/internal/state/proxy_user_test.go @@ -0,0 +1,57 @@ +package state + +import ( + "path/filepath" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func TestProxyUserCreateHasSharePermission(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + proxyConfig := "../../../_docker/src/proxy/backend/config.yaml" + settings.Initialize(proxyConfig) + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "demo-127.0.0.1", + LoginMethod: users.LoginMethodProxy, + }, + } + settings.ApplyUserDefaults(u) + if err = CreateUser(u, ""); err != nil { + t.Fatal(err) + } + + loaded, err := GetUserByUsername("demo-127.0.0.1") + if err != nil { + t.Fatal(err) + } + if !loaded.Permissions.Share { + t.Fatalf("Share=false after create+reload; perms=%+v defaults.share=%v", + loaded.Permissions, settings.Config.UserDefaults.Account.Permissions.Share) + } + + _ = Close() + _, err = Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + + reloaded, err := GetUserByUsername("demo-127.0.0.1") + if err != nil { + t.Fatal(err) + } + if !reloaded.Permissions.Share { + t.Fatalf("Share=false after DB reload; perms=%+v", reloaded.Permissions) + } +} diff --git a/backend/internal/state/quick_setup.go b/backend/internal/state/quick_setup.go new file mode 100644 index 0000000000..f556465536 --- /dev/null +++ b/backend/internal/state/quick_setup.go @@ -0,0 +1,91 @@ +package state + +import ( + "fmt" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/go-logger/logger" +) + +// QuickSetup creates the initial admin user on first run. +func QuickSetup() error { + if settings.Env.IsPlaywright || settings.Env.IsDevMode { + settings.Env.IsFirstLoad = false + } else { + settings.Env.IsFirstLoad = true + } + + settings.Config.Auth.Key = utils.GenerateKey() + + passwordAuth := settings.Config.Auth.Methods.PasswordAuth.Enabled + noAuth := settings.Config.Auth.Methods.NoAuth + + if !passwordAuth && !noAuth { + return nil + } + + user := &users.User{} + ApplyUserDefaults(user) + + user.Username = settings.Config.Auth.AdminUsername + if user.Username == "" { + user.Username = "admin" + } + + if settings.Config.Auth.AdminPassword == "" { + settings.Config.Auth.AdminPassword = "admin" + } + + user.Permissions.Admin = true + user.LoginMethod = users.LoginMethodPassword + + user.BackendScopes = []users.BackendScope{} + for _, val := range settings.Config.Server.Sources { + user.BackendScopes = append(user.BackendScopes, users.BackendScope{ + Path: val.Path, + Scope: "/", + }) + } + + user.LockPassword = false + user.Permissions = settings.AdminPerms() + adminPerms := settings.AdminSourceFilePermissions() + for i := range user.BackendScopes { + user.BackendScopes[i].Permissions = adminPerms + } + users.SyncBackendSourcePermissionsMap(user) + user.Version = users.CurrentUserMigrationVersion + user.ShowFirstLogin = settings.Env.IsFirstLoad && user.Permissions.Admin + + logger.Debugf("Creating user as admin: %v", user.Username) + + hashedPassword, hashErr := utils.HashPwd(settings.Config.Auth.AdminPassword) + if hashErr != nil { + return fmt.Errorf("failed to hash admin password: %w", hashErr) + } + user.Password = hashedPassword + + nid, err := utils.RandomUint64ID() + if err != nil { + return fmt.Errorf("failed to allocate admin user id: %w", err) + } + user.ID = nid + + if err := sqlDb.CreateUser(user); err != nil { + return fmt.Errorf("failed to create admin user: %w", err) + } + logger.Debug("quickSetup created admin user", + "username", user.Username, + "userID", user.ID, + "permAdmin", user.Permissions.Admin, + "permShare", user.Permissions.Share, + "permModify", user.Permissions.Modify, + "permCreate", user.Permissions.Create, + "permDelete", user.Permissions.Delete, + "permDownload", user.Permissions.Download, + "permApi", user.Permissions.Api, + ) + return nil +} diff --git a/backend/internal/state/shares.go b/backend/internal/state/shares.go new file mode 100644 index 0000000000..2ea82a40c3 --- /dev/null +++ b/backend/internal/state/shares.go @@ -0,0 +1,456 @@ +package state + +import ( + "fmt" + "net/http" + "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/go-logger/logger" +) + +// Share operations + +// GetShare retrieves a share by hash +// Returns a value (not pointer) to prevent modifications to the cache +func GetShare(hash string) (share.Share, error) { + sharesMux.RLock() + defer sharesMux.RUnlock() + + link, exists := sharesByHash[hash] + if !exists { + return share.Share{}, fmt.Errorf("share not found") + } + + // Check if expired + if !link.KeepAfterExpiration && link.Expire > 0 && link.Expire < time.Now().Unix() { + return share.Share{}, fmt.Errorf("share expired") + } + + // Return a value copy - automatically immutable + return copyShareLink(link), nil +} + +// GetAllShares retrieves all non-expired shares +// Returns values (not pointers) to prevent modifications to the cache +func GetAllShares() ([]share.Share, error) { + sharesMux.RLock() + defer sharesMux.RUnlock() + + now := time.Now().Unix() + var shares []share.Share + + for _, link := range sharesByHash { + if link.Expire == 0 || link.Expire > now || link.KeepAfterExpiration { + shares = append(shares, copyShareLink(link)) + } + } + + return shares, nil +} + +// GetSharesByUserID retrieves all non-expired shares owned by userID. +// Returns values (not pointers) to prevent modifications to the cache +func GetSharesByUserID(userID uint64) ([]share.Share, error) { + sharesMux.RLock() + defer sharesMux.RUnlock() + + now := time.Now().Unix() + var shares []share.Share + + for _, link := range sharesByHash { + if link.UserID == userID { + if link.Expire == 0 || link.Expire > now || link.KeepAfterExpiration { + shares = append(shares, copyShareLink(link)) + } + } + } + + return shares, nil +} + +// GetSharesByPath retrieves shares for a specific source and path +// Returns values (not pointers) to prevent modifications to the cache +func GetSharesByPath(source, path string) ([]share.Share, error) { + sharesMux.RLock() + defer sharesMux.RUnlock() + + pathKey := makePathKey(source, path) + hashes, exists := sharesByPath[pathKey] + + if !exists { + return []share.Share{}, nil + } + + var shares []share.Share + for _, hash := range hashes { + if link, exists := sharesByHash[hash]; exists { + shares = append(shares, copyShareLink(link)) + } + } + + return shares, nil +} + +// CreateShare creates a new share with write-through to SQL +func CreateShare(link *share.Share) error { + sharesMux.Lock() + defer sharesMux.Unlock() + + // 1. Check if share already exists in cache (state) + if _, exists := sharesByHash[link.Hash]; exists { + return fmt.Errorf("share with hash %s already exists", link.Hash) + } + + // 2. Write to database + err := sqlDb.SaveShare(link) + if err != nil { + return err + } + + // 3. Update cache to match database + sharesByHash[link.Hash] = link + pathKey := makePathKey(link.SourcePath, link.Path) + + // Add to path index + sharesByPath[pathKey] = append(sharesByPath[pathKey], link.Hash) + + return nil +} + +// UpdateShare updates an existing share with write-through to SQL +// Takes a function that modifies the share to ensure thread-safe updates +func UpdateShare(hash string, updateFn func(*share.Share) error) error { + sharesMux.Lock() + defer sharesMux.Unlock() + + // 1. Check if share exists in cache (state) + link, exists := sharesByHash[hash] + if !exists { + return fmt.Errorf("share not found in cache") + } + + // Apply updates to get the new state + if err := updateFn(link); err != nil { + return err + } + + // 2. Write to database + err := sqlDb.SaveShare(link) + if err != nil { + return err + } + + // 3. Cache is already updated since we modified the pointer directly + + return nil +} + +// IncrementShareDownloadCount updates share entity state: global download count and, when +// per-user limits are enabled, the count for viewerUsername. This is not activity audit +// logging — use activity.RecordDownload for the Activity Viewer. Callers must not mutate +// download counters on share snapshots directly. +func IncrementShareDownloadCount(hash, viewerUsername string) error { + sharesMux.Lock() + defer sharesMux.Unlock() + link, exists := sharesByHash[hash] + if !exists { + return fmt.Errorf("share not found in cache") + } + link.Downloads++ + if link.PerUserDownloadLimit { + link.IncrementUserDownload(viewerUsername) + } + return sqlDb.SaveShare(link) +} + +// DeleteShare deletes a share by hash +func DeleteShare(hash string) error { + sharesMux.Lock() + defer sharesMux.Unlock() + + // 1. Check if share exists in cache (state) + link, exists := sharesByHash[hash] + if !exists { + return fmt.Errorf("share not found in cache") + } + + // 2. Delete from database + err := sqlDb.DeleteShare(hash) + if err != nil { + return err + } + + // 3. Remove from cache to match database + delete(sharesByHash, hash) + + // Remove from path index + pathKey := makePathKey(link.SourcePath, link.Path) + hashes := sharesByPath[pathKey] + for i, h := range hashes { + if h == hash { + sharesByPath[pathKey] = append(hashes[:i], hashes[i+1:]...) + break + } + } + + // Clean up empty path entries + if len(sharesByPath[pathKey]) == 0 { + delete(sharesByPath, pathKey) + } + + return nil +} + +// UpdateSharePath updates the path for a specific share +func UpdateSharePath(hash, newPath string) error { + sharesMux.Lock() + defer sharesMux.Unlock() + + // 1. Check if share exists in cache (state) + link, exists := sharesByHash[hash] + if !exists { + return fmt.Errorf("share not found in cache") + } + + oldPathKey := makePathKey(link.SourcePath, link.Path) + + // 2. Update database + err := sqlDb.UpdateSharePath(hash, newPath) + if err != nil { + return err + } + + // 3. Update cache to match database + link.Path = newPath + newPathKey := makePathKey(link.SourcePath, newPath) + + // Remove from old path index + if oldHashes, exists := sharesByPath[oldPathKey]; exists { + for i, h := range oldHashes { + if h == hash { + sharesByPath[oldPathKey] = append(oldHashes[:i], oldHashes[i+1:]...) + break + } + } + if len(sharesByPath[oldPathKey]) == 0 { + delete(sharesByPath, oldPathKey) + } + } + + // Add to new path index + sharesByPath[newPathKey] = append(sharesByPath[newPathKey], hash) + + return nil +} + +// UpdateSharesPaths updates paths for shares when a resource is moved +func UpdateSharesPaths(oldSource, oldPath, newSource, newPath string) error { + sharesMux.Lock() + defer sharesMux.Unlock() + + // Update SQL + err := sqlDb.UpdateSharesPaths(oldSource, oldPath, newSource, newPath) + if err != nil { + return err + } + + // Update cache + oldPathKey := makePathKey(oldSource, oldPath) + if hashes, exists := sharesByPath[oldPathKey]; exists { + for _, hash := range hashes { + if link, exists := sharesByHash[hash]; exists { + link.SourcePath = newSource + link.Path = newPath + } + } + + // Move hashes to new path key + newPathKey := makePathKey(newSource, newPath) + sharesByPath[newPathKey] = hashes + delete(sharesByPath, oldPathKey) + } + + return nil +} + +// removeShareFromPathIndexLocked removes hash from sharesByPath for the given source/path key. Caller must hold sharesMux. +func removeShareFromPathIndexLocked(source, path, hash string) { + adjustedPath := utils.AddTrailingSlashIfNotExists(path) + adjustedSource := utils.AddTrailingSlashIfNotExists(source) + key := makePathKey(adjustedSource, adjustedPath) + if inner, ok := sharesByPath[key]; ok { + out := make([]string, 0, len(inner)) + for _, h := range inner { + if h != hash { + out = append(out, h) + } + } + if len(out) == 0 { + delete(sharesByPath, key) + } else { + sharesByPath[key] = out + } + } +} + +// appendShareToPathIndexLocked appends hash to sharesByPath for source/path. Caller must hold sharesMux. +func appendShareToPathIndexLocked(source, path, hash string) { + adjustedPath := utils.AddTrailingSlashIfNotExists(path) + adjustedSource := utils.AddTrailingSlashIfNotExists(source) + key := makePathKey(adjustedSource, adjustedPath) + sharesByPath[key] = append(sharesByPath[key], hash) +} + +// UpdateSharesForMovedResource updates share rows whose stored path is under a moved index path (same logic as +// share.Storage.UpdateShares). It is the only supported way to reconcile shares after a filesystem move. +// Returns hashes of updated shares (e.g. for logging). +func UpdateSharesForMovedResource(oldSource, oldPath, newSource, newPath string) ([]string, error) { + 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) { + continue + } + + removeShareFromPathIndexLocked(l.SourcePath, l.Path, l.Hash) + + l.SourcePath = newSource + l.Path = newPath + + if err := sqlDb.SaveShare(l); err != nil { + logger.Error("failed to save updated share after resource move", "hash", l.Hash, "error", err) + return updatedHashes, err + } + + appendShareToPathIndexLocked(l.SourcePath, l.Path, l.Hash) + updatedHashes = append(updatedHashes, l.Hash) + } + return updatedHashes, nil +} + +// IsShared checks if a path is shared by the given owner user id. +func IsShared(source, path string, userID uint64) bool { + sharesMux.RLock() + defer sharesMux.RUnlock() + + // Normalize path + normalizedPath := strings.TrimSuffix(path, "/") + if normalizedPath == "" { + normalizedPath = "/" + } + pathKey := makePathKey(source, normalizedPath) + + hashes, exists := sharesByPath[pathKey] + if !exists { + return false + } + + now := time.Now().Unix() + for _, hash := range hashes { + link, exists := sharesByHash[hash] + if !exists { + continue + } + if link.UserID == userID { + if link.Expire == 0 || link.Expire > now { + return true + } + } + } + + return false +} + +// PrepSharesForFrontend builds API-safe ShareFrontend copies for share pointers. +func PrepSharesForFrontend(viewer *users.User, r *http.Request, publicHost, publicScheme string, links ...*share.Share) []*share.ShareFrontend { + ownerLookup := func(userID uint64) string { + u, err := GetUserByID(userID) + if err != nil { + return "" + } + return u.Username + } + return share.PrepForFrontend(viewer, r, publicHost, publicScheme, ownerLookup, links...) +} + +// PrepShareValuesForFrontend builds API-safe ShareFrontend copies from immutable share values. +func PrepShareValuesForFrontend(viewer *users.User, r *http.Request, publicHost, publicScheme string, shares []share.Share) []*share.ShareFrontend { + if len(shares) == 0 { + return utils.NonNilSlice([]*share.ShareFrontend(nil)) + } + ptrs := make([]*share.Share, len(shares)) + for i := range shares { + s := shares[i] + ptrs[i] = new(share.Share) + *ptrs[i] = s + } + return PrepSharesForFrontend(viewer, r, publicHost, publicScheme, ptrs...) +} + +// PrepShareForFrontend builds a single API-safe ShareFrontend copy from an immutable share value. +func PrepShareForFrontend(viewer *users.User, r *http.Request, publicHost, publicScheme string, sh share.Share) *share.ShareFrontend { + prepped := PrepShareValuesForFrontend(viewer, r, publicHost, publicScheme, []share.Share{sh}) + if len(prepped) == 0 { + return nil + } + return prepped[0] +} + +// GetSharesInScope returns non-expired shares for scopePath on source owned by userID. +func GetSharesInScope(scopePath, source string, userID uint64) ([]*share.Share, error) { + links, err := GetSharesByPath(source, scopePath) + if err != nil { + return nil, err + } + now := time.Now().Unix() + filtered := make([]*share.Share, 0, len(links)) + for i := range links { + l := links[i] + if l.UserID == userID && (l.Expire == 0 || l.Expire > now || l.KeepAfterExpiration) { + copy := l + filtered = append(filtered, ©) + } + } + return filtered, nil +} + +// copyShareLink creates a deep copy of a share link +func copyShareLink(link *share.Share) share.Share { + // Shallow copy (now safe since there's no mutex) + linkCopy := *link + + // Deep copy slices + if link.AllowedUsernames != nil { + linkCopy.AllowedUsernames = make([]string, len(link.AllowedUsernames)) + copy(linkCopy.AllowedUsernames, link.AllowedUsernames) + } + + if link.SidebarLinks != nil { + linkCopy.SidebarLinks = make([]users.SidebarLink, len(link.SidebarLinks)) + copy(linkCopy.SidebarLinks, link.SidebarLinks) + } + + // Deep copy map + if link.UserDownloads != nil { + linkCopy.UserDownloads = make(map[string]int, len(link.UserDownloads)) + for k, v := range link.UserDownloads { + linkCopy.UserDownloads[k] = v + } + } + + //nolint:govet // We intentionally don't copy the Mu field to avoid mutex copy + return linkCopy +} diff --git a/backend/internal/state/shares_frontend_test.go b/backend/internal/state/shares_frontend_test.go new file mode 100644 index 0000000000..9ac0260985 --- /dev/null +++ b/backend/internal/state/shares_frontend_test.go @@ -0,0 +1,39 @@ +package state + +import ( + "encoding/json" + "net/http/httptest" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" +) + +func TestPrepShareValuesForFrontend_emptyReturnsJSONArray(t *testing.T) { + got := PrepShareValuesForFrontend(nil, httptest.NewRequest("GET", "/", nil), "example.com", "https", nil) + if got == nil { + t.Fatal("expected non-nil slice for empty shares") + } + if len(got) != 0 { + t.Fatalf("expected empty slice, got len=%d", len(got)) + } + raw, err := json.Marshal(got) + if err != nil { + t.Fatalf("marshal: %v", err) + } + if string(raw) != "[]" { + t.Fatalf("expected JSON [], got %s", string(raw)) + } +} + +func TestPrepShareValuesForFrontend_nonEmptyPreservesEntries(t *testing.T) { + shares := []share.Share{{ + ShareColumns: share.ShareColumns{Hash: "abc123", Path: "/docs"}, + }} + got := PrepShareValuesForFrontend(nil, httptest.NewRequest("GET", "/", nil), "example.com", "https", shares) + if len(got) != 1 { + t.Fatalf("expected 1 share, got %d", len(got)) + } + if got[0].Hash != "abc123" { + t.Fatalf("hash = %q, want abc123", got[0].Hash) + } +} diff --git a/backend/internal/state/source_access_defaults.go b/backend/internal/state/source_access_defaults.go new file mode 100644 index 0000000000..584172f6a6 --- /dev/null +++ b/backend/internal/state/source_access_defaults.go @@ -0,0 +1,264 @@ +package state + +import ( + "encoding/json" + "fmt" + "reflect" + "sync" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +const sourceAccessDefaultsSettingKey = "sourceAccessDefaults" + +var ( + sourceAccessMu sync.RWMutex + sourceAccessEnforcedDefault settings.SourceFilePermissionsEnforcement +) + +type sourceAccessSettingsDocument struct { + DefaultPermissions users.SourceFilePermissions `json:"defaultPermissions"` + EnforcedPermissions settings.SourceFilePermissionsEnforcement `json:"enforcedPermissions,omitempty"` +} + +// InitSourceAccessDefaults loads persisted source access defaults and applies them to every source. +func InitSourceAccessDefaults() error { + if sqlDb == nil { + return fmt.Errorf("sqlDb not initialized") + } + + doc, found, err := loadSourceAccessSettingsDocument() + if err != nil { + return err + } + if !found { + perms := deriveInitialSourceAccessDefaults() + doc = sourceAccessSettingsDocument{DefaultPermissions: perms} + if saveErr := saveSourceAccessSettingsDocument(doc); saveErr != nil { + return saveErr + } + } + + if settings.Env.ConfigSourceDefaultPermissions != nil { + overlaid := settings.OverlayConfigSourceDefaults(doc.DefaultPermissions) + if !reflect.DeepEqual(doc.DefaultPermissions, overlaid) { + doc.DefaultPermissions = overlaid + if saveErr := saveSourceAccessSettingsDocument(doc); saveErr != nil { + return fmt.Errorf("save config-synced source defaults: %w", saveErr) + } + } + } + + settings.ApplySourceAccessDefaultsToAllSources(doc.DefaultPermissions) + sourceAccessMu.Lock() + sourceAccessEnforcedDefault = doc.EnforcedPermissions + sourceAccessMu.Unlock() + + if !found { + return stripLegacyFilePermissionsFromUserDefaults() + } + return nil +} + +func deriveInitialSourceAccessDefaults() users.SourceFilePermissions { + for _, src := range settings.Config.Server.Sources { + if src != nil && !src.Config.DefaultPermissions.IsUnset() { + return settings.NormalizeSourceFilePermissions(src.Config.DefaultPermissions) + } + } + return settings.BuiltinDefaultSourceFilePermissions() +} + +func loadSourceAccessSettingsDocument() (sourceAccessSettingsDocument, bool, error) { + raw, err := sqlDb.GetSetting(sourceAccessDefaultsSettingKey) + if err != nil { + if err.Error() == fmt.Sprintf("setting not found: %s", sourceAccessDefaultsSettingKey) { + return sourceAccessSettingsDocument{}, false, nil + } + return sourceAccessSettingsDocument{}, false, err + } + + var probe map[string]json.RawMessage + if err := json.Unmarshal(raw, &probe); err != nil { + return sourceAccessSettingsDocument{}, false, fmt.Errorf("parse %s: %w", sourceAccessDefaultsSettingKey, err) + } + if _, wrapped := probe["defaultPermissions"]; wrapped { + var doc sourceAccessSettingsDocument + if err := json.Unmarshal(raw, &doc); err != nil { + return sourceAccessSettingsDocument{}, false, fmt.Errorf("parse %s: %w", sourceAccessDefaultsSettingKey, err) + } + doc.DefaultPermissions = settings.NormalizeSourceFilePermissions(doc.DefaultPermissions) + return doc, true, nil + } + + var legacy users.SourceFilePermissions + if err := json.Unmarshal(raw, &legacy); err != nil { + return sourceAccessSettingsDocument{}, false, fmt.Errorf("parse legacy %s: %w", sourceAccessDefaultsSettingKey, err) + } + return sourceAccessSettingsDocument{ + DefaultPermissions: settings.NormalizeSourceFilePermissions(legacy), + }, true, nil +} + +func saveSourceAccessSettingsDocument(doc sourceAccessSettingsDocument) error { + doc.DefaultPermissions = settings.NormalizeSourceFilePermissions( + users.MarkSourceFilePermissionsConfigured(doc.DefaultPermissions), + ) + return sqlDb.SaveSetting(sourceAccessDefaultsSettingKey, doc) +} + +func currentSourceAccessSettingsDocument() sourceAccessSettingsDocument { + sourceAccessMu.RLock() + defer sourceAccessMu.RUnlock() + return sourceAccessSettingsDocument{ + DefaultPermissions: GetSourceAccessDefaults(), + EnforcedPermissions: sourceAccessEnforcedDefault, + } +} + +// GetSourceAccessDefaults returns the global default file permissions for sources. +func GetSourceAccessDefaults() users.SourceFilePermissions { + return settings.DefaultSourceFilePermissions() +} + +// SourceSettings is the admin API payload for GET/PATCH /api/settings/source. +type SourceSettings struct { + DefaultPermissions users.SourceFilePermissions `json:"defaultPermissions"` + EnforcedPermissions settings.SourceFilePermissionsEnforcement `json:"enforcedPermissions"` + LockedFromConfigPaths []string `json:"lockedFromConfigPaths,omitempty"` + LockMessage string `json:"lockMessage,omitempty"` +} + +// GetSourceSettings returns admin-editable source-wide settings. +func GetSourceSettings() SourceSettings { + doc := currentSourceAccessSettingsDocument() + lockedPaths := settings.ConfigSourceDefaultLockedPaths() + lockMessage := "" + if len(lockedPaths) > 0 { + lockMessage = settings.SourceDefaultsConfigLockMessage + } + return SourceSettings{ + DefaultPermissions: doc.DefaultPermissions, + EnforcedPermissions: doc.EnforcedPermissions, + LockedFromConfigPaths: lockedPaths, + LockMessage: lockMessage, + } +} + +// GetEnforcedSourcePermissions returns universal enforced source permission flags. +func GetEnforcedSourcePermissions() settings.SourceFilePermissionsEnforcement { + sourceAccessMu.RLock() + defer sourceAccessMu.RUnlock() + return sourceAccessEnforcedDefault +} + +// PatchSourceAccessDefaults merges a partial defaultPermissions patch and persists. +func PatchSourceAccessDefaults(patchJSON []byte) error { + if err := settings.ValidateSourceDefaultsPatchNotConfigLocked(patchJSON); err != nil { + return err + } + current := GetSourceAccessDefaults() + merged, mergeErr := settings.MergeSourceDefaultsPatchJSON(current, patchJSON) + if mergeErr != nil { + return mergeErr + } + return SetSourceAccessDefaults(merged) +} + +// SetSourceAccessDefaults persists and applies new global source file permission defaults. +func SetSourceAccessDefaults(perms users.SourceFilePermissions) error { + if sqlDb == nil { + return fmt.Errorf("sqlDb not initialized") + } + sourceAccessMu.Lock() + doc := sourceAccessSettingsDocument{ + DefaultPermissions: settings.NormalizeSourceFilePermissions(users.MarkSourceFilePermissionsConfigured(perms)), + EnforcedPermissions: sourceAccessEnforcedDefault, + } + if err := saveSourceAccessSettingsDocument(doc); err != nil { + sourceAccessMu.Unlock() + return err + } + settings.ApplySourceAccessDefaultsToAllSources(doc.DefaultPermissions) + hasEnforced := len(settings.EnforcedSourcePermissionFlags(doc.EnforcedPermissions)) > 0 + sourceAccessMu.Unlock() + + if !hasEnforced { + return nil + } + return ResyncEnforcedSourcePermissionsForAllUsers() +} + +// PatchSourceAccessEnforced merges enforcement patch JSON and resyncs all users. +func PatchSourceAccessEnforced(patchJSON []byte) error { + sourceAccessMu.Lock() + merged, mergeErr := settings.MergeSourceEnforcedPatchJSON(sourceAccessEnforcedDefault, patchJSON) + if mergeErr != nil { + sourceAccessMu.Unlock() + return mergeErr + } + doc := sourceAccessSettingsDocument{ + DefaultPermissions: GetSourceAccessDefaults(), + EnforcedPermissions: merged, + } + if saveErr := saveSourceAccessSettingsDocument(doc); saveErr != nil { + sourceAccessMu.Unlock() + return fmt.Errorf("save enforced source permissions: %w", saveErr) + } + sourceAccessEnforcedDefault = merged + sourceAccessMu.Unlock() + + return ResyncEnforcedSourcePermissionsForAllUsers() +} + +func stripLegacyFilePermissionsFromUserDefaults() error { + patch := map[string]interface{}{ + "account": map[string]interface{}{ + "permissions": map[string]interface{}{ + "modify": nil, + "create": nil, + "delete": nil, + "download": nil, + "view": nil, + }, + }, + } + patchJSON, err := json.Marshal(patch) + if err != nil { + return err + } + merged, mergeErr := settings.MergeUserDefaultsPatchJSON(userDefaultsDefault, patchJSON) + if mergeErr != nil { + return mergeErr + } + userDefaultsDefault = merged + settings.Config.UserDefaults = merged + if saveErr := sqlDb.SaveSetting(userDefaultsDefaultSettingKey, merged); saveErr != nil { + return saveErr + } + enfPatch := map[string]interface{}{ + "account": map[string]interface{}{ + "permissions": map[string]interface{}{ + "modify": false, + "create": false, + "delete": false, + "download": false, + "view": false, + }, + }, + } + enfJSON, err := json.Marshal(enfPatch) + if err != nil { + return err + } + mergedEnf, mergeErr := settings.MergeEnforcedPatchJSON(userDefaultsEnforcedDefault, enfJSON) + if mergeErr != nil { + return mergeErr + } + userDefaultsEnforcedDefault = mergedEnf + if saveErr := sqlDb.SaveSetting(userDefaultsEnforcedDefaultKey, mergedEnf); saveErr != nil { + return saveErr + } + return nil +} diff --git a/backend/internal/state/source_defaults_config_integration_test.go b/backend/internal/state/source_defaults_config_integration_test.go new file mode 100644 index 0000000000..49f5aeb63b --- /dev/null +++ b/backend/internal/state/source_defaults_config_integration_test.go @@ -0,0 +1,53 @@ +package state + +import ( + "path/filepath" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func TestInitSourceAccessDefaults_overlaysConfigOnRestart(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + t.Setenv("FILEBROWSER_PLAYWRIGHT_TEST", "true") + settings.Initialize("../../../_docker/src/jwt/backend/config.yaml") + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + access := GetSourceAccessDefaults() + if !access.Modify || !access.Create { + t.Fatalf("initial source access defaults: %+v", access) + } + + // Simulate admin changing modify in SQLite; config should re-overlay on next init. + sourceAccessMu.Lock() + doc := sourceAccessSettingsDocument{ + DefaultPermissions: users.SourceFilePermissions{ + View: true, Download: true, Modify: false, Create: true, Delete: false, + }, + EnforcedPermissions: sourceAccessEnforcedDefault, + } + if saveErr := saveSourceAccessSettingsDocument(doc); saveErr != nil { + sourceAccessMu.Unlock() + t.Fatal(saveErr) + } + sourceAccessMu.Unlock() + + if err := InitSourceAccessDefaults(); err != nil { + t.Fatal(err) + } + + access = GetSourceAccessDefaults() + if !access.Modify { + t.Fatal("expected modify re-overlaid from jwt config on restart") + } + if settings.Env.ConfigSourceDefaultPermissions == nil { + t.Fatal("expected config source default permissions for jwt yaml") + } +} diff --git a/backend/internal/state/source_enforcement_sync.go b/backend/internal/state/source_enforcement_sync.go new file mode 100644 index 0000000000..6e0535788b --- /dev/null +++ b/backend/internal/state/source_enforcement_sync.go @@ -0,0 +1,64 @@ +package state + +import ( + "fmt" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/go-logger/logger" +) + +// ApplyEnforcedSourcePermissionsSyncToUser applies enforced source permission defaults onto u in memory. +// Returns true if scope permissions changed. +func ApplyEnforcedSourcePermissionsSyncToUser(u *users.User) bool { + if u == nil { + return false + } + defaults := GetSourceAccessDefaults() + enforced := GetEnforcedSourcePermissions() + return settings.SyncEnforcedSourcePermissionsOntoUser(u, defaults, enforced) +} + +// ResyncEnforcedSourcePermissionsForAllUsers writes enforced source permission defaults into SQLite for every user when they differ. +// +// Lock ordering: snapshot sourceAccessMu, release it, then acquire usersMux. +// Callers holding usersMux must snapshot enforcement via GetEnforcedSourcePermissions before locking usersMux. +func ResyncEnforcedSourcePermissionsForAllUsers() error { + sourceAccessMu.RLock() + defaults := GetSourceAccessDefaults() + enforced := sourceAccessEnforcedDefault + sourceAccessMu.RUnlock() + + usersMux.Lock() + defer usersMux.Unlock() + + usersList, err := sqlDb.ListUsers() + if err != nil { + return fmt.Errorf("list users for source permission enforced sync: %w", err) + } + + var updated int + for _, row := range usersList { + if row == nil { + continue + } + u := cloneUserPtr(row) + if !settings.EnforcementAppliesToUser(u) { + continue + } + if !settings.SyncEnforcedSourcePermissionsOntoUser(u, defaults, enforced) { + continue + } + u.FrontendScopes = nil + u.SourcePermissions = nil + if err := sqlDb.UpdateUser(u); err != nil { + return fmt.Errorf("sync enforced source permissions for user %s: %w", u.Username, err) + } + putUserInCache(u) + updated++ + } + if updated > 0 { + logger.Debugf("synced enforced source permissions for %d users", updated) + } + return nil +} diff --git a/backend/internal/state/state.go b/backend/internal/state/state.go new file mode 100644 index 0000000000..77729d0e30 --- /dev/null +++ b/backend/internal/state/state.go @@ -0,0 +1,183 @@ +package state + +import ( + "fmt" + "sync" + + "github.com/gtsteffaniak/filebrowser/backend/internal/auth" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/access" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/dbindex" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/sqldb" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/go-logger/logger" +) + +var ( + // Separate mutexes for each resource type for better concurrency + usersMux sync.RWMutex + sharesMux sync.RWMutex + indexMux sync.RWMutex + + // sqlDb is the SQLite persistence layer. Only state package code should call it directly; + // everyone else goes through exported state.* helpers and the caches below. + sqlDb *sqldb.SQLStore + + // In-memory caches (authoritative at runtime after Initialize for shares/access/index; users use TTL cache) + sharesByHash map[string]*share.Share + sharesByPath map[string][]string // "source:path" -> []hash + indexInfoByPath map[string]*dbindex.IndexInfo + + // accessDb holds access rules, groups, and token hashes in memory with write-through to sqlDb. + accessDb *access.Storage +) + +// Initialize loads all data from SQL into memory and sets the default store handle. +// Prefer state.Open when you need the *Store for dependency injection. +func Initialize(dbPath string) (bool, error) { + _, existingDb, err := Open(dbPath) + return existingDb, err +} + +func initialize(dbPath string) (bool, error) { + // Lock all mutexes during initialization + usersMux.Lock() + sharesMux.Lock() + indexMux.Lock() + defer usersMux.Unlock() + defer sharesMux.Unlock() + defer indexMux.Unlock() + + logger.Info("Initializing state management system...") + var existingDb bool + var err error + sqlDb, existingDb, err = sqldb.NewSQLStore(dbPath) + if err != nil { + return false, fmt.Errorf("failed to initialize SQL database: %w", err) + } + + if err = InitUserDefaultsSettings(); err != nil { + return existingDb, fmt.Errorf("failed to initialize user defaults settings: %w", err) + } + + if err = InitSourceAccessDefaults(); err != nil { + return existingDb, fmt.Errorf("failed to initialize source access defaults: %w", err) + } + + var userCount int + if countErr := sqlDb.DB().QueryRow("SELECT COUNT(*) FROM users").Scan(&userCount); countErr != nil { + return existingDb, fmt.Errorf("failed to count users: %w", countErr) + } + if userCount == 0 { + if err = QuickSetup(); err != nil { + return existingDb, fmt.Errorf("failed to run initial setup: %w", err) + } + } + + // Initialize caches + sharesByHash = make(map[string]*share.Share) + sharesByPath = make(map[string][]string) + indexInfoByPath = make(map[string]*dbindex.IndexInfo) + + logger.Debugf("Loading shares and index data into memory...") + + users.SetUsernameToID(UserIDForUsername) + + // Load shares + sharesList, err := sqlDb.ListAllShares() + if err != nil { + return existingDb, fmt.Errorf("failed to load shares: %w", err) + } + for _, link := range sharesList { + sharesByHash[link.Hash] = link + pathKey := makePathKey(link.SourcePath, link.Path) + sharesByPath[pathKey] = append(sharesByPath[pathKey], link.Hash) + } + logger.Debugf("Loaded %d shares", len(sharesList)) + + // Load index info + allIndexInfo, err := sqlDb.ListAllIndexInfo() + if err != nil { + return existingDb, fmt.Errorf("failed to load index info: %w", err) + } + for _, info := range allIndexInfo { + indexInfoByPath[info.Path] = info + } + logger.Debugf("Loaded %d index info entries", len(allIndexInfo)) + + // Initialize access rules cache + accessDb = &access.Storage{ + AllRules: make(access.SourceRuleMap), + Groups: make(access.GroupMap), + RevokedTokens: make(map[string]struct{}), + HashedTokens: make(map[string]uint64), + } + + allRules, err := sqlDb.GetAllAccessRules() + if err != nil { + return existingDb, fmt.Errorf("failed to load access rules: %w", err) + } + accessDb.AllRules = allRules + logger.Debugf("Loaded access rules for %d sources", len(allRules)) + + allGroups, err := sqlDb.GetAllGroups() + if err != nil { + return existingDb, fmt.Errorf("failed to load groups: %w", err) + } + accessDb.Groups = allGroups + logger.Debugf("Loaded %d groups", len(allGroups)) + + revokedTokens, err := sqlDb.GetAllRevokedTokens() + if err != nil { + return existingDb, fmt.Errorf("failed to load revoked tokens: %w", err) + } + accessDb.RevokedTokens = revokedTokens + logger.Debugf("Loaded %d revoked tokens", len(revokedTokens)) + + hashedTokens, err := sqlDb.GetAllHashedTokens() + if err != nil { + return existingDb, fmt.Errorf("failed to load hashed tokens: %w", err) + } + accessDb.HashedTokens = hashedTokens + logger.Debugf("Loaded %d hashed tokens", len(hashedTokens)) + + accessDb.SetSQLStore(sqlDb) + + err = auth.InitializeEncryption() + if err != nil { + return existingDb, fmt.Errorf("failed to initialize auth encryption: %w", err) + } + + logger.Debugf("State management system initialized successfully") + + if err := InitAnalyticsSettings(); err != nil { + return existingDb, fmt.Errorf("failed to initialize analytics settings: %w", err) + } + + InitActivityRecorder(settings.Config.Server.DatabaseV2) + + return existingDb, nil +} + +// Close closes the underlying SQL database +func Close() error { + usersMux.Lock() + sharesMux.Lock() + indexMux.Lock() + defer usersMux.Unlock() + defer sharesMux.Unlock() + defer indexMux.Unlock() + + users.SetUsernameToID(nil) + clearUserRecordCache() + StopActivityRecorder() + if sqlDb != nil { + return sqlDb.Close() + } + return nil +} + +func makePathKey(source, path string) string { + return source + ":" + path +} diff --git a/backend/internal/state/store.go b/backend/internal/state/store.go new file mode 100644 index 0000000000..f3d21e5d9b --- /dev/null +++ b/backend/internal/state/store.go @@ -0,0 +1,94 @@ +package state + +import ( + "github.com/gtsteffaniak/filebrowser/backend/internal/database/dbindex" + "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/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" +) + +// Store is the runtime handle for the state gateway. It implements ports interfaces +// by delegating to the package-level cache and sqlDb helpers. +type Store struct{} + +var defaultStore *Store + +// Default returns the store opened by Open/Initialize, or nil before startup. +func Default() *Store { + return defaultStore +} + +// Open loads all persisted data and returns the store handle for dependency injection. +func Open(dbPath string) (*Store, bool, error) { + existingDb, err := initialize(dbPath) + if err != nil { + return nil, existingDb, err + } + defaultStore = &Store{} + return defaultStore, existingDb, nil +} + +// --- ports.UserReader --- + +func (s *Store) GetUserByID(id uint64) (users.User, error) { + return GetUserByID(id) +} + +func (s *Store) GetUserByUsername(username string) (users.User, error) { + return GetUserByUsername(username) +} + +// --- ports.UserWriter --- + +func (s *Store) CreateUser(user *users.User, plaintextPassword string) error { + return CreateUser(user, plaintextPassword) +} + +func (s *Store) UpdateUser(user *users.User, plaintextPassword string, fields ...string) error { + return UpdateUser(user, plaintextPassword, fields...) +} + +func (s *Store) DeleteUser(id uint64) error { + return DeleteUser(id) +} + +// --- ports.AccessGate --- + +func (s *Store) AccessPermitted(sourcePath string, indexPath utils.IndexPath, username string) bool { + return AccessPermitted(sourcePath, indexPath, username) +} + +func (s *Store) UpdateAccessRulesOnMove(sourcePath string, oldPath, newPath utils.IndexPath) (int, error) { + return UpdateAccessRulesOnMove(sourcePath, oldPath, newPath) +} + +// CheckChildItemAccess implements files.ChildAccessChecker. +func (s *Store) CheckChildItemAccess(response *iteminfo.FileInfo, idx *indexing.Index, username string) error { + return CheckChildItemAccess(response, idx, username) +} + +// --- ports.ShareReader --- + +func (s *Store) GetShare(hash string) (share.Share, error) { + return GetShare(hash) +} + +func (s *Store) IsShared(source, path string, userID uint64) bool { + return IsShared(source, path, userID) +} + +// --- ports.IndexMetaStore --- + +func (s *Store) GetIndexInfo(path string) (dbindex.IndexInfo, error) { + return GetIndexInfo(path) +} + +func (s *Store) SaveIndexInfo(info *dbindex.IndexInfo) error { + return SaveIndexInfo(info) +} + +func (s *Store) ResetAllIndexComplexities() error { + return ResetAllIndexComplexities() +} diff --git a/backend/internal/state/user_cache.go b/backend/internal/state/user_cache.go new file mode 100644 index 0000000000..ff55e396b1 --- /dev/null +++ b/backend/internal/state/user_cache.go @@ -0,0 +1,114 @@ +package state + +import ( + "fmt" + "time" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/go-cache/cache" +) + +const userCacheTTL = 30 * time.Minute + +var userRecordCache = cache.NewCache[*users.User](userCacheTTL, userCacheTTL+5*time.Minute) + +func userCacheKeyID(id uint64) string { + return fmt.Sprintf("id:%d", id) +} + +func userCacheKeyName(username string) string { + return fmt.Sprintf("name:%s", username) +} + +func putUserInCache(user *users.User) { + if user == nil { + return + } + cached := cloneUserPtr(user) + userRecordCache.Set(userCacheKeyName(user.Username), cached) + if user.ID != 0 { + userRecordCache.Set(userCacheKeyID(user.ID), cached) + } +} + +func deleteUserFromCache(user *users.User) { + if user == nil { + return + } + userRecordCache.Delete(userCacheKeyName(user.Username)) + if user.ID != 0 { + userRecordCache.Delete(userCacheKeyID(user.ID)) + } +} + +func clearUserRecordCache() { + userRecordCache.ClearAll() +} + +func cloneUserPtr(user *users.User) *users.User { + if user == nil { + return nil + } + copy := *user + copyUserSlices(©, user) + return © +} + +func loadUserByUsernameFromDB(username string) (*users.User, error) { + user, err := sqlDb.GetUserByUsername(username) + if err != nil && err.Error() == "user not found" { + return nil, errors.ErrNotExist + } + return user, err +} + +func loadUserByIDFromDB(id uint64) (*users.User, error) { + user, err := sqlDb.GetUserByID(id) + if err != nil && err.Error() == "user not found" { + return nil, errors.ErrNotExist + } + return user, err +} + +func getCachedUserByUsername(username string) (*users.User, bool) { + if cached, ok := userRecordCache.Get(userCacheKeyName(username)); ok && cached != nil { + return cloneUserPtr(cached), true + } + return nil, false +} + +func getCachedUserByID(id uint64) (*users.User, bool) { + if cached, ok := userRecordCache.Get(userCacheKeyID(id)); ok && cached != nil { + return cloneUserPtr(cached), true + } + return nil, false +} + +// loadExistingUserLocked loads a mutable user copy for updates (callers must hold usersMux). +func loadExistingUserLocked(user *users.User) (*users.User, error) { + if user == nil { + return nil, fmt.Errorf("user not found in cache") + } + if user.ID != 0 { + if cached, ok := getCachedUserByID(user.ID); ok { + return cached, nil + } + fromDB, err := loadUserByIDFromDB(user.ID) + if err != nil { + return nil, err + } + return cloneUserPtr(fromDB), nil + } + if user.Username != "" { + if cached, ok := getCachedUserByUsername(user.Username); ok { + return cached, nil + } + fromDB, err := loadUserByUsernameFromDB(user.Username) + if err != nil { + return nil, err + } + return cloneUserPtr(fromDB), nil + } + return nil, fmt.Errorf("user not found in cache") +} diff --git a/backend/internal/state/user_cache_test.go b/backend/internal/state/user_cache_test.go new file mode 100644 index 0000000000..5353322e57 --- /dev/null +++ b/backend/internal/state/user_cache_test.go @@ -0,0 +1,28 @@ +package state + +import ( + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func TestCloneUserPtr_passkeyCredentialsNotAliased(t *testing.T) { + orig := &users.User{ + FrontendUser: users.FrontendUser{Username: "u1"}, + PasskeyCredentials: []users.WebAuthnCredential{ + {ID: "id1", PublicKey: "secret", Transport: []string{"usb"}}, + }, + } + cloned := cloneUserPtr(orig) + if cloned == orig { + t.Fatal("expected distinct pointer") + } + cloned.PasskeyCredentials[0].PublicKey = "" + if orig.PasskeyCredentials[0].PublicKey != "secret" { + t.Fatal("PrepForFrontend-style mutation must not affect original") + } + cloned.PasskeyCredentials[0].Transport[0] = "nfc" + if orig.PasskeyCredentials[0].Transport[0] != "usb" { + t.Fatal("transport slice must be deep copied") + } +} diff --git a/backend/internal/state/user_defaults.go b/backend/internal/state/user_defaults.go new file mode 100644 index 0000000000..e31f8213c9 --- /dev/null +++ b/backend/internal/state/user_defaults.go @@ -0,0 +1,277 @@ +package state + +import ( + "encoding/json" + "fmt" + "reflect" + "strings" + "sync" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/go-logger/logger" +) + +const ( + userDefaultsDefaultSettingKey = "userDefaults.default" + userDefaultsEnforcedDefaultKey = "userDefaults.enforced.default" + + userDefaultsLoginKeyPrefix = "userDefaults.login." + userDefaultsEnforcedLoginPrefix = "userDefaults.enforced.login." +) + +var ( + userDefaultsMu sync.RWMutex + userDefaultsDefault settings.UserDefaults + userDefaultsEnforcedDefault settings.UserDefaultsEnforcement +) + +// InitUserDefaultsSettings loads persisted user defaults from SQLite and seeds from config when missing. +func InitUserDefaultsSettings() error { + seed := settings.Config.UserDefaults + _, existingDefaultsErr := sqlDb.GetSetting(userDefaultsDefaultSettingKey) + + if existingDefaultsErr != nil { + if err := sqlDb.SaveSetting(userDefaultsDefaultSettingKey, seed); err != nil { + return fmt.Errorf("seed user defaults: %w", err) + } + } + + if _, err := sqlDb.GetSetting(userDefaultsEnforcedDefaultKey); err != nil { + // Config-specified paths lock admin UI edits only; enforcement is opt-in via Settings. + if saveErr := sqlDb.SaveSetting(userDefaultsEnforcedDefaultKey, settings.UserDefaultsEnforcement{}); saveErr != nil { + return fmt.Errorf("seed enforced user defaults: %w", saveErr) + } + } + + if err := migrateLoginScopedUserDefaultsToUniversal(); err != nil { + return fmt.Errorf("migrate scoped user defaults: %w", err) + } + + defaults, err := loadUserDefaultsSetting(userDefaultsDefaultSettingKey) + if err != nil { + return fmt.Errorf("load user defaults: %w", err) + } + + if settings.Env.ConfigUserDefaultsSpecified { + overlaid, overlayErr := settings.ApplyConfigSpecifiedPathsToUserDefaults(defaults, settings.Config.UserDefaults) + if overlayErr != nil { + return fmt.Errorf("overlay config user defaults: %w", overlayErr) + } + if !reflect.DeepEqual(defaults, overlaid) { + if saveErr := sqlDb.SaveSetting(userDefaultsDefaultSettingKey, overlaid); saveErr != nil { + return fmt.Errorf("save config-synced user defaults: %w", saveErr) + } + defaults = overlaid + } + } + + enforcedDefault, err := loadUserDefaultsEnforcedSetting(userDefaultsEnforcedDefaultKey) + if err != nil { + return fmt.Errorf("load enforced user defaults: %w", err) + } + + userDefaultsMu.Lock() + userDefaultsDefault = defaults + userDefaultsEnforcedDefault = enforcedDefault + settings.Config.UserDefaults = defaults + userDefaultsMu.Unlock() + + return nil +} + +func migrateLoginScopedUserDefaultsToUniversal() error { + all, err := sqlDb.GetAllSettings() + if err != nil { + return err + } + + if err := mergeAndDeleteLoginScopedSettings( + all, + userDefaultsLoginKeyPrefix, + userDefaultsDefaultSettingKey, + func(base settings.UserDefaults, patch []byte) (settings.UserDefaults, error) { + return settings.MergeUserDefaultsPatchJSON(base, patch) + }, + ); err != nil { + return err + } + + return mergeAndDeleteLoginScopedEnforced(all) +} + +func mergeAndDeleteLoginScopedEnforced(all map[string][]byte) error { + base, err := loadUserDefaultsEnforcedSetting(userDefaultsEnforcedDefaultKey) + if err != nil { + return err + } + merged := base + var deleted int + for key, raw := range all { + if !strings.HasPrefix(key, userDefaultsEnforcedLoginPrefix) { + continue + } + scope := strings.TrimPrefix(key, userDefaultsEnforcedLoginPrefix) + if scope == "" { + continue + } + next, mergeErr := settings.MergeEnforcedPatchJSON(merged, raw) + if mergeErr != nil { + return fmt.Errorf("merge enforced login scope %s: %w", scope, mergeErr) + } + merged = next + if err := sqlDb.DeleteSetting(key); err != nil { + return fmt.Errorf("delete legacy enforced scope %s: %w", key, err) + } + deleted++ + } + if deleted == 0 { + return nil + } + if err := sqlDb.SaveSetting(userDefaultsEnforcedDefaultKey, merged); err != nil { + return fmt.Errorf("save merged enforced user defaults: %w", err) + } + logger.Infof("migrated %d login-scoped enforced user default(s) into universal config", deleted) + return nil +} + +func mergeAndDeleteLoginScopedSettings[T any]( + all map[string][]byte, + prefix string, + targetKey string, + merge func(base T, patch []byte) (T, error), +) error { + rawBase, err := sqlDb.GetSetting(targetKey) + if err != nil { + return err + } + var merged T + if err := json.Unmarshal(rawBase, &merged); err != nil { + return fmt.Errorf("parse %s: %w", targetKey, err) + } + var deleted int + for key, raw := range all { + if !strings.HasPrefix(key, prefix) { + continue + } + scope := strings.TrimPrefix(key, prefix) + if scope == "" { + continue + } + next, mergeErr := merge(merged, raw) + if mergeErr != nil { + return fmt.Errorf("merge login scope %s: %w", scope, mergeErr) + } + merged = next + if err := sqlDb.DeleteSetting(key); err != nil { + return fmt.Errorf("delete legacy scope %s: %w", key, err) + } + deleted++ + } + if deleted == 0 { + return nil + } + if err := sqlDb.SaveSetting(targetKey, merged); err != nil { + return fmt.Errorf("save merged user defaults: %w", err) + } + logger.Infof("migrated %d login-scoped user default(s) into universal config", deleted) + return nil +} + +func loadUserDefaultsSetting(key string) (settings.UserDefaults, error) { + raw, err := sqlDb.GetSetting(key) + if err != nil { + return settings.UserDefaults{}, err + } + var ud settings.UserDefaults + if err := json.Unmarshal(raw, &ud); err != nil { + return settings.UserDefaults{}, fmt.Errorf("parse %s: %w", key, err) + } + return ud, nil +} + +func loadUserDefaultsEnforcedSetting(key string) (settings.UserDefaultsEnforcement, error) { + raw, err := sqlDb.GetSetting(key) + if err != nil { + return settings.UserDefaultsEnforcement{}, err + } + var enforced settings.UserDefaultsEnforcement + if err := json.Unmarshal(raw, &enforced); err != nil { + return settings.UserDefaultsEnforcement{}, fmt.Errorf("parse %s: %w", key, err) + } + return enforced, nil +} + +// GetDefaultUserDefaults returns the universal user defaults template. +func GetDefaultUserDefaults() settings.UserDefaults { + return EffectiveUserDefaults() +} + +// GetUserDefaults returns the universal user defaults template. +func GetUserDefaults() settings.UserDefaults { + return EffectiveUserDefaults() +} + +// GetEnforcedUserDefaults returns universal enforcement flags. +func GetEnforcedUserDefaults() settings.UserDefaultsEnforcement { + return EffectiveEnforced() +} + +// PatchUserDefaults merges patch JSON into the universal defaults and persists. +func PatchUserDefaults(patchJSON []byte) error { + if err := settings.ValidateUserDefaultsPatchNotConfigLocked(patchJSON); err != nil { + return err + } + userDefaultsMu.Lock() + merged, mergeErr := settings.MergeUserDefaultsPatchJSON(userDefaultsDefault, patchJSON) + if mergeErr != nil { + userDefaultsMu.Unlock() + return mergeErr + } + if saveErr := sqlDb.SaveSetting(userDefaultsDefaultSettingKey, merged); saveErr != nil { + userDefaultsMu.Unlock() + return fmt.Errorf("save user defaults: %w", saveErr) + } + userDefaultsDefault = merged + settings.Config.UserDefaults = merged + userDefaultsMu.Unlock() + + return nil +} + +// PatchUserDefaultsEnforced merges enforcement patch JSON into the universal config. +func PatchUserDefaultsEnforced(patchJSON []byte) error { + userDefaultsMu.Lock() + merged, mergeErr := settings.MergeEnforcedPatchJSON(userDefaultsEnforcedDefault, patchJSON) + if mergeErr != nil { + userDefaultsMu.Unlock() + return mergeErr + } + if saveErr := sqlDb.SaveSetting(userDefaultsEnforcedDefaultKey, merged); saveErr != nil { + userDefaultsMu.Unlock() + return fmt.Errorf("save enforced user defaults: %w", saveErr) + } + userDefaultsEnforcedDefault = merged + userDefaultsMu.Unlock() + + return ResyncEnforcedDefaultsForAllUsers() +} + +// EffectiveEnforced returns universal enforcement flags. +func EffectiveEnforced() settings.UserDefaultsEnforcement { + userDefaultsMu.RLock() + defer userDefaultsMu.RUnlock() + return userDefaultsEnforcedDefault +} + +// EffectiveUserDefaults returns the universal defaults template for all users. +func EffectiveUserDefaults() settings.UserDefaults { + userDefaultsMu.RLock() + defer userDefaultsMu.RUnlock() + return userDefaultsDefault +} + +// ApplyUserDefaults applies persisted defaults to a user. +func ApplyUserDefaults(u *users.User) { + settings.ApplyUserDefaultsFrom(u, EffectiveUserDefaults()) +} diff --git a/backend/internal/state/user_defaults_test.go b/backend/internal/state/user_defaults_test.go new file mode 100644 index 0000000000..fa606a9173 --- /dev/null +++ b/backend/internal/state/user_defaults_test.go @@ -0,0 +1,26 @@ +package state + +import ( + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func TestEffectiveUserDefaults_returnsUniversalTemplate(t *testing.T) { + userDefaultsMu.Lock() + userDefaultsDefault = settings.UserDefaults{ + Listing: settings.UserDefaultsListing{ + QuickDownload: true, + ShowHidden: true, + }, + } + userDefaultsMu.Unlock() + + effective := EffectiveUserDefaults() + if !effective.Listing.ShowHidden { + t.Fatalf("expected ShowHidden true") + } + if !effective.Listing.QuickDownload { + t.Fatalf("expected QuickDownload true") + } +} diff --git a/backend/internal/state/user_defaults_yaml_integration_test.go b/backend/internal/state/user_defaults_yaml_integration_test.go new file mode 100644 index 0000000000..4851a64bf0 --- /dev/null +++ b/backend/internal/state/user_defaults_yaml_integration_test.go @@ -0,0 +1,99 @@ +package state + +import ( + "path/filepath" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func TestStateInit_proxyYAML_seedsDefaultsAndCreatesUser(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + t.Setenv("FILEBROWSER_PLAYWRIGHT_TEST", "true") + settings.Initialize("../../../_docker/src/proxy/backend/config.yaml") + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + effective := EffectiveUserDefaults() + if !effective.Account.Permissions.Share { + t.Fatal("DB-seeded defaults missing share from proxy yaml") + } + access := GetSourceAccessDefaults() + if !access.View || !access.Modify || !access.Create { + t.Fatalf("source access defaults: %+v", access) + } + + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "demo-127.0.0.1", + LoginMethod: users.LoginMethodProxy, + }, + } + settings.ApplyUserDefaults(u) + if err = CreateUser(u, ""); err != nil { + t.Fatal(err) + } + loaded, err := GetUserByUsername("demo-127.0.0.1") + if err != nil { + t.Fatal(err) + } + if !loaded.Permissions.Share { + t.Fatal("Share not persisted") + } + if loaded.BackendScopes[0].Scope != "/demo-127.0.0.1" { + t.Fatalf("scope=%q", loaded.BackendScopes[0].Scope) + } + p := loaded.BackendScopes[0].Permissions + if !p.Modify || !p.Create { + t.Fatalf("user scope file permissions: %+v", p) + } +} + +func TestStateInit_jwtYAML_organizedDefaultsOnNewUser(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + t.Setenv("FILEBROWSER_PLAYWRIGHT_TEST", "true") + settings.Initialize("../../../_docker/src/jwt/backend/config.yaml") + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + effective := EffectiveUserDefaults() + if !effective.Account.Permissions.Share { + t.Fatal("share not in effective defaults") + } + access := GetSourceAccessDefaults() + if !access.Modify || !access.Create || !access.Download { + t.Fatalf("source defaultPermissions from jwt yaml: %+v", access) + } + + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "testuser", + LoginMethod: users.LoginMethodJwt, + }, + } + settings.ApplyUserDefaults(u) + if err = CreateUser(u, ""); err != nil { + t.Fatal(err) + } + loaded, err := GetUserByUsername("testuser") + if err != nil { + t.Fatal(err) + } + if !loaded.DarkMode || !loaded.Preview.Image { + t.Fatalf("profile fields: darkMode=%v preview.image=%v", loaded.DarkMode, loaded.Preview.Image) + } + if loaded.BackendScopes[0].Permissions.Modify != access.Modify { + t.Fatalf("scope perms=%+v access=%+v", loaded.BackendScopes[0].Permissions, access) + } +} diff --git a/backend/internal/state/user_enforcement_sync.go b/backend/internal/state/user_enforcement_sync.go new file mode 100644 index 0000000000..13a32a1ebc --- /dev/null +++ b/backend/internal/state/user_enforcement_sync.go @@ -0,0 +1,62 @@ +package state + +import ( + "fmt" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/go-logger/logger" +) + +// ApplyEnforcedSyncToUser applies enforced default values onto u in memory. Returns true if profile fields changed. +func ApplyEnforcedSyncToUser(u *users.User) bool { + if u == nil { + return false + } + d := EffectiveUserDefaults() + e := EffectiveEnforced() + return settings.SyncEnforcedDefaultsOntoUser(u, d, e) +} + +// ResyncEnforcedDefaultsForAllUsers writes enforced default values into SQLite for every user when they differ. +func ResyncEnforcedDefaultsForAllUsers() error { + userDefaultsMu.RLock() + defer userDefaultsMu.RUnlock() + + usersMux.Lock() + defer usersMux.Unlock() + + d := userDefaultsDefault + e := userDefaultsEnforcedDefault + + usersList, err := sqlDb.ListUsers() + if err != nil { + return fmt.Errorf("list users for enforced sync: %w", err) + } + + var updated int + for _, row := range usersList { + if row == nil { + continue + } + u := cloneUserPtr(row) + if !settings.EnforcementAppliesToUser(u) { + continue + } + if !settings.SyncEnforcedDefaultsOntoUser(u, d, e) { + continue + } + users.SyncBackendSourcePermissionsMap(u) + u.FrontendScopes = nil + u.SourcePermissions = nil + if err := sqlDb.UpdateUser(u); err != nil { + return fmt.Errorf("sync enforced defaults for user %s: %w", u.Username, err) + } + putUserInCache(u) + updated++ + } + if updated > 0 { + logger.Debugf("synced enforced user defaults for %d users", updated) + } + return nil +} diff --git a/backend/internal/state/user_enforcement_sync_test.go b/backend/internal/state/user_enforcement_sync_test.go new file mode 100644 index 0000000000..1b1ff34e70 --- /dev/null +++ b/backend/internal/state/user_enforcement_sync_test.go @@ -0,0 +1,80 @@ +package state + +import ( + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func snapshotUserDefaultsGlobals(t *testing.T) { + t.Helper() + userDefaultsMu.Lock() + prevDefault := userDefaultsDefault + prevEnforced := userDefaultsEnforcedDefault + userDefaultsMu.Unlock() + t.Cleanup(func() { + userDefaultsMu.Lock() + userDefaultsDefault = prevDefault + userDefaultsEnforcedDefault = prevEnforced + userDefaultsMu.Unlock() + }) +} + +func TestApplyEnforcedSyncToUser_mutatesProfile(t *testing.T) { + snapshotUserDefaultsGlobals(t) + userDefaultsMu.Lock() + userDefaultsDefault = settings.UserDefaults{ + Listing: settings.UserDefaultsListing{ShowHidden: true}, + } + userDefaultsEnforcedDefault = settings.UserDefaultsEnforcement{ + Listing: settings.UserDefaultsListingEnforcement{ShowHidden: true}, + } + userDefaultsMu.Unlock() + + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "alice", + NonAdminEditable: users.NonAdminEditable{ + ShowHidden: false, + }, + }, + } + if !ApplyEnforcedSyncToUser(u) { + t.Fatal("expected enforced sync to change profile") + } + if !u.ShowHidden { + t.Fatal("expected ShowHidden true after enforced sync") + } + if ApplyEnforcedSyncToUser(u) { + t.Fatal("expected no further changes when already aligned") + } +} + +func TestApplyEnforcedSyncToUser_skipsAdmin(t *testing.T) { + snapshotUserDefaultsGlobals(t) + userDefaultsMu.Lock() + userDefaultsDefault = settings.UserDefaults{ + Listing: settings.UserDefaultsListing{ShowHidden: true}, + } + userDefaultsEnforcedDefault = settings.UserDefaultsEnforcement{ + Listing: settings.UserDefaultsListingEnforcement{ShowHidden: true}, + } + userDefaultsMu.Unlock() + + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "admin", + NonAdminEditable: users.NonAdminEditable{ + ShowHidden: false, + }, + }, + } + u.Permissions.Admin = true + if ApplyEnforcedSyncToUser(u) { + t.Fatal("expected enforced sync to skip admin users") + } + if u.ShowHidden { + t.Fatal("admin profile should remain unchanged") + } +} diff --git a/backend/internal/state/users.go b/backend/internal/state/users.go new file mode 100644 index 0000000000..a0d32fa2da --- /dev/null +++ b/backend/internal/state/users.go @@ -0,0 +1,592 @@ +package state + +import ( + "fmt" + "reflect" + "strings" + + "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/database/share" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// User operations + +// copyBackendSourcePermissions returns a shallow copy of the per-source permissions map. +func copyBackendSourcePermissions(m map[string]users.SourceFilePermissions) map[string]users.SourceFilePermissions { + if m == nil { + return nil + } + out := make(map[string]users.SourceFilePermissions, len(m)) + for k, v := range m { + out[k] = v + } + return out +} + +// copyUserSlices deep-copies user slice/map fields into userCopy. +func copyUserSlices(userCopy *users.User, user *users.User) { + if user.BackendScopes != nil { + userCopy.BackendScopes = make([]users.BackendScope, len(user.BackendScopes)) + copy(userCopy.BackendScopes, user.BackendScopes) + } + if user.BackendSourcePermissions != nil { + userCopy.BackendSourcePermissions = copyBackendSourcePermissions(user.BackendSourcePermissions) + } + if user.Tokens != nil { + userCopy.Tokens = make(map[string]users.AuthToken, len(user.Tokens)) + for k, v := range user.Tokens { + userCopy.Tokens[k] = v + } + } + if user.SidebarLinks != nil { + userCopy.SidebarLinks = make([]users.SidebarLink, len(user.SidebarLinks)) + copy(userCopy.SidebarLinks, user.SidebarLinks) + } + if user.FrontendScopes != nil { + userCopy.FrontendScopes = make([]users.FrontendScope, len(user.FrontendScopes)) + copy(userCopy.FrontendScopes, user.FrontendScopes) + } + if user.SourcePermissions != nil { + userCopy.SourcePermissions = copyBackendSourcePermissions(user.SourcePermissions) + } + if user.ApiKeys != nil { + userCopy.ApiKeys = make(map[string]users.AuthToken, len(user.ApiKeys)) + for k, v := range user.ApiKeys { + userCopy.ApiKeys[k] = v + } + } + if user.PasskeyCredentials != nil { + userCopy.PasskeyCredentials = copyWebAuthnCredentials(user.PasskeyCredentials) + } + if user.PinnedItems != nil { + userCopy.PinnedItems = copyPinnedItems(user.PinnedItems) + } +} + +func copyWebAuthnCredentials(in []users.WebAuthnCredential) []users.WebAuthnCredential { + out := make([]users.WebAuthnCredential, len(in)) + for i, c := range in { + out[i] = c + if c.Transport != nil { + out[i].Transport = append([]string(nil), c.Transport...) + } + } + return out +} + +func copyPinnedItems(in users.PinnedItems) users.PinnedItems { + if in == nil { + return nil + } + out := make(users.PinnedItems, len(in)) + for srcPath, dirs := range in { + dirCopy := make(map[string][]string, len(dirs)) + for dirPath, names := range dirs { + dirCopy[dirPath] = append([]string(nil), names...) + } + out[srcPath] = dirCopy + } + return out +} + +// GetUserByID retrieves a user by stable numeric id (JWT belongsTo, admin APIs). +func GetUserByID(id uint64) (users.User, error) { + if id == 0 { + return users.User{}, errors.ErrNotExist + } + usersMux.RLock() + defer usersMux.RUnlock() + + if cached, ok := getCachedUserByID(id); ok { + return *cached, nil + } + + user, err := loadUserByIDFromDB(id) + if err != nil { + return users.User{}, err + } + putUserInCache(user) + userCopy := *user + copyUserSlices(&userCopy, user) + return userCopy, nil +} + +// GetUserByUsername returns a user by username (30m cache, SQLite on miss). +func GetUserByUsername(username string) (users.User, error) { + usersMux.RLock() + defer usersMux.RUnlock() + + if cached, ok := getCachedUserByUsername(username); ok { + return *cached, nil + } + + user, err := loadUserByUsernameFromDB(username) + if err != nil { + return users.User{}, err + } + putUserInCache(user) + userCopy := *user + copyUserSlices(&userCopy, user) + return userCopy, nil +} + +// UserIDForUsername returns the stable id for a login name (for id-keyed user storage). +func UserIDForUsername(username string) (uint64, error) { + u, err := GetUserByUsername(username) + if err != nil { + return 0, err + } + return u.ID, nil +} + +// GetAllUsers returns all users from SQLite (not a long-lived memory map). +func GetAllUsers() ([]users.User, error) { + usersMux.RLock() + defer usersMux.RUnlock() + + usersList, err := sqlDb.ListUsers() + if err != nil { + return nil, err + } + out := make([]users.User, 0, len(usersList)) + for _, user := range usersList { + if user == nil { + continue + } + userCopy := *user + copyUserSlices(&userCopy, user) + out = append(out, userCopy) + } + return out, nil +} + +// UserFromAPIToken resolves the user for a validated API JWT: numeric belongsTo id, or minimal tokens +// (hash → user id). Usernames are not used so a reused login name never inherits a previous account's API access. +func UserFromAPIToken(tk users.AuthToken, rawToken string) (users.User, error) { + if tk.BelongsTo != 0 { + return GetUserByID(tk.BelongsTo) + } + if uid, ok := accessDb.GetUserIDFromToken(rawToken); ok { + return GetUserByID(uid) + } + return users.User{}, errors.ErrNotExist +} + +// UserForShareOwner resolves the user who owns a share link. +func UserForShareOwner(link share.Share) (users.User, error) { + if link.UserID == 0 { + return users.User{}, errors.ErrNotExist + } + return GetUserByID(link.UserID) +} + +// CreateUser creates a new user with plaintext password. +// +// Scope model: only BackendScopes are persisted (SQL user_data). JSON "scopes" on the API unmarshals into +// FrontendScopes; state converts those to BackendScopes via APIScopesToBackend, clears FrontendScopes, then +// may apply default-enabled sources. In-memory/cache users always keep FrontendScopes nil; GET handlers use +// PrepForFrontend to repopulate FrontendScopes from BackendScopes for responses. +func CreateUser(user *users.User, plaintextPassword string) error { + if err := users.ValidateUsername(user.Username); err != nil { + return err + } + if _, err := GetUserByUsername(user.Username); err == nil { + return fmt.Errorf("user with username %s already exists", user.Username) + } else if err != errors.ErrNotExist { + return err + } + // Hash password if provided + if plaintextPassword != "" { + hashedPassword, err := utils.HashPwd(plaintextPassword) + if err != nil { + return fmt.Errorf("failed to hash password: %w", err) + } + user.Password = hashedPassword + } + + // Incoming API "scopes" → BackendScopes; FrontendScopes must not remain on the persisted user. + if err := applyScopesFromAPI(user); err != nil { + return err + } + + // If still no BackendScopes (omitted or invalid API names), same defaults as ApplyUserDefaults. + ApplyUserDefaults(user) + defaults := EffectiveUserDefaults() + enforced := EffectiveEnforced() + settings.ApplyEnforcedDefaultsFrom(user, defaults, enforced) + settings.ApplyEnforcedSourcePermissionsFrom(user, GetSourceAccessDefaults(), GetEnforcedSourcePermissions()) + + users.SyncBackendSourcePermissionsMap(user) + + usersMux.Lock() + defer usersMux.Unlock() + + if user.ID == 0 { + nid, genErr := utils.RandomUint64ID() + if genErr != nil { + return fmt.Errorf("allocate user id: %w", genErr) + } + user.ID = nid + } + + if err := sqlDb.CreateUser(user); err != nil { + return err + } + + putUserInCache(user) + + return nil +} + +func validatePatchFieldList(fields ...string) error { + if len(fields) == 0 { + return fmt.Errorf("which must list at least one JSON field name to update") + } + for _, jsonFieldName := range fields { + jsonFieldName = strings.TrimSpace(jsonFieldName) + if jsonFieldName == "" { + return fmt.Errorf("which must not contain empty field names") + } + if strings.EqualFold(jsonFieldName, "all") { + return fmt.Errorf("invalid which field %q", jsonFieldName) + } + } + return nil +} + +// FieldListIncludes reports whether fields contains name, case-insensitively. +func FieldListIncludes(fields []string, name string) bool { + for _, f := range fields { + if strings.EqualFold(strings.TrimSpace(f), name) { + return true + } + } + return false +} + +// UpdateUser patches an existing user with write-through to SQL. +// fields must list JSON tag names (e.g. "showFirstLogin", "scopes", "permissions"). +// If plaintextPassword is provided (non-empty), it will be hashed when "password" is in fields. +func UpdateUser(user *users.User, plaintextPassword string, fields ...string) error { + if err := validatePatchFieldList(fields...); err != nil { + return err + } + + sourceDefaults := GetSourceAccessDefaults() + sourceEnforced := GetEnforcedSourcePermissions() + + usersMux.Lock() + defer usersMux.Unlock() + + storedSnapshot, err := loadExistingUserLocked(user) + if err != nil { + return fmt.Errorf("user %s not found in cache", user.Username) + } + existingUser := cloneUserPtr(storedSnapshot) + + existingVal := reflect.ValueOf(existingUser).Elem() + newVal := reflect.ValueOf(user).Elem() + + for _, jsonFieldName := range fields { + jsonFieldName = strings.TrimSpace(jsonFieldName) + if strings.EqualFold(jsonFieldName, "password") { + if plaintextPassword == "" { + return fmt.Errorf("password field requires a non-empty plaintext password") + } + hashedPassword, hashErr := utils.HashPwd(plaintextPassword) + if hashErr != nil { + return fmt.Errorf("failed to hash password: %w", hashErr) + } + existingUser.Password = hashedPassword + continue + } + + structFieldName := findFieldByJSONTag(reflect.TypeOf(user).Elem(), jsonFieldName) + if structFieldName == "" { + structFieldName = jsonFieldName + } + + existingField := existingVal.FieldByName(structFieldName) + newField := newVal.FieldByName(structFieldName) + if !existingField.IsValid() || !existingField.CanSet() || !newField.IsValid() { + return fmt.Errorf("unknown or read-only user field %q", jsonFieldName) + } + existingField.Set(newField) + } + + if FieldListIncludes(fields, "otpEnabled") && !existingUser.OtpEnabled { + existingUser.TOTPSecret = "" + existingUser.TOTPNonce = "" + } + + if fieldListRequiresScopeConversion(fields) { + if err := applyScopesFromAPI(existingUser); err != nil { + return err + } + } + + return commitUserUpdate(existingUser, storedSnapshot, sourceDefaults, sourceEnforced) +} + +func commitUserUpdate(existingUser, storedSnapshot *users.User, sourceDefaults users.SourceFilePermissions, sourceEnforced settings.SourceFilePermissionsEnforcement) error { + oldUsername := storedSnapshot.Username + oldUserID := storedSnapshot.ID + + users.SyncBackendSourcePermissionsMap(existingUser) + existingUser.FrontendScopes = nil + existingUser.SourcePermissions = nil + + defaults := EffectiveUserDefaults() + enforced := EffectiveEnforced() + if err := settings.ValidateUserAgainstEnforcedDefaults(existingUser, defaults, enforced); err != nil { + return err + } + if err := settings.ValidateUserScopePermissionsAgainstEnforced(existingUser, sourceDefaults, sourceEnforced); err != nil { + return err + } + + if oldUsername != existingUser.Username { + if err := sqlDb.UpdateUserUsername(oldUsername, existingUser); err != nil { + return err + } + if oldUserID != 0 && oldUserID != existingUser.ID { + userRecordCache.Delete(userCacheKeyID(oldUserID)) + } + userRecordCache.Delete(userCacheKeyName(oldUsername)) + } else if err := sqlDb.UpdateUser(existingUser); err != nil { + return err + } + + putUserInCache(existingUser) + return nil +} + +// fieldListPatchesBackendScopes reports whether fields include persisted scope paths (JSON tag +// "backendScopes", case-insensitive; matches struct name BackendScopes as well). +func fieldListPatchesBackendScopes(fields []string) bool { + for _, f := range fields { + f = strings.TrimSpace(f) + if strings.EqualFold(f, "backendScopes") { + return true + } + } + return false +} + +func fieldListPatchesAPISourcePermissions(fields []string) bool { + for _, f := range fields { + f = strings.TrimSpace(f) + if strings.EqualFold(f, "sourcePermissions") || strings.EqualFold(f, "scopes") { + return true + } + } + return false +} + +func fieldListRequiresScopeConversion(fields []string) bool { + return fieldListPatchesBackendScopes(fields) || fieldListPatchesAPISourcePermissions(fields) +} + +// applyScopesFromAPI converts API scopes (with nested permissions) into BackendScopes. +// Legacy sourcePermissions map is merged into scopes when permissions are omitted per scope. +func applyScopesFromAPI(user *users.User) error { + if len(user.SourcePermissions) > 0 && len(user.FrontendScopes) > 0 { + byName := make(map[string]users.SourceFilePermissions, len(user.SourcePermissions)) + for name, perms := range user.SourcePermissions { + byName[name] = perms + } + for i, scope := range user.FrontendScopes { + if scope.Permissions != nil { + continue + } + if perms, ok := byName[scope.Name]; ok { + p := perms + user.FrontendScopes[i].Permissions = &p + } + } + } + defaults := settings.DefaultSourceFilePermissions() + if user.Permissions.Admin { + defaults = settings.AdminSourceFilePermissions() + } + for i, scope := range user.FrontendScopes { + if scope.Permissions != nil { + continue + } + p := defaults + user.FrontendScopes[i].Permissions = &p + } + if len(user.FrontendScopes) > 0 { + backend, convErr := users.APIScopesToBackend(user.FrontendScopes) + if convErr != nil { + return convErr + } + user.BackendScopes = backend + } else if len(user.SourcePermissions) > 0 { + backendPerms, convErr := users.APISourcePermsToBackend(user.SourcePermissions) + if convErr != nil { + return convErr + } + for i, scope := range user.BackendScopes { + if perms, ok := backendPerms[scope.Path]; ok { + user.BackendScopes[i].Permissions = perms + } + } + } + user.FrontendScopes = nil + user.SourcePermissions = nil + return nil +} + +// findFieldByJSONTag recursively searches for a struct field by its JSON tag name +// Handles embedded structs by searching through all levels +func findFieldByJSONTag(t reflect.Type, jsonTag string) string { + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + + // Check if this field's JSON tag matches + jsonTagValue := field.Tag.Get("json") + if jsonTagValue != "" { + // Parse tag (might be "fieldName,omitempty") + tagName := strings.Split(jsonTagValue, ",")[0] + if tagName == jsonTag { + return field.Name + } + } + + // If this is an embedded struct (Anonymous field), search recursively + if field.Anonymous && field.Type.Kind() == reflect.Struct { + if nestedFieldName := findFieldByJSONTag(field.Type, jsonTag); nestedFieldName != "" { + // For embedded structs, we can access the field directly by name + // because Go promotes embedded struct fields + return nestedFieldName + } + } + } + + return "" +} + +// DeleteUser deletes a user by stable numeric id (non-zero). +func DeleteUser(id uint64) error { + if id == 0 { + return fmt.Errorf("user not found in state") + } + usersMux.Lock() + defer usersMux.Unlock() + + user, err := loadExistingUserLocked(&users.User{ID: id}) + if err != nil { + return fmt.Errorf("user not found in state") + } + + if err := sqlDb.DeleteUserByID(id); err != nil { + return err + } + + deleteUserFromCache(user) + + if accessDb != nil { + _ = accessDb.RemoveHashedTokensForUser(id) + } + + return nil +} + +// DeleteUserByUsername deletes a user by username +func DeleteUserByUsername(username string) error { + usersMux.Lock() + defer usersMux.Unlock() + + user, err := loadExistingUserLocked(&users.User{FrontendUser: users.FrontendUser{Username: username}}) + if err != nil { + return fmt.Errorf("user not found in state") + } + + uid := user.ID + if err := sqlDb.DeleteUserByUsername(username); err != nil { + return err + } + + deleteUserFromCache(user) + + if accessDb != nil && uid != 0 { + _ = accessDb.RemoveHashedTokensForUser(uid) + } + + return nil +} + +// TokenNameForRawToken returns the persisted token name when rawToken matches a stored API key. +func TokenNameForRawToken(user *users.User, rawToken string) (string, bool) { + if user == nil { + return "", false + } + usersMux.RLock() + defer usersMux.RUnlock() + return users.TokenNameByRaw(user.Tokens, rawToken) +} + +// AddUserToken adds an API token to a user +func AddUserToken(ownerUsername string, token users.AuthToken) error { + usersMux.Lock() + defer usersMux.Unlock() + + user, err := loadExistingUserLocked(&users.User{FrontendUser: users.FrontendUser{Username: ownerUsername}}) + if err != nil { + return fmt.Errorf("user not found in state") + } + + // Check if token already exists + if user.Tokens != nil { + if _, tokenExists := user.Tokens[token.Name]; tokenExists { + return fmt.Errorf("token with name %s already exists for user", token.Name) + } + } + + // Prepare the update + if user.Tokens == nil { + user.Tokens = make(map[string]users.AuthToken) + } + users.StoreToken(user.Tokens, token) + + if err := sqlDb.UpdateUser(user); err != nil { + return err + } + + putUserInCache(user) + + return nil +} + +// DeleteUserToken removes an API token from a user +func DeleteUserToken(ownerUsername string, tokenName string) error { + usersMux.Lock() + defer usersMux.Unlock() + + user, err := loadExistingUserLocked(&users.User{FrontendUser: users.FrontendUser{Username: ownerUsername}}) + if err != nil { + return fmt.Errorf("user not found in state") + } + + // Check if token exists + if user.Tokens == nil { + return fmt.Errorf("user has no tokens") + } + if _, tokenExists := user.Tokens[tokenName]; !tokenExists { + return fmt.Errorf("token with name %s not found for user", tokenName) + } + + users.RemoveTokenByName(user.Tokens, tokenName) + + if err := sqlDb.UpdateUser(user); err != nil { + return err + } + + putUserInCache(user) + + return nil +} diff --git a/backend/internal/state/users_test.go b/backend/internal/state/users_test.go new file mode 100644 index 0000000000..b39fc8963a --- /dev/null +++ b/backend/internal/state/users_test.go @@ -0,0 +1,343 @@ +package state + +import ( + "path/filepath" + "strings" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func TestCreateUserValidateUsername(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize("../../../_docker/src/noauth/backend/config.yaml") + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + tests := []struct { + name string + username string + wantErr string + }{ + {name: "empty username", username: "", wantErr: "username is empty"}, + {name: "reserved anonymous", username: "anonymous", wantErr: "reserved"}, + {name: "valid username", username: "alice", wantErr: ""}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: tc.username, + }, + } + err := CreateUser(u, "password") + if tc.wantErr == "" { + if err != nil { + t.Fatalf("CreateUser(%q): unexpected error: %v", tc.username, err) + } + return + } + if err == nil { + t.Fatalf("CreateUser(%q): expected error containing %q", tc.username, tc.wantErr) + } + if !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("CreateUser(%q): got %v, want error containing %q", tc.username, err, tc.wantErr) + } + }) + } +} + +func TestUpdateUserPatchPreservesTOTPSecret(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize("../../../_docker/src/noauth/backend/config.yaml") + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "alice", + NonAdminEditable: users.NonAdminEditable{ + Locale: "en", + }, + }, + } + if err = CreateUser(u, "password"); err != nil { + t.Fatal(err) + } + u.TOTPSecret = "persisted-secret" + u.TOTPNonce = "persisted-nonce" + u.OtpEnabled = true + if err = UpdateUser(u, "", "totpSecret", "totpNonce", "otpEnabled"); err != nil { + t.Fatal(err) + } + + patch := &users.User{ + ID: u.ID, + FrontendUser: users.FrontendUser{ + Username: "alice", + NonAdminEditable: users.NonAdminEditable{ + Locale: "de", + }, + }, + } + if err = UpdateUser(patch, "", "locale"); err != nil { + t.Fatal(err) + } + + loaded, err := GetUserByUsername("alice") + if err != nil { + t.Fatal(err) + } + if loaded.TOTPSecret != "persisted-secret" || loaded.TOTPNonce != "persisted-nonce" { + t.Fatalf("expected TOTP preserved after locale patch, got secret=%q nonce=%q", loaded.TOTPSecret, loaded.TOTPNonce) + } + if loaded.Locale != "de" { + t.Fatalf("expected locale updated, got %q", loaded.Locale) + } +} + +func TestUpdateUserRejectsEmptyFields(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize("../../../_docker/src/noauth/backend/config.yaml") + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "alice", + }, + } + if err = CreateUser(u, "password"); err != nil { + t.Fatal(err) + } + + patch := &users.User{ + ID: u.ID, + FrontendUser: users.FrontendUser{ + Username: "alice", + NonAdminEditable: users.NonAdminEditable{ + Locale: "de", + }, + }, + } + if err = UpdateUser(patch, ""); err == nil { + t.Fatal("expected error when no fields are specified") + } +} + +func TestUpdateUserRejectsAllField(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize("../../../_docker/src/noauth/backend/config.yaml") + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "alice", + NonAdminEditable: users.NonAdminEditable{ + Locale: "en", + }, + }, + } + if err = CreateUser(u, "password"); err != nil { + t.Fatal(err) + } + + patch := &users.User{ + ID: u.ID, + FrontendUser: users.FrontendUser{ + Username: "alice", + NonAdminEditable: users.NonAdminEditable{ + Locale: "de", + }, + }, + } + if err = UpdateUser(patch, "", "all"); err == nil { + t.Fatal("expected error when which contains all") + } +} + +func TestUpdateUserRejectsUnknownField(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize("../../../_docker/src/noauth/backend/config.yaml") + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "alice", + NonAdminEditable: users.NonAdminEditable{ + Locale: "en", + }, + }, + } + if err = CreateUser(u, "password"); err != nil { + t.Fatal(err) + } + + patch := &users.User{ + ID: u.ID, + FrontendUser: users.FrontendUser{ + Username: "alice", + }, + } + if err = UpdateUser(patch, "", "notARealField"); err == nil { + t.Fatal("expected error for unknown field") + } +} + +func TestUpdateUserRejectsPasswordWithoutPlaintext(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize("../../../_docker/src/noauth/backend/config.yaml") + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "alice", + }, + } + if err = CreateUser(u, "password"); err != nil { + t.Fatal(err) + } + + patch := &users.User{ID: u.ID, FrontendUser: users.FrontendUser{Username: "alice"}} + if err = UpdateUser(patch, "", "password"); err == nil { + t.Fatal("expected error when password is in which but plaintext is empty") + } +} + +func TestUpdateUserClearsTOTPWhenOtpDisabled(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize("../../../_docker/src/noauth/backend/config.yaml") + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "alice", + OtpEnabled: true, + }, + } + if err = CreateUser(u, "password"); err != nil { + t.Fatal(err) + } + u.TOTPSecret = "persisted-secret" + u.TOTPNonce = "persisted-nonce" + if err = UpdateUser(u, "", "totpSecret", "totpNonce", "otpEnabled"); err != nil { + t.Fatal(err) + } + + disable := &users.User{ + ID: u.ID, + FrontendUser: users.FrontendUser{ + Username: "alice", + OtpEnabled: false, + }, + } + if err = UpdateUser(disable, "", "otpEnabled"); err != nil { + t.Fatal(err) + } + + loaded, err := GetUserByUsername("alice") + if err != nil { + t.Fatal(err) + } + if loaded.TOTPSecret != "" || loaded.TOTPNonce != "" { + t.Fatalf("expected TOTP cleared when otpEnabled disabled, got secret=%q nonce=%q", loaded.TOTPSecret, loaded.TOTPNonce) + } + if loaded.OtpEnabled { + t.Fatal("expected otpEnabled false") + } +} + +func TestUpdateUserPatchPreservesBackendSourcePermissions(t *testing.T) { + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", "") + settings.Initialize("../../../_docker/src/noauth/backend/config.yaml") + settings.Env.IsPlaywright = true + + dbPath := filepath.Join(t.TempDir(), "filebrowser.sqlite") + _, err := Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = Close() }) + + scopePerms := users.SourceFilePermissions{View: true, Download: true, Modify: true} + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "alice", + Permissions: users.Permissions{Admin: true}, + }, + BackendScopes: []users.BackendScope{{Path: "/data/a", Scope: "/", Permissions: scopePerms}}, + Version: users.SourcePermissionsMigrationVersion, + } + if err = CreateUser(u, "password"); err != nil { + t.Fatal(err) + } + + patch := &users.User{ + ID: u.ID, + FrontendUser: users.FrontendUser{ + Username: "alice", + }, + BackendScopes: []users.BackendScope{{Path: "/data/a", Scope: "/", Permissions: scopePerms}}, + Version: users.SourcePermissionsMigrationVersion, + } + if err = UpdateUser(patch, "", "backendScopes"); err != nil { + t.Fatal(err) + } + + reloaded, err := GetUserByUsername("alice") + if err != nil { + t.Fatal(err) + } + if len(reloaded.BackendScopes) == 0 || !reloaded.BackendScopes[0].Permissions.View || !reloaded.BackendScopes[0].Permissions.Modify { + t.Fatalf("expected perms preserved after patch, got %#v", reloaded.BackendScopes) + } +} + diff --git a/backend/internal/usersidebar/links.go b/backend/internal/usersidebar/links.go new file mode 100644 index 0000000000..246e0b110e --- /dev/null +++ b/backend/internal/usersidebar/links.go @@ -0,0 +1,45 @@ +package usersidebar + +import ( + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +// FrontendLinks converts backend sidebar links to frontend-style links. +func FrontendLinks(links []users.SidebarLink, showToolsInSidebar bool) []users.SidebarLink { + if !users.SourceConfigLoaded() { + return []users.SidebarLink{} + } + hasTools := false + newLinks := []users.SidebarLink{} + for _, link := range links { + if users.IsSourceSidebarCategory(link.Category) { + if link.SourceName == "" { + continue + } + source, ok := users.ResolveSourceKey(link.SourceName) + if !ok { + continue + } + 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) + } + } + link.SourceName = source.Name + } else if link.Category == "tool" && link.Target == "/tools" { + hasTools = true + } + newLinks = append(newLinks, link) + } + if !hasTools && showToolsInSidebar { + newLinks = append(newLinks, users.SidebarLink{ + Name: "Tools", + Category: "tool", + Target: "/tools", + Icon: "build", + }) + } + return newLinks +} diff --git a/backend/internal/usersidebar/normalize.go b/backend/internal/usersidebar/normalize.go new file mode 100644 index 0000000000..b95b71f13d --- /dev/null +++ b/backend/internal/usersidebar/normalize.go @@ -0,0 +1,79 @@ +package usersidebar + +import ( + "strings" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// NormalizeSidebarLinks canonicalizes persisted sidebar links for storage. +// Source links are resolved via ResolveSourceKey on SourceName, with Name as fallback. +// SourceName is set to the canonical backend path; Name to the configured display name. +// Unresolvable source links are dropped. Source links are deduped by canonical path +// (first occurrence wins). Non-source links pass through; duplicate Tools links are deduped. +func NormalizeSidebarLinks(links []users.SidebarLink) ([]users.SidebarLink, bool) { + if !users.SourceConfigLoaded() { + return links, false + } + if len(links) == 0 { + return links, false + } + + seenSourcePaths := make(map[string]struct{}) + hasTools := false + out := make([]users.SidebarLink, 0, len(links)) + changed := false + + for _, link := range links { + if users.IsSourceSidebarCategory(link.Category) { + source, ok := resolveSourceLink(link) + if !ok { + changed = true + continue + } + if _, dup := seenSourcePaths[source.Path]; dup { + changed = true + continue + } + seenSourcePaths[source.Path] = struct{}{} + + normalized := link + normalized.Category = users.NormalizeSidebarLinkCategory(normalized.Category) + normalized.SourceName = source.Path + if strings.TrimSpace(normalized.Name) == "" { + normalized.Name = source.Name + } + if normalized.Target == "" { + normalized.Target = "/" + } + if normalized != link { + changed = true + } + out = append(out, normalized) + continue + } + + if link.Category == "tool" && link.Target == "/tools" { + if hasTools { + changed = true + continue + } + hasTools = true + } + out = append(out, link) + } + + return out, changed +} + +func resolveSourceLink(link users.SidebarLink) (users.SourceInfo, bool) { + if link.SourceName != "" { + if source, ok := users.ResolveSourceKey(link.SourceName); ok { + return source, true + } + } + if link.Name != "" { + return users.ResolveSourceKey(link.Name) + } + return users.SourceInfo{}, false +} diff --git a/backend/internal/usersidebar/normalize_test.go b/backend/internal/usersidebar/normalize_test.go new file mode 100644 index 0000000000..d41f33874d --- /dev/null +++ b/backend/internal/usersidebar/normalize_test.go @@ -0,0 +1,184 @@ +package usersidebar + +import ( + "reflect" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func testSourceConfig(t *testing.T) { + t.Helper() + had := users.SourceConfigLoaded() + t.Cleanup(func() { + if !had { + users.SetSourceConfig(nil) + } + }) + users.SetSourceConfig(&users.SourceConfigProvider{ + GetSourceByPath: func(path string) (users.SourceInfo, bool) { + switch path { + case "../frontend/tests/playwright-files": + return users.SourceInfo{ + Path: "../frontend/tests/playwright-files", + Name: "playwright + files", + }, true + case ".": + return users.SourceInfo{Path: ".", Name: "docker"}, true + case "/tests/playwright-files": + return users.SourceInfo{Path: "/tests/playwright-files", Name: "access"}, true + default: + return users.SourceInfo{}, false + } + }, + GetSourceByName: func(name string) (users.SourceInfo, bool) { + switch name { + case "playwright + files": + return users.SourceInfo{ + Path: "../frontend/tests/playwright-files", + Name: "playwright + files", + }, true + case "docker": + return users.SourceInfo{Path: ".", Name: "docker"}, true + case "access": + return users.SourceInfo{Path: "/tests/playwright-files", Name: "access"}, true + default: + return users.SourceInfo{}, false + } + }, + }) +} + +func TestNormalizeSidebarLinks_dedupesLinuxAndDockerPaths(t *testing.T) { + testSourceConfig(t) + + in := []users.SidebarLink{ + {Name: "playwright + files", Category: "source", SourceName: "/app/frontend/tests/playwright-files", Target: "/"}, + {Name: "docker", Category: "source", SourceName: "/app/backend", Target: "/"}, + {Name: "access", Category: "source", SourceName: "/tests/playwright-files", Target: "/"}, + {Name: "playwright + files", Category: "source", SourceName: "../frontend/tests/playwright-files", Target: "/"}, + {Name: "docker", Category: "source", SourceName: ".", Target: "/"}, + {Name: "access", Category: "source", SourceName: "/tests/playwright-files", Target: "/"}, + } + + out, changed := NormalizeSidebarLinks(in) + if !changed { + t.Fatal("expected changed=true") + } + if len(out) != 3 { + t.Fatalf("len(out) = %d, want 3", len(out)) + } + want := []users.SidebarLink{ + {Name: "playwright + files", Category: "source", SourceName: "../frontend/tests/playwright-files", Target: "/"}, + {Name: "docker", Category: "source", SourceName: ".", Target: "/"}, + {Name: "access", Category: "source", SourceName: "/tests/playwright-files", Target: "/"}, + } + if !reflect.DeepEqual(out, want) { + t.Fatalf("got %#v, want %#v", out, want) + } +} + +func TestNormalizeSidebarLinks_nameFallbackRemapsStalePath(t *testing.T) { + testSourceConfig(t) + + in := []users.SidebarLink{ + {Name: "playwright + files", Category: "source", SourceName: "/app/frontend/tests/playwright-files", Target: "/"}, + } + + out, changed := NormalizeSidebarLinks(in) + if !changed { + t.Fatal("expected changed=true") + } + if len(out) != 1 { + t.Fatalf("len(out) = %d, want 1", len(out)) + } + if out[0].SourceName != "../frontend/tests/playwright-files" { + t.Fatalf("SourceName = %q", out[0].SourceName) + } + if out[0].Name != "playwright + files" { + t.Fatalf("Name = %q", out[0].Name) + } +} + +func TestNormalizeSidebarLinks_idempotentOnCanonicalLinks(t *testing.T) { + testSourceConfig(t) + + in := []users.SidebarLink{ + {Name: "playwright + files", Category: "source", SourceName: "../frontend/tests/playwright-files", Target: "/"}, + {Name: "docker", Category: "source", SourceName: ".", Target: "/"}, + {Name: "access", Category: "source", SourceName: "/tests/playwright-files", Target: "/"}, + } + + out, changed := NormalizeSidebarLinks(in) + if changed { + t.Fatal("expected changed=false for canonical links") + } + if !reflect.DeepEqual(out, in) { + t.Fatalf("got %#v, want %#v", out, in) + } + + out2, changed2 := NormalizeSidebarLinks(out) + if changed2 { + t.Fatal("expected second pass unchanged") + } + if !reflect.DeepEqual(out2, in) { + t.Fatalf("second pass got %#v", out2) + } +} + +func TestNormalizeSidebarLinks_dropsUnresolvableSourceLink(t *testing.T) { + testSourceConfig(t) + + in := []users.SidebarLink{ + {Name: "ghost", Category: "source", SourceName: "/no/such/path", Target: "/"}, + {Name: "docker", Category: "source", SourceName: ".", Target: "/"}, + } + + out, changed := NormalizeSidebarLinks(in) + if !changed { + t.Fatal("expected changed=true") + } + if len(out) != 1 { + t.Fatalf("len(out) = %d, want 1", len(out)) + } + if out[0].Name != "docker" { + t.Fatalf("remaining link = %#v", out[0]) + } +} + +func TestNormalizeSidebarLinks_dedupesToolsLink(t *testing.T) { + testSourceConfig(t) + + tools := users.SidebarLink{Name: "Tools", Category: "tool", Target: "/tools", Icon: "build"} + in := []users.SidebarLink{ + tools, + tools, + } + + out, changed := NormalizeSidebarLinks(in) + if !changed { + t.Fatal("expected changed=true") + } + if len(out) != 1 { + t.Fatalf("len(out) = %d, want 1", len(out)) + } +} + +func TestNormalizeSidebarLinks_noConfigLoaded(t *testing.T) { + had := users.SourceConfigLoaded() + t.Cleanup(func() { + if !had { + users.SetSourceConfig(nil) + } + }) + users.SetSourceConfig(nil) + + in := []users.SidebarLink{{Name: "x", Category: "source", SourceName: "."}} + out, changed := NormalizeSidebarLinks(in) + if changed { + t.Fatal("expected changed=false when source config not loaded") + } + if !reflect.DeepEqual(out, in) { + t.Fatalf("got %#v", out) + } +} diff --git a/backend/internal/usersidebar/scopes.go b/backend/internal/usersidebar/scopes.go new file mode 100644 index 0000000000..7cfbb35b15 --- /dev/null +++ b/backend/internal/usersidebar/scopes.go @@ -0,0 +1,103 @@ +package usersidebar + +import ( + "strings" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// EnsureSidebarLinksFromScopes adds source sidebar links for scoped sources that have no link yet. +// Existing links (including custom names, icons, and categories) are preserved. +func EnsureSidebarLinksFromScopes(links []users.SidebarLink, scopes []users.BackendScope) ([]users.SidebarLink, bool) { + if !users.SourceConfigLoaded() || len(scopes) == 0 { + return links, false + } + + present := sourcePathsInSidebarLinks(links) + out := append([]users.SidebarLink(nil), links...) + changed := false + + for _, scope := range uniqueScopedSourcePaths(scopes) { + if _, ok := present[scope]; ok { + continue + } + source, ok := users.ResolveSourceKey(scope) + if !ok { + continue + } + out = append(out, users.SidebarLink{ + Name: source.Name, + Category: string(users.SidebarLinkSource), + Target: "/", + SourceName: source.Path, + }) + present[source.Path] = struct{}{} + changed = true + } + + return out, changed +} + +// ValidSourceSidebarLinkCount returns how many source links resolve to a configured source. +func ValidSourceSidebarLinkCount(links []users.SidebarLink) int { + count := 0 + for _, link := range links { + if !users.IsSourceSidebarCategory(link.Category) { + continue + } + if _, ok := resolveSourceLink(link); ok { + count++ + } + } + return count +} + +func uniqueScopedSourcePaths(scopes []users.BackendScope) []string { + seen := make(map[string]struct{}, len(scopes)) + out := make([]string, 0, len(scopes)) + for _, scope := range scopes { + path := strings.TrimSpace(scope.Path) + if path == "" { + continue + } + if _, dup := seen[path]; dup { + continue + } + seen[path] = struct{}{} + out = append(out, path) + } + return out +} + +func sourcePathsInSidebarLinks(links []users.SidebarLink) map[string]struct{} { + present := make(map[string]struct{}) + for _, link := range links { + if !users.IsSourceSidebarCategory(link.Category) { + continue + } + source, ok := resolveSourceLink(link) + if !ok { + continue + } + present[source.Path] = struct{}{} + } + return present +} + +func NeedsSidebarLinksFromScopes(links []users.SidebarLink, scopes []users.BackendScope) bool { + scopePaths := uniqueScopedSourcePaths(scopes) + if len(scopePaths) == 0 { + return false + } + valid := ValidSourceSidebarLinkCount(links) + if valid == 0 { + return true + } + present := sourcePathsInSidebarLinks(links) + for _, path := range scopePaths { + if _, ok := present[path]; !ok { + return true + } + } + return false +} diff --git a/backend/internal/usersidebar/scopes_test.go b/backend/internal/usersidebar/scopes_test.go new file mode 100644 index 0000000000..b0c326f5dc --- /dev/null +++ b/backend/internal/usersidebar/scopes_test.go @@ -0,0 +1,112 @@ +package usersidebar + +import ( + "reflect" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func TestNormalizeSidebarLinks_preservesCustomSourceNameAndIcon(t *testing.T) { + testSourceConfig(t) + + in := []users.SidebarLink{ + { + Name: "My Files", + Category: string(users.SidebarLinkSourceMinimal), + Icon: "folder", + SourceName: "../frontend/tests/playwright-files", + Target: "/", + }, + } + + out, changed := NormalizeSidebarLinks(in) + if changed { + t.Fatal("expected canonical link unchanged") + } + if len(out) != 1 { + t.Fatalf("len(out) = %d, want 1", len(out)) + } + if out[0].Name != "My Files" { + t.Fatalf("Name = %q, want custom name preserved", out[0].Name) + } + if out[0].Icon != "folder" { + t.Fatalf("Icon = %q, want folder", out[0].Icon) + } + if out[0].Category != string(users.SidebarLinkSourceMinimal) { + t.Fatalf("Category = %q", out[0].Category) + } +} + +func TestEnsureSidebarLinksFromScopes_addsMissingScopedSources(t *testing.T) { + testSourceConfig(t) + + links := []users.SidebarLink{ + { + Name: "docker", + Category: string(users.SidebarLinkSource), + SourceName: ".", + Target: "/", + }, + { + Name: "Docs", + Category: string(users.SidebarLinkCustom), + Target: "https://example.com", + Icon: "link", + }, + } + scopes := []users.BackendScope{ + {Path: "."}, + {Path: "../frontend/tests/playwright-files"}, + } + + out, changed := EnsureSidebarLinksFromScopes(links, scopes) + if !changed { + t.Fatal("expected changed=true") + } + if len(out) != 3 { + t.Fatalf("len(out) = %d, want 3", len(out)) + } + if out[2].Name != "playwright + files" { + t.Fatalf("added link = %#v", out[2]) + } + if out[1].Category != string(users.SidebarLinkCustom) { + t.Fatalf("custom link lost: %#v", out[1]) + } +} + +func TestNeedsSidebarLinksFromScopes_partialCoverage(t *testing.T) { + testSourceConfig(t) + + links := []users.SidebarLink{ + {Name: "docker", Category: "source", SourceName: ".", Target: "/"}, + } + scopes := []users.BackendScope{ + {Path: "."}, + {Path: "../frontend/tests/playwright-files"}, + } + if !NeedsSidebarLinksFromScopes(links, scopes) { + t.Fatal("expected partial scope coverage to need merge") + } +} + +func TestEnsureSidebarLinksFromScopes_idempotent(t *testing.T) { + testSourceConfig(t) + + links := []users.SidebarLink{ + {Name: "playwright + files", Category: "source", SourceName: "../frontend/tests/playwright-files", Target: "/"}, + {Name: "docker", Category: "source", SourceName: ".", Target: "/"}, + } + scopes := []users.BackendScope{ + {Path: "../frontend/tests/playwright-files"}, + {Path: "."}, + } + + out, changed := EnsureSidebarLinksFromScopes(links, scopes) + if changed { + t.Fatal("expected changed=false") + } + if !reflect.DeepEqual(out, links) { + t.Fatalf("got %#v", out) + } +} diff --git a/backend/common/utils/cache.go b/backend/internal/utils/cache.go similarity index 78% rename from backend/common/utils/cache.go rename to backend/internal/utils/cache.go index 2d399b654b..c8f56e4784 100644 --- a/backend/common/utils/cache.go +++ b/backend/internal/utils/cache.go @@ -12,4 +12,6 @@ var ( SearchResultsCache = cache.NewCache[string](15*time.Second, 1*time.Hour) OnlyOfficeCache = cache.NewCache[string](48*time.Hour, 1*time.Hour) JwtCache = cache.NewCache[string](1*time.Hour, 72*time.Hour) + ViewGrantsCache = cache.NewCache[ViewGrant](15 * time.Minute) + ViewGrantIndex = cache.NewCache[string](15 * time.Minute) ) diff --git a/backend/common/utils/checkForUpdates.go b/backend/internal/utils/checkForUpdates.go similarity index 97% rename from backend/common/utils/checkForUpdates.go rename to backend/internal/utils/checkForUpdates.go index 2faa34bf7a..f8fc4a2d38 100644 --- a/backend/common/utils/checkForUpdates.go +++ b/backend/internal/utils/checkForUpdates.go @@ -8,7 +8,7 @@ import ( "strings" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/version" + "github.com/gtsteffaniak/filebrowser/backend/internal/version" "github.com/gtsteffaniak/go-logger/logger" "golang.org/x/mod/semver" ) diff --git a/backend/common/utils/crypto.go b/backend/internal/utils/crypto.go similarity index 79% rename from backend/common/utils/crypto.go rename to backend/internal/utils/crypto.go index a392b8b818..34b529160d 100644 --- a/backend/common/utils/crypto.go +++ b/backend/internal/utils/crypto.go @@ -4,7 +4,9 @@ import ( "crypto/rand" "crypto/sha256" "encoding/base64" + "encoding/binary" "encoding/hex" + "fmt" "golang.org/x/crypto/bcrypt" ) @@ -54,6 +56,21 @@ func HashSHA256(data string) string { return hex.EncodeToString(bytes[:]) } +// RandomUint64ID returns a non-zero cryptographically random uint64 (e.g. new user rows after migration). +// Small ids 1, 2, 3, … remain valid for migrated Bolt-era users. +func RandomUint64ID() (uint64, error) { + var b [8]byte + for { + if _, err := rand.Read(b[:]); err != nil { + return 0, fmt.Errorf("random id: %w", err) + } + id := binary.BigEndian.Uint64(b[:]) + if id != 0 { + return id, nil + } + } +} + func GenerateKey() string { b := make([]byte, 64) _, err := rand.Read(b) diff --git a/backend/common/utils/file.go b/backend/internal/utils/file.go similarity index 78% rename from backend/common/utils/file.go rename to backend/internal/utils/file.go index a511860609..f56a70e3a8 100644 --- a/backend/common/utils/file.go +++ b/backend/internal/utils/file.go @@ -10,10 +10,10 @@ import ( "hash" "io" "os" - "path/filepath" + "path" "strings" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" ) // GetChecksum calculates the checksum of a file using the specified algorithm. @@ -57,8 +57,8 @@ type FileOptions struct { ExtractEmbeddedSubtitles bool // whether to extract embedded subtitles from media files AlbumArt bool // whether to get album art from media files ShowHidden bool // whether to show hidden files (true = show, false = hide) - ShowPinnedItems bool // whether to show pinned items - ShareHash string // when set, pinned items are loaded from this share link + ShowPinnedItems bool // whether to show pinned items + ShareHash string // when set, pinned items are loaded from this share link HideFileExt string // Hide files based on extensions (eg: '.lrc' or '.srt') FollowSymlinks bool // whether to follow symlinks Only string // whether to only get files or folders @@ -66,25 +66,25 @@ type FileOptions struct { ShowSharedAttr bool // whether to show share attributes } -// SanitizeUserPath prevents path traversal attacks by cleaning and validating user input. -// Rule 1: Do Not Use User Input in File Paths (without validation) -func SanitizeUserPath(userPath string) (string, error) { - clean := filepath.Clean(userPath) +// SanitizePath cleans and validates a path or path-like filter (index paths, globs, etc.) +// to block traversal. Rule 1: Do Not Use Untrusted Input in File Paths (without validation). +func SanitizePath(inputPath string) (string, error) { + clean := path.Clean(inputPath) - // Split the path into segments to check for path traversal attempts - // We check if ".." appears as a complete path segment (not just in a filename) - segments := strings.Split(clean, string(filepath.Separator)) + // Split the path into segments to check for path traversal attempts. + // We check if ".." appears as a complete path segment (not just in a filename). + segments := strings.Split(clean, "/") for _, segment := range segments { - // Check if any segment is exactly ".." (path traversal attempt) - // This catches any ".." that filepath.Clean couldn't resolve (i.e., escape attempts) + // Check if any segment is exactly ".." (path traversal attempt). + // This catches any ".." that path.Clean couldn't resolve (i.e., escape attempts). if segment == ".." { return "", fmt.Errorf("invalid path: path traversal detected") } } if clean == "." { - return "", fmt.Errorf("invalid path: path must standard index path") + return "", fmt.Errorf("invalid path: path must be a standard index path") } return clean, nil diff --git a/backend/internal/utils/indexpath.go b/backend/internal/utils/indexpath.go new file mode 100644 index 0000000000..3270f7d35f --- /dev/null +++ b/backend/internal/utils/indexpath.go @@ -0,0 +1,101 @@ +package utils + +import ( + "fmt" + "strings" +) + +// IndexPath is a normalized index-relative path with explicit directory vs file semantics. +// Parts holds path segments only (no empty strings). An empty Parts slice represents root "/". +// String() always returns a path starting with "/". Directories include a trailing slash; files do not. +type IndexPath struct { + Parts []string + IsDir bool +} + +// NewIndexPath builds an IndexPath from already-separated segments (internal use). +func NewIndexPath(parts []string, isDir bool) IndexPath { + return IndexPath{Parts: parts, IsDir: isDir} +} + +// IndexPathFromNormalized parses an already-normalized slash-separated path (internal/indexer use). +func IndexPathFromNormalized(path string, isDir bool) IndexPath { + p, _ := parseIndexPath(path, isDir, false) + return p +} + +// ParseSanitizedIndexPath validates external path input then parses a slash-separated index path. +func ParseSanitizedIndexPath(userPath string, isDir bool) (IndexPath, error) { + clean, err := SanitizePath(userPath) + if err != nil { + return IndexPath{}, err + } + return parseIndexPath(clean, isDir, true) +} + +func parseIndexPath(path string, isDir bool, strict bool) (IndexPath, error) { + if strict && strings.Contains(path, `\`) { + return IndexPath{}, fmt.Errorf("invalid path: backslashes not allowed") + } + + inner := strings.Trim(path, "/") + if inner == "" { + return IndexPath{IsDir: isDir}, nil + } + + parts := strings.FieldsFunc(inner, func(r rune) bool { + return r == '/' + }) + if strict { + for _, part := range parts { + if part == "." || part == ".." { + return IndexPath{}, fmt.Errorf("invalid path: %q segment not allowed", part) + } + } + } + + return IndexPath{Parts: parts, IsDir: isDir}, nil +} + +// String returns the canonical index path string. Never returns an empty string; root is "/". +func (p IndexPath) String() string { + if len(p.Parts) == 0 { + return "/" + } + s := "/" + strings.Join(p.Parts, "/") + if p.IsDir { + return s + "/" + } + return s +} + +// AsDirectory returns a copy with directory semantics (trailing slash when stringified). +func (p IndexPath) AsDirectory() IndexPath { + if p.IsDir { + return p + } + return IndexPath{Parts: append([]string(nil), p.Parts...), IsDir: true} +} + +// IsRoot reports whether this path is the index root. +func (p IndexPath) IsRoot() bool { + return len(p.Parts) == 0 +} + +// Parent returns the parent directory path. Root's parent is root. +func (p IndexPath) Parent() IndexPath { + if p.IsRoot() { + return IndexPath{IsDir: true} + } + return IndexPath{Parts: append([]string(nil), p.Parts[:len(p.Parts)-1]...), IsDir: true} +} + +// Join appends a single path segment and sets directory vs file semantics. +func (p IndexPath) Join(name string, isDir bool) IndexPath { + return IndexPath{Parts: append(append([]string(nil), p.Parts...), name), IsDir: isDir} +} + +// RuleKey returns the canonical string key for access rule storage (always directory form). +func (p IndexPath) RuleKey() string { + return p.AsDirectory().String() +} diff --git a/backend/internal/utils/indexpath_test.go b/backend/internal/utils/indexpath_test.go new file mode 100644 index 0000000000..35bdb0ff70 --- /dev/null +++ b/backend/internal/utils/indexpath_test.go @@ -0,0 +1,182 @@ +package utils + +import ( + "strings" + "testing" +) + +func TestIndexPathFromNormalized_String(t *testing.T) { + tests := []struct { + name string + input string + isDir bool + expected string + }{ + {"root slash", "/", true, "/"}, + {"empty", "", true, "/"}, + {"hidden at root", "/.test", true, "/.test/"}, + {"trailing slash dir", "/test/", true, "/test/"}, + {"nested dir", "/nested/path", true, "/nested/path/"}, + {"file no trailing", "/test/file.txt", false, "/test/file.txt"}, + {"single file segment", "file.txt", false, "/file.txt"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := IndexPathFromNormalized(tt.input, tt.isDir).String() + if got != tt.expected { + t.Errorf("IndexPathFromNormalized(%q, %v).String() = %q, want %q", tt.input, tt.isDir, got, tt.expected) + } + }) + } +} + +func TestParseIndexPath_consecutiveSlashes(t *testing.T) { + got := IndexPathFromNormalized("/a//b/", true) + if got.String() != "/a/b/" { + t.Errorf("got %q want /a/b/", got.String()) + } + if len(got.Parts) != 2 { + t.Errorf("Parts = %v, want [a b]", got.Parts) + } +} + +func TestSanitizePath_indexPaths(t *testing.T) { + tests := []struct { + name string + input string + want string + wantErr bool + }{ + {"root slash", "/", "/", false}, + {"nested", "/foo/bar", "/foo/bar", false}, + {"traversal segment", "..", "", true}, + {"resolved traversal", "/../secret", "/secret", false}, + {"empty", "", "", true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := SanitizePath(tt.input) + if tt.wantErr { + if err == nil { + t.Fatalf("SanitizePath(%q) expected error", tt.input) + } + return + } + if err != nil { + t.Fatalf("SanitizePath(%q) unexpected error: %v", tt.input, err) + } + if strings.Contains(got, `\`) { + t.Errorf("SanitizePath(%q) = %q contains backslash", tt.input, got) + } + if got != tt.want { + t.Errorf("SanitizePath(%q) = %q, want %q", tt.input, got, tt.want) + } + }) + } +} + +func TestParseSanitizedIndexPath_root(t *testing.T) { + got, err := ParseSanitizedIndexPath("/", true) + if err != nil { + t.Fatalf("ParseSanitizedIndexPath(/): %v", err) + } + if got.String() != "/" { + t.Errorf("got %q want /", got.String()) + } +} + +func TestParseSanitizedIndexPath(t *testing.T) { + _, err := ParseSanitizedIndexPath("..", true) + if err == nil { + t.Fatal("expected error for .. path") + } + + got, err := ParseSanitizedIndexPath("/valid/path/", true) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got.String() != "/valid/path/" { + t.Errorf("got %q want /valid/path/", got.String()) + } + + // SanitizePath resolves traversal; result is a normal index path + got, err = ParseSanitizedIndexPath("/../secret", true) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got.String() != "/secret/" { + t.Errorf("got %q want /secret/", got.String()) + } +} + +func TestIndexPath_Parent(t *testing.T) { + tests := []struct { + name string + path IndexPath + expected string + }{ + {"root parent", IndexPathFromNormalized("/", true), "/"}, + {"one level", IndexPathFromNormalized("/a/", true), "/"}, + {"two levels", IndexPathFromNormalized("/a/b/", true), "/a/"}, + {"file parent is dir", IndexPathFromNormalized("/a/b.txt", false), "/a/"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.path.Parent().String() + if got != tt.expected { + t.Errorf("Parent().String() = %q, want %q", got, tt.expected) + } + }) + } +} + +func TestIndexPath_Join(t *testing.T) { + root := IndexPathFromNormalized("/", true) + child := root.Join("test", true) + if child.String() != "/test/" { + t.Errorf("Join dir got %q, want /test/", child.String()) + } + file := root.Join("readme.txt", false) + if file.String() != "/readme.txt" { + t.Errorf("Join file got %q, want /readme.txt", file.String()) + } +} + +func TestIndexPath_RuleKey(t *testing.T) { + file := IndexPathFromNormalized("/foo/bar.txt", false) + if file.RuleKey() != "/foo/bar.txt/" { + t.Errorf("RuleKey() = %q, want /foo/bar.txt/", file.RuleKey()) + } + dir := IndexPathFromNormalized("/foo/", true) + if dir.RuleKey() != "/foo/" { + t.Errorf("RuleKey() = %q, want /foo/", dir.RuleKey()) + } +} + +func TestAddTrailingSlashIfNotExists(t *testing.T) { + if AddTrailingSlashIfNotExists("/foo") != "/foo/" { + t.Errorf("expected /foo/") + } + if AddTrailingSlashIfNotExists("/") != "/" { + t.Errorf("root should stay /") + } +} + +func BenchmarkIndexPathFromNormalized(b *testing.B) { + const input = "/nested/path/to/resource/" + b.ReportAllocs() + for b.Loop() { + _ = IndexPathFromNormalized(input, true) + } +} + +func BenchmarkParseSanitizedIndexPath(b *testing.B) { + const input = "/nested/path/to/resource/" + b.ReportAllocs() + for b.Loop() { + _, _ = ParseSanitizedIndexPath(input, true) + } +} diff --git a/backend/common/utils/main.go b/backend/internal/utils/main.go similarity index 59% rename from backend/common/utils/main.go rename to backend/internal/utils/main.go index afc702eac8..60817dacd9 100644 --- a/backend/common/utils/main.go +++ b/backend/internal/utils/main.go @@ -5,9 +5,7 @@ import ( "fmt" math "math/rand" "os" - "path/filepath" "reflect" - "runtime" "strings" "time" @@ -65,41 +63,6 @@ func PrintStructFields(v interface{}) { } } -func GetParentDirectoryPath(path string) string { - if path == "/" || path == "" { - return "" - } - path = strings.TrimSuffix(path, "/") // Remove trailing slash if any - lastSlash := strings.LastIndex(path, "/") - if lastSlash == -1 { - return "" // No parent directory for a relative path without slashes - } - if lastSlash == 0 { - return "/" // If the last slash is the first character, return root - } - return path[:lastSlash] -} - -func GetLastComponent(path string) string { - if path == "" { - return "" - } - path = strings.TrimSuffix(path, "/") // Remove trailing slash if any - lastSlash := strings.LastIndex(path, "/") - if lastSlash == -1 { - return path // No parent directory for a relative path without slashes - } - return path[lastSlash+1:] -} - -func JoinPathAsUnix(parts ...string) string { - joinedPath := filepath.Join(parts...) - if runtime.GOOS == "windows" { - joinedPath = strings.ReplaceAll(joinedPath, "\\", "/") - } - return joinedPath -} - func NonNilSlice[T any](in []T) []T { if in == nil { return []T{} @@ -128,19 +91,6 @@ func Clamp[T cmp.Ordered](value, min, max T) T { return value } -// NormalizeRulePath ensures directory paths have trailing slashes for consistent rule storage -func AddTrailingSlashIfNotExists(indexPath string) string { - // Root path stays as "/" - if indexPath == "/" { - return "/" - } - // For all other paths, ensure they have trailing slashes - if !strings.HasSuffix(indexPath, "/") { - return indexPath + "/" - } - return indexPath -} - func CheckPathExists(realPath string) bool { if _, err := os.Stat(realPath); os.IsNotExist(err) { return false diff --git a/backend/common/utils/main_test.go b/backend/internal/utils/main_test.go similarity index 100% rename from backend/common/utils/main_test.go rename to backend/internal/utils/main_test.go diff --git a/backend/common/utils/media.go b/backend/internal/utils/media.go similarity index 100% rename from backend/common/utils/media.go rename to backend/internal/utils/media.go diff --git a/backend/common/utils/mocks.go b/backend/internal/utils/mocks.go similarity index 100% rename from backend/common/utils/mocks.go rename to backend/internal/utils/mocks.go diff --git a/backend/internal/utils/path.go b/backend/internal/utils/path.go new file mode 100644 index 0000000000..3fa94ca90e --- /dev/null +++ b/backend/internal/utils/path.go @@ -0,0 +1,53 @@ +package utils + +import ( + "path/filepath" + "runtime" + "strings" +) + +func GetParentDirectoryPath(path string) string { + if path == "/" || path == "" { + return "" + } + path = strings.TrimSuffix(path, "/") // Remove trailing slash if any + lastSlash := strings.LastIndex(path, "/") + if lastSlash == -1 { + return "" // No parent directory for a relative path without slashes + } + if lastSlash == 0 { + return "/" // If the last slash is the first character, return root + } + return path[:lastSlash] +} + +func GetLastComponent(path string) string { + if path == "" { + return "" + } + path = strings.TrimSuffix(path, "/") // Remove trailing slash if any + lastSlash := strings.LastIndex(path, "/") + if lastSlash == -1 { + return path // No parent directory for a relative path without slashes + } + return path[lastSlash+1:] +} + +func JoinPathAsUnix(parts ...string) string { + joinedPath := filepath.Join(parts...) + if runtime.GOOS == "windows" { + joinedPath = strings.ReplaceAll(joinedPath, "\\", "/") + } + return joinedPath +} + +// AddTrailingSlashIfNotExists ensures a directory index path has a trailing slash (root stays "/"). +func AddTrailingSlashIfNotExists(indexPath string) string { + if indexPath == "" || indexPath == "/" { + return "/" + } + if indexPath[len(indexPath)-1] != '/' { + return indexPath + "/" + } + return indexPath +} diff --git a/backend/internal/utils/stream_grant.go b/backend/internal/utils/stream_grant.go new file mode 100644 index 0000000000..ebbd20fe95 --- /dev/null +++ b/backend/internal/utils/stream_grant.go @@ -0,0 +1,8 @@ +package utils + +// ViewGrant authorizes inline viewing/streaming within a scoped context. +// Source is a storage source name for authenticated browsing, or a share hash on public shares. +type ViewGrant struct { + Source string + ExpiresAt int64 +} diff --git a/backend/common/utils/textfile.go b/backend/internal/utils/textfile.go similarity index 100% rename from backend/common/utils/textfile.go rename to backend/internal/utils/textfile.go diff --git a/backend/common/version/version.go b/backend/internal/version/version.go similarity index 100% rename from backend/common/version/version.go rename to backend/internal/version/version.go diff --git a/backend/http/access.go b/backend/internal/web/access.go similarity index 68% rename from backend/http/access.go rename to backend/internal/web/access.go index f998fdfe5d..22f5dec9d5 100644 --- a/backend/http/access.go +++ b/backend/internal/web/access.go @@ -1,11 +1,16 @@ -package http +package web import ( "encoding/json" "fmt" "net/http" - "github.com/gtsteffaniak/filebrowser/backend/indexing" + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/activity" + "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/indexing" "github.com/gtsteffaniak/go-logger/logger" ) @@ -13,6 +18,23 @@ type GroupListResponse struct { Groups []string `json:"groups"` } +// parseAccessQueryPath validates and parses an index path from an API query parameter. +func parseAccessQueryPath(path string) (utils.IndexPath, error) { + if path == "" { + return utils.IndexPath{}, fmt.Errorf("path is required") + } + return utils.ParseSanitizedIndexPath(path, true) +} + +// parseAccessQueryPathOrBadRequest wraps parseAccessQueryPath with a standard HTTP 400 response. +func parseAccessQueryPathOrBadRequest(path string) (utils.IndexPath, int, error) { + parsed, err := parseAccessQueryPath(path) + if err != nil { + return utils.IndexPath{}, http.StatusBadRequest, err + } + return parsed, 0, nil +} + // accessGetHandler lists all access rules or retrieves a specific rule. // @Summary List access rules // @Description Lists access rules. Can be filtered by source, path, user, or group. Can also be grouped by user or group. @@ -27,7 +49,7 @@ type GroupListResponse struct { // @Failure 400 {object} map[string]string "Bad request" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/access [get] -func accessGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func accessGetHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { sourceName := r.URL.Query().Get("source") indexPath := r.URL.Query().Get("path") user := r.URL.Query().Get("user") @@ -44,30 +66,36 @@ func accessGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) // Return rules based on input parameters if user != "" { - rules := store.Access.GetRulesForUser(sourcePath, user) - return renderJSON(w, r, rules) + rules := state.GetRulesForUser(sourcePath, user) + return RenderJSON(w, r, rules) } if group != "" { - rules := store.Access.GetRulesForGroup(sourcePath, group) - return renderJSON(w, r, rules) + rules := state.GetRulesForGroup(sourcePath, group) + return RenderJSON(w, r, rules) } if sourceName == "" { + logger.Warningf("api access GET: empty source query (user=%q admin=%v path=%q userQ=%q groupQ=%q)", + d.User.Username, d.User.Permissions.Admin, indexPath, user, group) return http.StatusBadRequest, fmt.Errorf("source parameter is required for this query") } if indexPath != "" { - rule, _ := store.Access.GetFrontendRules(sourcePath, indexPath) - return renderJSON(w, r, rule) + parsedPath, status, err := parseAccessQueryPathOrBadRequest(indexPath) + if err != nil { + return status, err + } + rule, _ := state.GetFrontendRules(sourcePath, parsedPath) + return RenderJSON(w, r, rule) } // List all rules for the source by default - all, err := store.Access.GetAllRules(sourcePath) + all, err := state.GetAllRules(sourcePath) if err != nil { logger.Errorf("failed to retrieve access rules: %v", err) return http.StatusInternalServerError, fmt.Errorf("failed to retrieve access rules: %w", err) } - return renderJSON(w, r, all) + return RenderJSON(w, r, all) } // accessPostHandler adds or updates an access rule. @@ -83,7 +111,7 @@ func accessGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) // @Failure 400 {object} map[string]string "Bad request" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/access [post] -func accessPostHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func accessPostHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { sourceName := r.URL.Query().Get("source") indexPath := r.URL.Query().Get("path") index := indexing.GetIndex(sourceName) @@ -102,24 +130,35 @@ func accessPostHandler(w http.ResponseWriter, r *http.Request, d *requestContext if indexPath == "" || body.RuleCategory == "" || (body.RuleCategory != "all" && body.Value == "") { return http.StatusBadRequest, fmt.Errorf("path, ruleCategory, and value are required, unless ruleCategory is 'all'") } - var err error + parsedPath, status, err := parseAccessQueryPathOrBadRequest(indexPath) + if err != nil { + return status, err + } + if body.RuleCategory == "user" { + if _, err = state.GetUserByUsername(body.Value); err != nil { + if err == errors.ErrNotExist { + return http.StatusBadRequest, fmt.Errorf("user not found: %s", body.Value) + } + return http.StatusInternalServerError, fmt.Errorf("failed to look up user: %w", err) + } + } if body.Allow { switch body.RuleCategory { case "user": - err = store.Access.AllowUser(index.Path, indexPath, body.Value) + err = state.AllowUser(index.Path, parsedPath, body.Value) case "group": - err = store.Access.AllowGroup(index.Path, indexPath, body.Value) + err = state.AllowGroup(index.Path, parsedPath, body.Value) default: return http.StatusBadRequest, fmt.Errorf("invalid ruleCategory: must be 'user' or 'group'") } } else { switch body.RuleCategory { case "user": - err = store.Access.DenyUser(index.Path, indexPath, body.Value) + err = state.DenyUser(index.Path, parsedPath, body.Value) case "group": - err = store.Access.DenyGroup(index.Path, indexPath, body.Value) + err = state.DenyGroup(index.Path, parsedPath, body.Value) case "all": - err = store.Access.DenyAll(index.Path, indexPath) + err = state.DenyAll(index.Path, parsedPath) default: return http.StatusBadRequest, fmt.Errorf("invalid ruleCategory: must be 'user', 'group', or 'all'") } @@ -128,7 +167,8 @@ func accessPostHandler(w http.ResponseWriter, r *http.Request, d *requestContext logger.Errorf("failed to add or update rule: %v", err) return http.StatusInternalServerError, fmt.Errorf("failed to add or update rule: %w", err) } - return renderJSON(w, r, map[string]string{"message": "rule added or updated"}) + activity.RecordAccessCreate(r, toActor(d), sourceName, parsedPath.String(), activity.AccessRuleCreateChanges(body.Allow, body.RuleCategory, body.Value)) + return RenderJSON(w, r, map[string]string{"message": "rule added or updated"}) } // accessDeleteHandler deletes a single user or group from a rule. @@ -148,7 +188,7 @@ func accessPostHandler(w http.ResponseWriter, r *http.Request, d *requestContext // @Failure 400 {object} map[string]string "Bad request" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/access [delete] -func accessDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func accessDeleteHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { sourceName := r.URL.Query().Get("source") indexPath := r.URL.Query().Get("path") index := indexing.GetIndex(sourceName) @@ -165,6 +205,10 @@ func accessDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestConte if indexPath == "" || ruleCategory == "" || (ruleCategory != "all" && value == "") { return http.StatusBadRequest, fmt.Errorf("path, ruleCategory, and value are required, unless ruleCategory is 'all'") } + parsedPath, status, err := parseAccessQueryPathOrBadRequest(indexPath) + if err != nil { + return status, err + } // Handle cascade delete if cascade { @@ -173,13 +217,12 @@ func accessDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestConte } var count int - var err error switch ruleCategory { case "user": - count, err = store.Access.RemoveUserCascade(index.Path, indexPath, value, allow) + count, err = state.RemoveUserCascade(index.Path, parsedPath, value, allow) case "group": - count, err = store.Access.RemoveGroupCascade(index.Path, indexPath, value, allow) + count, err = state.RemoveGroupCascade(index.Path, parsedPath, value, allow) default: return http.StatusBadRequest, fmt.Errorf("invalid ruleCategory for cascade delete: must be 'user' or 'group'") } @@ -193,7 +236,8 @@ func accessDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestConte return http.StatusNotFound, fmt.Errorf("no entries found in rule hierarchy") } - return renderJSON(w, r, map[string]interface{}{ + activity.RecordAccessDelete(r, toActor(d), sourceName, parsedPath.String(), activity.AccessRuleDeleteChanges(ruleType, ruleCategory, value, true, count)) + return RenderJSON(w, r, map[string]interface{}{ "message": "rule entries deleted", "count": count, }) @@ -201,32 +245,33 @@ func accessDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestConte // Handle non-cascade delete (original behavior) var found bool - var err error if allow { switch ruleCategory { case "user": - found, err = store.Access.RemoveAllowUser(index.Path, indexPath, value) + found, err = state.RemoveAllowUser(index.Path, parsedPath, value) case "group": - found, err = store.Access.RemoveAllowGroup(index.Path, indexPath, value) + found, err = state.RemoveAllowGroup(index.Path, parsedPath, value) } } else { switch ruleCategory { case "user": - found, err = store.Access.RemoveDenyUser(index.Path, indexPath, value) + found, err = state.RemoveDenyUser(index.Path, parsedPath, value) case "group": - found, err = store.Access.RemoveDenyGroup(index.Path, indexPath, value) + found, err = state.RemoveDenyGroup(index.Path, parsedPath, value) case "all": - found, err = store.Access.RemoveDenyAll(index.Path, indexPath) + found, err = state.RemoveDenyAll(index.Path, parsedPath) } } + if err != nil { + logger.Errorf("failed to remove rule entry: %v", err) + return http.StatusInternalServerError, fmt.Errorf("failed to remove rule entry: %w", err) + } if !found { - if err != nil { - logger.Errorf("failed to remove rule entry: %v", err) - } return http.StatusNotFound, fmt.Errorf("entry not found in rule") } - return renderJSON(w, r, map[string]string{"message": "rule entry deleted"}) + activity.RecordAccessDelete(r, toActor(d), sourceName, parsedPath.String(), activity.AccessRuleDeleteChanges(ruleType, ruleCategory, value, false, 0)) + return RenderJSON(w, r, map[string]string{"message": "rule entry deleted"}) } // groupGetHandler retrieves all groups or groups for a specific user. @@ -239,17 +284,17 @@ func accessDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestConte // @Success 200 {object} GroupListResponse "Object containing a list of groups" // @Failure 403 {object} map[string]string "Forbidden" // @Router /api/access/groups [get] -func groupGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !d.user.Permissions.Admin { +func groupGetHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if !d.User.Permissions.Admin { return http.StatusForbidden, nil } user := r.URL.Query().Get("user") if user != "" { - groups := store.Access.GetUserGroups(user) - return renderJSON(w, r, &GroupListResponse{Groups: groups}) + groups := state.GetUserGroups(user) + return RenderJSON(w, r, &GroupListResponse{Groups: groups}) } - groups := store.Access.GetAllGroups() - return renderJSON(w, r, &GroupListResponse{Groups: groups}) + groups := state.GetAllGroups() + return RenderJSON(w, r, &GroupListResponse{Groups: groups}) } // groupPostHandler adds a user to a group. @@ -264,13 +309,13 @@ func groupGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) // @Failure 403 {object} map[string]string "Forbidden" // @Failure 500 {object} map[string]string "Internal Server Error" // @Router /api/access/group [post] -func groupPostHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !d.user.Permissions.Admin { +func groupPostHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if !d.User.Permissions.Admin { return http.StatusForbidden, nil } group := r.URL.Query().Get("group") user := r.URL.Query().Get("user") - err := store.Access.AddUserToGroup(group, user) + err := state.AddUserToGroup(group, user) if err != nil { return http.StatusInternalServerError, err } @@ -289,13 +334,13 @@ func groupPostHandler(w http.ResponseWriter, r *http.Request, d *requestContext) // @Failure 403 {object} map[string]string "Forbidden" // @Failure 500 {object} map[string]string "Internal Server Error" // @Router /api/access/group [delete] -func groupDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !d.user.Permissions.Admin { +func groupDeleteHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if !d.User.Permissions.Admin { return http.StatusForbidden, nil } group := r.URL.Query().Get("group") user := r.URL.Query().Get("user") - err := store.Access.RemoveUserFromGroup(group, user) + err := state.RemoveUserFromGroup(group, user) if err != nil { return http.StatusInternalServerError, err } @@ -313,7 +358,7 @@ func groupDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestContex // @Failure 400 {object} map[string]string "Bad request - missing or invalid parameters" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/access [patch] -func accessPatchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func accessPatchHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { var body struct { Source string `json:"source"` OldPath string `json:"oldPath"` @@ -335,12 +380,24 @@ func accessPatchHandler(w http.ResponseWriter, r *http.Request, d *requestContex return http.StatusBadRequest, fmt.Errorf("source not found: %s", body.Source) } - // Update the access rule path - err := store.Access.UpdateRulePath(index.Path, body.OldPath, body.NewPath) + oldPath, status, err := parseAccessQueryPathOrBadRequest(body.OldPath) + if err != nil { + return status, err + } + newPath, status, err := parseAccessQueryPathOrBadRequest(body.NewPath) + if err != nil { + return status, err + } + + err = state.UpdateRulePath(index.Path, oldPath, newPath) if err != nil { logger.Errorf("failed to update rule path: %v", err) return http.StatusInternalServerError, fmt.Errorf("failed to update rule path: %w", err) } - return renderJSON(w, r, map[string]string{"message": "rule path updated"}) + activity.RecordAccessUpdate(r, toActor(d), body.Source, newPath.String(), []activitydb.FieldChange{ + {Field: "oldPath", From: oldPath.String(), To: newPath.String()}, + }) + + return RenderJSON(w, r, map[string]string{"message": "rule path updated"}) } diff --git a/backend/internal/web/access_test.go b/backend/internal/web/access_test.go new file mode 100644 index 0000000000..c739e458c7 --- /dev/null +++ b/backend/internal/web/access_test.go @@ -0,0 +1,203 @@ +package web + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + activityrec "github.com/gtsteffaniak/filebrowser/backend/internal/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/app" + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func setupAccessHTTPTest(t *testing.T) { + t.Helper() + dbPath := filepath.Join(t.TempDir(), "access-http-test.sqlite") + if _, err := state.Initialize(dbPath); err != nil { + t.Fatal(err) + } + app.MustWireServices(state.Default()) + t.Cleanup(func() { + state.Close() + }) + + settings.Config.Server.SourceMap = map[string]*settings.Source{ + "/downloads": { + Path: "/downloads", + Name: "Downloads", + }, + } + settings.Config.Server.NameToSource = map[string]*settings.Source{ + "Downloads": settings.Config.Server.SourceMap["/downloads"], + } + settings.InitializeUserResolvers() + + adminUser := &users.User{ + ID: 1, + FrontendUser: users.FrontendUser{ + Username: "admin", + Permissions: users.Permissions{Admin: true}, + }, + } + if err := state.CreateUser(adminUser, ""); err != nil { + t.Fatal(err) + } + adminUser.Permissions = users.Permissions{Admin: true} + if err := state.UpdateUser(adminUser, "", "permissions"); err != nil { + t.Fatal(err) + } + + indexing.SetTestIndex("Downloads", "/downloads") + t.Cleanup(func() { + indexing.ClearTestIndices() + }) +} + +func TestAccessPostHandler_RejectsNonExistentUser(t *testing.T) { + setupAccessHTTPTest(t) + + body, err := json.Marshal(map[string]any{ + "allow": false, + "ruleCategory": "user", + "value": "test", + }) + if err != nil { + t.Fatal(err) + } + + req := httptest.NewRequest(http.MethodPost, "/api/access?source=Downloads&path=%2F", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + + adminUser, err := state.GetUserByUsername("admin") + if err != nil { + t.Fatal(err) + } + + status, handlerErr := accessPostHandler(rec, req, &requestContext{User: &adminUser}) + if status != http.StatusBadRequest { + t.Fatalf("expected status 400, got %d (err=%v body=%s)", status, handlerErr, rec.Body.String()) + } + if handlerErr == nil || handlerErr.Error() != "user not found: test" { + t.Fatalf("expected user not found error, got: %v", handlerErr) + } +} + +func TestAccessPostHandler_RecordsActivityDetails(t *testing.T) { + setupAccessHTTPTest(t) + + adminUser, err := state.GetUserByUsername("admin") + if err != nil { + t.Fatal(err) + } + ctx := &requestContext{User: &adminUser} + + body, err := json.Marshal(map[string]any{ + "allow": false, + "ruleCategory": "user", + "value": "admin", + }) + if err != nil { + t.Fatal(err) + } + + req := httptest.NewRequest(http.MethodPost, "/api/access?source=Downloads&path=%2F", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.RemoteAddr = "127.0.0.1:1234" + rec := httptest.NewRecorder() + + status, handlerErr := accessPostHandler(rec, req, ctx) + if status != http.StatusOK || handlerErr != nil { + t.Fatalf("post handler failed: status=%d err=%v body=%s", status, handlerErr, rec.Body.String()) + } + + activityrec.FlushNow() + rows, total, err := state.ListActivity(activitydb.QueryFilter{ + EventTypes: []activitydb.EventType{activitydb.EventAccessCreate}, + Limit: 10, + }) + if err != nil { + t.Fatal(err) + } + if total != 1 || len(rows) != 1 { + t.Fatalf("expected 1 access create activity row, got total=%d len=%d", total, len(rows)) + } + if rows[0].Details.Changes == nil || len(rows[0].Details.Changes) != 3 { + t.Fatalf("expected 3 activity detail changes, got %#v", rows[0].Details.Changes) + } + assertActivityChange(t, rows[0].Details.Changes, "ruleType", "deny") + assertActivityChange(t, rows[0].Details.Changes, "ruleCategory", "user") + assertActivityChange(t, rows[0].Details.Changes, "value", "admin") +} + +func TestAccessDeleteHandler_RecordsActivityDetails(t *testing.T) { + setupAccessHTTPTest(t) + + adminUser, err := state.GetUserByUsername("admin") + if err != nil { + t.Fatal(err) + } + ctx := &requestContext{User: &adminUser} + + addBody, err := json.Marshal(map[string]any{ + "allow": false, + "ruleCategory": "user", + "value": "admin", + }) + if err != nil { + t.Fatal(err) + } + addReq := httptest.NewRequest(http.MethodPost, "/api/access?source=Downloads&path=%2F", bytes.NewReader(addBody)) + addReq.Header.Set("Content-Type", "application/json") + addReq.RemoteAddr = "127.0.0.1:1234" + addRec := httptest.NewRecorder() + if status, handlerErr := accessPostHandler(addRec, addReq, ctx); status != http.StatusOK || handlerErr != nil { + t.Fatalf("setup post failed: status=%d err=%v", status, handlerErr) + } + + delReq := httptest.NewRequest(http.MethodDelete, "/api/access?source=Downloads&path=%2F&ruleType=deny&ruleCategory=user&value=admin", nil) + delReq.RemoteAddr = "127.0.0.1:1234" + delRec := httptest.NewRecorder() + status, handlerErr := accessDeleteHandler(delRec, delReq, ctx) + if status != http.StatusOK || handlerErr != nil { + t.Fatalf("delete handler failed: status=%d err=%v body=%s", status, handlerErr, delRec.Body.String()) + } + + activityrec.FlushNow() + rows, total, err := state.ListActivity(activitydb.QueryFilter{ + EventTypes: []activitydb.EventType{activitydb.EventAccessDelete}, + Limit: 10, + }) + if err != nil { + t.Fatal(err) + } + if total != 1 || len(rows) != 1 { + t.Fatalf("expected 1 access delete activity row, got total=%d len=%d", total, len(rows)) + } + if rows[0].Details.Changes == nil { + t.Fatal("expected delete activity details changes") + } + assertActivityChange(t, rows[0].Details.Changes, "ruleType", "deny") + assertActivityChange(t, rows[0].Details.Changes, "ruleCategory", "user") + assertActivityChange(t, rows[0].Details.Changes, "value", "admin") +} + +func assertActivityChange(t *testing.T, changes []activitydb.FieldChange, field, wantTo string) { + t.Helper() + for _, change := range changes { + if change.Field == field { + if change.To != wantTo { + t.Fatalf("change %q: got to=%q want %q", field, change.To, wantTo) + } + return + } + } + t.Fatalf("missing change field %q in %#v", field, changes) +} diff --git a/backend/internal/web/activity.go b/backend/internal/web/activity.go new file mode 100644 index 0000000000..e24d4d3b5e --- /dev/null +++ b/backend/internal/web/activity.go @@ -0,0 +1,131 @@ +package web + +import ( + "encoding/csv" + "encoding/json" + "fmt" + "net/http" + + "github.com/gtsteffaniak/filebrowser/backend/internal/activity" + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" +) + +func toActor(d *Context) *activity.Actor { + if d == nil { + return nil + } + return &activity.Actor{User: d.User, Share: d.Share, Token: d.Token} +} + +// ListHandler returns paginated activity events (ungrouped). +func ListHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + filter, status, err := activity.ParseFilter(r, toActor(d)) + if err != nil { + return status, err + } + activity.ClampListPaging(&filter) + + items, total, err := state.ListActivity(filter) + if err != nil { + return http.StatusInternalServerError, err + } + activity.PrepareItemsForViewer(items, d.User) + totalPages := (total + filter.Limit - 1) / filter.Limit + if totalPages == 0 { + totalPages = 1 + } + + return RenderJSON(w, r, activitydb.ListResponse{ + Items: utils.NonNilSlice(items), + Total: total, + Page: filter.Page, + Limit: filter.Limit, + TotalPages: totalPages, + }) +} + +// GroupedHandler returns aggregated activity buckets for charts. +func GroupedHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + filter, status, err := activity.ParseFilter(r, toActor(d)) + if err != nil { + return status, err + } + if err = activity.ValidateChartParams(filter); err != nil { + return http.StatusBadRequest, err + } + if filter.Interval == "" && filter.GroupBy == "" { + filter.Interval = "hour" + } + if filter.SplitBy == "" { + filter.SplitBy = "eventType" + } + + buckets, err := state.ListActivityStats(filter) + if err != nil { + return http.StatusInternalServerError, err + } + return RenderJSON(w, r, activitydb.GroupedResponse{Buckets: utils.NonNilSlice(buckets)}) +} + +// ExportHandler streams activity rows as CSV. +func ExportHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + filter, status, err := activity.ParseFilter(r, toActor(d)) + if err != nil { + return status, err + } + optionalCols, err := activity.ParseExportRows(r.URL.Query().Get("rows")) + if err != nil { + return http.StatusBadRequest, err + } + filter.Page = 1 + filter.Limit = utils.Clamp(1000, 1, 500) + + w.Header().Set("Content-Type", "text/csv; charset=utf-8") + w.Header().Set("Content-Disposition", fmt.Sprintf( + `attachment; filename="activity-%d-%d.csv"`, filter.From, filter.To)) + + cw := csv.NewWriter(w) + includeDetails := d.User.Permissions.Admin + _ = cw.Write(activity.ExportHeader(includeDetails, optionalCols)) + + exported := 0 + for { + items, total, err := state.ListActivity(filter) + if err != nil { + return http.StatusInternalServerError, err + } + if len(items) == 0 { + break + } + activity.PrepareItemsForViewer(items, d.User) + for _, item := range items { + if exported >= activity.MaxExportRows { + _ = cw.Write([]string{"", "", "", "TRUNCATED"}) + cw.Flush() + return 0, nil + } + detailsJSON := "" + if includeDetails { + detailsJSON = string(mustJSON(item.Details)) + } + _ = cw.Write(activity.ExportRowValues(item, optionalCols, includeDetails, detailsJSON)) + exported++ + } + if filter.Page*filter.Limit >= total { + break + } + filter.Page++ + } + cw.Flush() + return 0, nil +} + +func mustJSON(v any) []byte { + b, err := json.Marshal(v) + if err != nil { + return []byte("{}") + } + return b +} diff --git a/backend/internal/web/analytics.go b/backend/internal/web/analytics.go new file mode 100644 index 0000000000..6005e0ac77 --- /dev/null +++ b/backend/internal/web/analytics.go @@ -0,0 +1,71 @@ +package web + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/gtsteffaniak/filebrowser/backend/internal/analytics" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/go-logger/logger" +) + +type analyticsStatusResponse struct { + Enabled bool `json:"enabled"` + Ready bool `json:"ready"` + PublishSupported bool `json:"publishSupported"` +} + +type analyticsUpdateRequest struct { + Enabled bool `json:"enabled"` +} + +func settingsAnalyticsGetHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + return RenderJSON(w, r, analyticsStatusResponse{ + Enabled: state.IsAnalyticsEnabled(), + Ready: analytics.Ready(), + PublishSupported: analytics.PublishSupported(), + }) +} + +func settingsAnalyticsUpdateHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + var body analyticsUpdateRequest + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + return http.StatusBadRequest, fmt.Errorf("failed to decode body: %w", err) + } + defer r.Body.Close() + + if body.Enabled && !analytics.PublishSupported() { + return http.StatusForbidden, fmt.Errorf("deployment analytics publishing is not available in this build") + } + + if err := state.SetAnalyticsEnabled(body.Enabled); err != nil { + logger.Errorf("failed to update analytics setting: %v", err) + return http.StatusInternalServerError, fmt.Errorf("failed to update analytics setting") + } + + if !body.Enabled { + analytics.NotifyAnalyticsDisabled() + analytics.InvalidateCache() + } else { + analytics.NotifyAnalyticsEnabled() + } + + return RenderJSON(w, r, analyticsStatusResponse{ + Enabled: state.IsAnalyticsEnabled(), + Ready: analytics.Ready(), + PublishSupported: analytics.PublishSupported(), + }) +} + +func settingsAnalyticsPreviewHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + preview, err := analytics.PreviewSnapshot() + if err != nil { + return http.StatusServiceUnavailable, fmt.Errorf("failed to build analytics preview: %w", err) + } + + if !json.Valid(preview) { + return http.StatusInternalServerError, fmt.Errorf("failed to format analytics preview") + } + return RenderJSON(w, r, json.RawMessage(preview)) +} diff --git a/backend/http/api.go b/backend/internal/web/api.go similarity index 59% rename from backend/http/api.go rename to backend/internal/web/api.go index 85361804e8..b4b72b835a 100644 --- a/backend/http/api.go +++ b/backend/internal/web/api.go @@ -1,4 +1,4 @@ -package http +package web import ( "fmt" @@ -8,8 +8,11 @@ import ( "strings" "time" - "github.com/gtsteffaniak/filebrowser/backend/auth" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/auth" + "github.com/gtsteffaniak/filebrowser/backend/internal/activity" + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" "github.com/gtsteffaniak/go-logger/logger" ) @@ -21,20 +24,20 @@ import ( // @Produce json // @Param name query string true "Name of the API token" // @Param days query string true "Duration of the API token in days" -// @Param permissions query string true "Permissions for the API token (comma-separated)" +// @Param permissions query string false "Global permissions (comma-separated: admin, api, share, realtime). Send \"minimal\" or omit with minimal=true for a WebDAV-compatible token." +// @Param minimal query bool false "When true, create a minimal token (standard JWT claims only). When false, create a customized token using permissions (may be empty)." // @Success 200 {object} HttpResponse "Token created successfully, response contains json object with token" // @Failure 400 {object} map[string]string "Bad request" // @Failure 404 {object} map[string]string "Not found" // @Failure 409 {object} map[string]string "Conflict" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/auth/token [post] -func createApiTokenHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func createApiTokenHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { name := r.URL.Query().Get("name") durationStr := r.URL.Query().Get("days") - permissionsStr := r.URL.Query().Get("permissions") - minimal := permissionsStr == "" + minimal, permissionsStr := apiTokenCreationMode(r) - if !d.user.Permissions.Api { + if !d.User.Permissions.Api { return http.StatusForbidden, fmt.Errorf("user does not have permission to create api tokens") } @@ -49,21 +52,13 @@ func createApiTokenHandler(w http.ResponseWriter, r *http.Request, d *requestCon // For minimal tokens (minimal=true), only standard JWT claims are included. var permissions users.Permissions if !minimal { - // Parse permissions from the query parameter permissions = users.Permissions{ - Api: strings.Contains(permissionsStr, "api") && d.user.Permissions.Api, - Admin: strings.Contains(permissionsStr, "admin") && d.user.Permissions.Admin, - Modify: strings.Contains(permissionsStr, "modify") && d.user.Permissions.Modify, - Delete: strings.Contains(permissionsStr, "delete") && d.user.Permissions.Delete, - Create: strings.Contains(permissionsStr, "create") && d.user.Permissions.Create, - Share: strings.Contains(permissionsStr, "share") && d.user.Permissions.Share, - Realtime: strings.Contains(permissionsStr, "realtime") && d.user.Permissions.Realtime, - Download: strings.Contains(permissionsStr, "download") && d.user.Permissions.Download, - } - if !permissions.Api && !permissions.Admin && !permissions.Modify && !permissions.Delete && - !permissions.Create && !permissions.Share && !permissions.Realtime && !permissions.Download { - minimal = true + Api: strings.Contains(permissionsStr, "api") && d.User.Permissions.Api, + Admin: strings.Contains(permissionsStr, "admin") && d.User.Permissions.Admin, + Share: strings.Contains(permissionsStr, "share") && d.User.Permissions.Share, + Realtime: strings.Contains(permissionsStr, "realtime") && d.User.Permissions.Realtime, } + permissions = users.SanitizeTokenPermissions(permissions) } // Convert the duration string to an int64 @@ -74,7 +69,7 @@ func createApiTokenHandler(w http.ResponseWriter, r *http.Request, d *requestCon // Here we assume the duration is in seconds; convert to time.Duration duration := time.Duration(durationInt) * time.Hour * 24 - tokenString, authToken, err := auth.MakeSignedTokenAPI(d.user, name, duration, permissions, minimal) + tokenString, authToken, err := auth.MakeSignedTokenAPI(d.User, name, duration, permissions, minimal) if err != nil { if strings.Contains(err.Error(), "key already exists with same name") { return http.StatusConflict, err @@ -83,13 +78,15 @@ func createApiTokenHandler(w http.ResponseWriter, r *http.Request, d *requestCon } // Store API token metadata in user's Tokens map - err = store.Users.AddApiToken(d.user.ID, name, tokenString, authToken) + authToken.Name = name + authToken.Token = tokenString + err = state.AddUserToken(d.User.Username, authToken) if err != nil { return http.StatusInternalServerError, err } - // Store token hash → user ID mapping in access storage for fast lookups - err = store.Access.AddApiToken(tokenString, d.user.ID) + // Store token hash → user id mapping in access storage for fast lookups + err = state.AddApiToken(tokenString, d.User.ID) if err != nil { return http.StatusInternalServerError, err } @@ -98,7 +95,35 @@ func createApiTokenHandler(w http.ResponseWriter, r *http.Request, d *requestCon Message: "here is your token!", Token: tokenString, } - return renderJSON(w, r, response) + activity.RecordTokenMutation(r, toActor(d), activitydb.EventTokenCreate, name) + return RenderJSON(w, r, response) +} + +const apiTokenPermissionsMinimal = "minimal" + +// apiTokenCreationMode decides whether to mint a minimal JWT or a customized token from query params. +// minimal=true or permissions=minimal → minimal token (WebDAV-compatible). +// minimal=false → customized token; permissions may be empty (all global caps false in the claim). +// Legacy clients omitting both minimal and permissions still receive a minimal token. +func apiTokenCreationMode(r *http.Request) (minimal bool, permissionsStr string) { + permissionsStr = r.URL.Query().Get("permissions") + if strings.EqualFold(permissionsStr, apiTokenPermissionsMinimal) { + return true, "" + } + + if minimalValues, ok := r.URL.Query()["minimal"]; ok && len(minimalValues) > 0 { + switch strings.ToLower(strings.TrimSpace(minimalValues[0])) { + case "true", "1": + return true, permissionsStr + case "false", "0": + return false, permissionsStr + } + } + + if permissionsStr == "" { + return true, "" + } + return false, permissionsStr } // deleteApiTokenHandler deletes an API token for the user. @@ -112,35 +137,36 @@ func createApiTokenHandler(w http.ResponseWriter, r *http.Request, d *requestCon // @Failure 404 {object} map[string]string "Not found" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/auth/token [delete] -func deleteApiTokenHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func deleteApiTokenHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { name := r.URL.Query().Get("name") - if !d.user.Permissions.Api { + if !d.User.Permissions.Api { return http.StatusForbidden, fmt.Errorf("user does not have permission to delete api tokens") } - tokenInfo, ok := d.user.Tokens[name] + tokenInfo, ok := d.User.Tokens[name] if !ok { return http.StatusNotFound, fmt.Errorf("api token not found") } // Perform the user update - err := store.Users.DeleteApiToken(d.user.ID, name) + err := state.DeleteUserToken(d.User.Username, name) if err != nil { return http.StatusNotFound, err } // Revoke the token (adds to RevokedTokens set) - if err := auth.RevokeApiToken(store.Access, tokenInfo.Token); err != nil { + if err := state.RevokeToken( tokenInfo.Token); err != nil { logger.Errorf("Failed to revoke token: %v", err) } - if err := store.Access.RemoveApiToken(tokenInfo.Token); err != nil { + if err := state.RemoveApiToken(tokenInfo.Token); err != nil { logger.Errorf("Failed to remove api token: %v", err) } response := HttpResponse{ Message: "successfully deleted api token from user", } - return renderJSON(w, r, response) + activity.RecordTokenMutation(r, toActor(d), activitydb.EventTokenDelete, name) + return RenderJSON(w, r, response) } type AuthTokenFrontend struct { @@ -148,9 +174,26 @@ type AuthTokenFrontend struct { Name string `json:"name"` IssuedAt int64 `json:"issuedAt"` ExpiresAt int64 `json:"expiresAt"` + Minimal bool `json:"minimal"` Permissions users.Permissions `json:"Permissions,omitempty"` } +func authTokenForFrontend(name string, token users.AuthToken, owner *users.User) AuthTokenFrontend { + minimal := users.IsMinimalApiToken(token) + perms := users.SanitizeTokenPermissions(token.Permissions) + if minimal && owner != nil { + perms = users.SanitizeTokenPermissions(owner.Permissions) + } + return AuthTokenFrontend{ + Token: token.Token, + Name: name, + IssuedAt: authTokenIssuedUnix(token), + ExpiresAt: authTokenExpiresUnix(token), + Minimal: minimal, + Permissions: perms, + } +} + // authTokenIssuedUnix returns iat from JWT claims when set, otherwise the persisted int64 (e.g. loaded from DB). func authTokenIssuedUnix(t users.AuthToken) int64 { if t.RegisteredClaims.IssuedAt != nil { @@ -177,29 +220,26 @@ func authTokenExpiresUnix(t users.AuthToken) int64 { // @Failure 404 {object} map[string]string "Not found" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/auth/token/list [get] -func listApiTokensHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !d.user.Permissions.Api { +func listApiTokensHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if !d.User.Permissions.Api { return http.StatusForbidden, fmt.Errorf("user does not have permission to list api tokens") } - if len(d.user.Tokens) == 0 { + if len(d.User.Tokens) == 0 { return http.StatusNotFound, fmt.Errorf("no api tokens found") } - AuthTokensFrontend := make([]AuthTokenFrontend, 0, len(d.user.Tokens)) - for name, token := range d.user.Tokens { - AuthTokensFrontend = append(AuthTokensFrontend, AuthTokenFrontend{ - Token: token.Token, - Name: name, - IssuedAt: authTokenIssuedUnix(token), - ExpiresAt: authTokenExpiresUnix(token), - Permissions: token.Permissions, - }) + AuthTokensFrontend := make([]AuthTokenFrontend, 0) + users.EachNamedToken(d.User.Tokens, func(name string, token users.AuthToken) { + AuthTokensFrontend = append(AuthTokensFrontend, authTokenForFrontend(name, token, d.User)) + }) + if len(AuthTokensFrontend) == 0 { + return http.StatusNotFound, fmt.Errorf("no api tokens found") } - + sort.Slice(AuthTokensFrontend, func(i, j int) bool { return AuthTokensFrontend[i].Name < AuthTokensFrontend[j].Name }) - return renderJSON(w, r, AuthTokensFrontend) + return RenderJSON(w, r, AuthTokensFrontend) } // getApiTokenHandler gets a specific API token. @@ -213,21 +253,15 @@ func listApiTokensHandler(w http.ResponseWriter, r *http.Request, d *requestCont // @Failure 404 {object} map[string]string "Not found" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/auth/token [get] -func getApiTokenHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func getApiTokenHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { name := r.URL.Query().Get("name") - if !d.user.Permissions.Api { + if !d.User.Permissions.Api { return http.StatusForbidden, fmt.Errorf("user does not have permission to list api tokens") } - tokenInfo, ok := d.user.Tokens[name] + tokenInfo, ok := d.User.Tokens[name] if !ok { return http.StatusNotFound, fmt.Errorf("api token not found") } - AuthTokenFrontendResponse := AuthTokenFrontend{ - Token: tokenInfo.Token, - Name: name, - IssuedAt: authTokenIssuedUnix(tokenInfo), - ExpiresAt: authTokenExpiresUnix(tokenInfo), - Permissions: tokenInfo.Permissions, - } - return renderJSON(w, r, AuthTokenFrontendResponse) + AuthTokenFrontendResponse := authTokenForFrontend(name, tokenInfo, d.User) + return RenderJSON(w, r, AuthTokenFrontendResponse) } diff --git a/backend/internal/web/api_test.go b/backend/internal/web/api_test.go new file mode 100644 index 0000000000..c4661945ad --- /dev/null +++ b/backend/internal/web/api_test.go @@ -0,0 +1,208 @@ +package web + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "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" +) + +const webdavPasswordLimit = 256 + +func TestApiTokenCreationMode(t *testing.T) { + t.Run("permissions minimal keyword", func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/auth/token?permissions=minimal", http.NoBody) + minimal, perms := apiTokenCreationMode(req) + if !minimal || perms != "" { + t.Fatalf("got minimal=%v perms=%q", minimal, perms) + } + }) + t.Run("minimal true boolean", func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/auth/token?minimal=true", http.NoBody) + minimal, _ := apiTokenCreationMode(req) + if !minimal { + t.Fatal("expected minimal") + } + }) + t.Run("minimal false with empty permissions", func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/auth/token?minimal=false", http.NoBody) + minimal, perms := apiTokenCreationMode(req) + if minimal || perms != "" { + t.Fatalf("got minimal=%v perms=%q", minimal, perms) + } + }) + t.Run("legacy omit both", func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/auth/token", http.NoBody) + minimal, _ := apiTokenCreationMode(req) + if !minimal { + t.Fatal("expected legacy default minimal") + } + }) + t.Run("legacy permissions list", func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/auth/token?permissions=api,admin", http.NoBody) + minimal, perms := apiTokenCreationMode(req) + if minimal || perms != "api,admin" { + t.Fatalf("got minimal=%v perms=%q", minimal, perms) + } + }) +} + +func TestCreateApiTokenUncustomizedUnder256(t *testing.T) { + setupTestEnv(t) + setTestAuthKey(t) + + user := createApiTokenTestUser(t, "tokenuser", users.Permissions{Api: true}) + rec := invokeCreateApiToken(t, user, "/auth/token?name=webdav&days=365&permissions=minimal") + if rec.Code != http.StatusOK { + t.Fatalf("expected 200, got %d body=%s", rec.Code, rec.Body.String()) + } + + token := decodeCreatedToken(t, rec.Body.Bytes()) + if len(token) >= webdavPasswordLimit { + t.Fatalf("uncustomized token length %d must stay under %d", len(token), webdavPasswordLimit) + } + assertHandlerMinimalJWTClaims(t, token) +} + +func TestCreateApiTokenLegacyOmitPermissionsStillMinimal(t *testing.T) { + setupTestEnv(t) + setTestAuthKey(t) + + user := createApiTokenTestUser(t, "tokenuser-legacy", users.Permissions{Api: true}) + rec := invokeCreateApiToken(t, user, "/auth/token?name=webdav&days=365") + if rec.Code != http.StatusOK { + t.Fatalf("expected 200, got %d body=%s", rec.Code, rec.Body.String()) + } + assertHandlerMinimalJWTClaims(t, decodeCreatedToken(t, rec.Body.Bytes())) +} + +func TestCreateApiTokenCustomizedWithNoEffectiveCapsKeepsPermissionsClaim(t *testing.T) { + setupTestEnv(t) + setTestAuthKey(t) + + // User can create API tokens but lacks admin; explicit customized token keeps Permissions in JWT. + user := createApiTokenTestUser(t, "tokenuser2", users.Permissions{Api: true}) + rec := invokeCreateApiToken(t, user, "/auth/token?name=custom&days=365&minimal=false&permissions=admin") + if rec.Code != http.StatusOK { + t.Fatalf("expected 200, got %d body=%s", rec.Code, rec.Body.String()) + } + + token := decodeCreatedToken(t, rec.Body.Bytes()) + claims := jwt.MapClaims{} + if _, _, err := jwt.NewParser().ParseUnverified(token, claims); err != nil { + t.Fatalf("parse token: %v", err) + } + perms, ok := claims["Permissions"].(map[string]interface{}) + if !ok { + t.Fatalf("customized token should include Permissions claim, got %v", claims) + } + if perms["admin"] != false { + t.Fatalf("expected admin false in customized token, got %v", perms["admin"]) + } +} + +func TestCreateApiTokenCustomizedWithEffectiveCaps(t *testing.T) { + setupTestEnv(t) + setTestAuthKey(t) + + user := createApiTokenTestUser(t, "tokenuser3", users.Permissions{Api: true, Admin: true}) + rec := invokeCreateApiToken(t, user, "/auth/token?name=custom&days=30&permissions=admin,api") + if rec.Code != http.StatusOK { + t.Fatalf("expected 200, got %d body=%s", rec.Code, rec.Body.String()) + } + + token := decodeCreatedToken(t, rec.Body.Bytes()) + claims := jwt.MapClaims{} + if _, _, err := jwt.NewParser().ParseUnverified(token, claims); err != nil { + t.Fatalf("parse token: %v", err) + } + perms, ok := claims["Permissions"].(map[string]interface{}) + if !ok { + t.Fatalf("expected Permissions claim in customized token, got %v", claims) + } + if perms["admin"] != true || perms["api"] != true { + t.Fatalf("expected admin and api true, got %v", perms) + } +} + +func setTestAuthKey(t *testing.T) { + t.Helper() + orig := settings.Config.Auth.Key + settings.Config.Auth.Key = "test-signing-key-for-length-check" + t.Cleanup(func() { settings.Config.Auth.Key = orig }) +} + +func createApiTokenTestUser(t *testing.T, username string, perms users.Permissions) *users.User { + t.Helper() + user := &users.User{ + FrontendUser: users.FrontendUser{ + Username: username, + Permissions: perms, + }, + } + if err := state.CreateUser(user, "password"); err != nil { + t.Fatalf("create user: %v", err) + } + got, err := state.GetUserByUsername(username) + if err != nil { + t.Fatalf("get user: %v", err) + } + got.Permissions = perms + if err = state.UpdateUser(&got, "", "permissions"); err != nil { + t.Fatalf("update permissions: %v", err) + } + got, err = state.GetUserByUsername(username) + if err != nil { + t.Fatalf("reload user: %v", err) + } + return &got +} + +func invokeCreateApiToken(t *testing.T, user *users.User, path string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPost, path, http.NoBody) + rec := httptest.NewRecorder() + ctx := &Context{User: user, Ctx: req.Context()} + status, err := createApiTokenHandler(rec, req, ctx) + if err != nil { + t.Fatalf("handler error: %v", err) + } + if status != http.StatusOK { + t.Fatalf("expected status %d, got %d body=%s", http.StatusOK, status, rec.Body.String()) + } + return rec +} + +func decodeCreatedToken(t *testing.T, body []byte) string { + t.Helper() + var resp HttpResponse + if err := json.Unmarshal(body, &resp); err != nil { + t.Fatalf("decode response: %v", err) + } + if resp.Token == "" { + t.Fatalf("empty token in response: %s", body) + } + return resp.Token +} + +func assertHandlerMinimalJWTClaims(t *testing.T, tokenString string) { + t.Helper() + claims := jwt.MapClaims{} + if _, _, err := jwt.NewParser().ParseUnverified(tokenString, claims); err != nil { + t.Fatalf("parse token: %v", err) + } + for _, key := range []string{"Permissions", "permissions", "belongsTo", "username", "name"} { + if _, ok := claims[key]; ok { + t.Fatalf("minimal token must not include %q claim; got %v", key, claims) + } + } + if claims["iss"] != auth.FB_ISSUER { + t.Fatalf("expected iss %q, got %v", auth.FB_ISSUER, claims["iss"]) + } +} diff --git a/backend/http/archive.go b/backend/internal/web/archive.go similarity index 88% rename from backend/http/archive.go rename to backend/internal/web/archive.go index 244f3fc3db..037673a2d4 100644 --- a/backend/http/archive.go +++ b/backend/internal/web/archive.go @@ -1,4 +1,4 @@ -package http +package web import ( "archive/tar" @@ -19,14 +19,18 @@ import ( "sync" "time" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/indexing" + "github.com/gtsteffaniak/filebrowser/backend/internal/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" "github.com/gtsteffaniak/go-cache/cache" "github.com/gtsteffaniak/go-logger/logger" "golang.org/x/time/rate" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + ) // archiveMultiRequestIdle is how long without another Range/HEAD on the same archiveToken before @@ -151,17 +155,17 @@ func archiveAttachmentStem(fileList []string, realPath string) string { // serveArchiveWithServeContent sends a built archive using ServeContent (Range-capable). // For share links with MaxBandwidth > 0, outbound data is throttled via newThrottledReadSeeker (same limit as single-file download). -func serveArchiveWithServeContent(w http.ResponseWriter, r *http.Request, d *requestContext, rs io.ReadSeeker, fi os.FileInfo, originalFileName string) (int, error) { - setContentDisposition(w, r, originalFileName) +func serveArchiveWithServeContent(w http.ResponseWriter, r *http.Request, d *Context, rs io.ReadSeeker, fi os.FileInfo, originalFileName string) (int, error) { + SetContentDisposition(w, r, originalFileName, false) w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Cache-Control", "private") w.Header().Set("X-Content-Type-Options", "nosniff") reader := rs - if d.share != nil && d.share.MaxBandwidth > 0 { - limit := rate.Limit(d.share.MaxBandwidth * 1024) - burst := d.share.MaxBandwidth * 1024 - reader = newThrottledReadSeeker(rs, limit, burst, r.Context()) + if d.Share.MaxBandwidth > 0 { + limit := rate.Limit(d.Share.MaxBandwidth * 1024) + burst := d.Share.MaxBandwidth * 1024 + reader = NewThrottledReadSeeker(rs, limit, burst, r.Context()) } http.ServeContent(w, r, originalFileName, fi.ModTime(), reader) return 0, nil @@ -192,13 +196,10 @@ func serveArchiveWithServeContent(w http.ResponseWriter, r *http.Request, d *req // @Failure 413 {object} map[string]string "Request Entity Too Large (archive size exceeds maxArchiveSizeGB limit)" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/resources/archive [post] -func archiveCreateHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if d.share != nil { +func archiveCreateHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if d.Share.Hash != "" { return http.StatusForbidden, fmt.Errorf("archive create not allowed for shares") } - if !d.user.Permissions.Create { - return http.StatusForbidden, fmt.Errorf("user is not allowed to create resources") - } var req archiveCreateRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { @@ -208,7 +209,7 @@ func archiveCreateHandler(w http.ResponseWriter, r *http.Request, d *requestCont return http.StatusBadRequest, fmt.Errorf("fromSource, paths, and destination are required") } - destClean, err := utils.SanitizeUserPath(req.Destination) + destClean, err := utils.SanitizePath(req.Destination) if err != nil { return http.StatusBadRequest, fmt.Errorf("invalid destination path: %v", err) } @@ -216,7 +217,7 @@ func archiveCreateHandler(w http.ResponseWriter, r *http.Request, d *requestCont pathsClean := make([]string, 0, len(req.Paths)) for _, p := range req.Paths { var clean string - clean, err = utils.SanitizeUserPath(p) + clean, err = utils.SanitizePath(p) if err != nil { return http.StatusBadRequest, fmt.Errorf("invalid path %q: %v", p, err) } @@ -228,12 +229,29 @@ func archiveCreateHandler(w http.ResponseWriter, r *http.Request, d *requestCont if destSource == "" { destSource = req.FromSource } + destPerms, err := effectiveFilePerms(d, destSource) + if err != nil { + return http.StatusForbidden, err + } + if !destPerms.Create { + return http.StatusForbidden, fmt.Errorf("user is not allowed to create resources in destination source") + } + fromPerms, err := effectiveFilePerms(d, req.FromSource) + if err != nil { + return http.StatusForbidden, err + } + if !fromPerms.Download { + return http.StatusForbidden, fmt.Errorf("user is not allowed to download source files") + } + if req.DeleteAfter && !fromPerms.Delete { + return http.StatusForbidden, fmt.Errorf("user is not allowed to delete source files") + } idx := indexing.GetIndex(req.FromSource) if idx == nil { return http.StatusNotFound, fmt.Errorf("source %s not found", req.FromSource) } - userScope, err := d.user.GetScopeForSourceName(req.FromSource) + userScope, err := d.User.GetScopeForSourceName(req.FromSource) if err != nil { return http.StatusForbidden, err } @@ -243,16 +261,16 @@ func archiveCreateHandler(w http.ResponseWriter, r *http.Request, d *requestCont if idxTo == nil { return http.StatusNotFound, fmt.Errorf("source %s not found", destSource) } - userScopeTo, err := d.user.GetScopeForSourceName(destSource) + userScopeTo, err := d.User.GetScopeForSourceName(destSource) if err != nil { return http.StatusForbidden, err } fullDestFile := utils.JoinPathAsUnix(userScopeTo, req.Destination) - if store.Access != nil && !store.Access.Permitted(idxTo.Path, fullDestFile, d.user.Username) { + if !state.AccessPermitted(idxTo.Path, utils.IndexPathFromNormalized(fullDestFile, true), d.User.Username) { return http.StatusForbidden, fmt.Errorf("access denied to destination %s", req.Destination) } fullDestParent := utils.GetParentDirectoryPath(fullDestFile) - if store.Access != nil && fullDestParent != fullDestFile && !store.Access.Permitted(idxTo.Path, fullDestParent, d.user.Username) { + if fullDestParent != fullDestFile && !state.AccessPermitted(idxTo.Path, utils.IndexPathFromNormalized(fullDestParent, true), d.User.Username) { return http.StatusForbidden, fmt.Errorf("access denied to destination parent of %s", req.Destination) } parentReal, _, err := idxTo.GetRealPath(fullDestParent) @@ -293,7 +311,7 @@ func archiveCreateHandler(w http.ResponseWriter, r *http.Request, d *requestCont itemPaths := make([]string, 0, len(req.Paths)) for _, it := range req.Paths { full := utils.JoinPathAsUnix(userScope, it) - if store.Access != nil && !store.Access.Permitted(idx.Path, full, d.user.Username) { + if !state.AccessPermitted(idx.Path, utils.IndexPathFromNormalized(full, true), d.User.Username) { continue // silently skip } itemPaths = append(itemPaths, full) @@ -303,15 +321,15 @@ func archiveCreateHandler(w http.ResponseWriter, r *http.Request, d *requestCont } // Check archive size limit if configured - if config.Server.MaxArchiveSizeGB > 0 { + if settings.Config.Server.MaxArchiveSizeGB > 0 { var estimatedSize int64 estimatedSize, err = computeArchiveSize(req.FromSource, itemPaths, d) if err != nil { return http.StatusInternalServerError, fmt.Errorf("failed to compute archive size: %v", err) } - maxSizeBytes := config.Server.MaxArchiveSizeGB * 1024 * 1024 * 1024 + maxSizeBytes := settings.Config.Server.MaxArchiveSizeGB * 1024 * 1024 * 1024 if estimatedSize > maxSizeBytes { - return http.StatusRequestEntityTooLarge, fmt.Errorf("archive size would exceed the maximum allowed size (maxArchiveSize: %d GB)", config.Server.MaxArchiveSizeGB) + return http.StatusRequestEntityTooLarge, fmt.Errorf("archive size would exceed the maximum allowed size (maxArchiveSize: %d GB)", settings.Config.Server.MaxArchiveSizeGB) } } @@ -331,7 +349,7 @@ func archiveCreateHandler(w http.ResponseWriter, r *http.Request, d *requestCont return http.StatusInternalServerError, createErr } - if req.DeleteAfter && d.user.Permissions.Delete { + if req.DeleteAfter { type itemToDelete struct { realPath string isDir bool @@ -358,7 +376,8 @@ func archiveCreateHandler(w http.ResponseWriter, r *http.Request, d *requestCont } } - return renderJSON(w, r, map[string]string{"path": req.Destination}, http.StatusOK) + activity.RecordArchive(r, toActor(d), activitydb.EventArchive, req.FromSource, req.Destination, req.Paths) + return RenderJSON(w, r, map[string]string{"path": req.Destination}, http.StatusOK) } // unarchiveHandler extracts an archive on the server. POST /resources/unarchive — server-side only. @@ -383,13 +402,10 @@ func archiveCreateHandler(w http.ResponseWriter, r *http.Request, d *requestCont // @Failure 413 {object} map[string]string "Request Entity Too Large (archive size exceeds maxArchiveSizeGB limit)" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/resources/unarchive [post] -func unarchiveHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if d.share != nil { +func unarchiveHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if d.Share.Hash != "" { return http.StatusForbidden, fmt.Errorf("unarchive not allowed for shares") } - if !d.user.Permissions.Create { - return http.StatusForbidden, fmt.Errorf("user is not allowed to create resources") - } var req unarchiveRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { @@ -401,12 +417,29 @@ func unarchiveHandler(w http.ResponseWriter, r *http.Request, d *requestContext) if req.ToSource == "" { req.ToSource = req.FromSource } + destPerms, err := effectiveFilePerms(d, req.ToSource) + if err != nil { + return http.StatusForbidden, err + } + if !destPerms.Create { + return http.StatusForbidden, fmt.Errorf("user is not allowed to create resources in destination source") + } + fromPerms, err := effectiveFilePerms(d, req.FromSource) + if err != nil { + return http.StatusForbidden, err + } + if !fromPerms.Download { + return http.StatusForbidden, fmt.Errorf("user is not allowed to download archive source") + } + if req.DeleteAfter && !fromPerms.Delete { + return http.StatusForbidden, fmt.Errorf("user is not allowed to delete archive source") + } - pathClean, err := utils.SanitizeUserPath(req.Path) + pathClean, err := utils.SanitizePath(req.Path) if err != nil { return http.StatusBadRequest, err } - destClean, err := utils.SanitizeUserPath(req.Destination) + destClean, err := utils.SanitizePath(req.Destination) if err != nil { return http.StatusBadRequest, fmt.Errorf("invalid destination: %v", err) } @@ -417,13 +450,13 @@ func unarchiveHandler(w http.ResponseWriter, r *http.Request, d *requestContext) if idxFrom == nil { return http.StatusNotFound, fmt.Errorf("source %s not found", req.FromSource) } - userScopeFrom, err := d.user.GetScopeForSourceName(req.FromSource) + userScopeFrom, err := d.User.GetScopeForSourceName(req.FromSource) if err != nil { return http.StatusForbidden, err } fullArchivePath := utils.JoinPathAsUnix(userScopeFrom, req.Path) - if store.Access != nil && !store.Access.Permitted(idxFrom.Path, fullArchivePath, d.user.Username) { + if !state.AccessPermitted(idxFrom.Path, utils.IndexPathFromNormalized(fullArchivePath, true), d.User.Username) { return http.StatusForbidden, fmt.Errorf("access denied to archive %s", req.Path) } archiveReal, _, err := idxFrom.GetRealPath(fullArchivePath) @@ -435,12 +468,12 @@ func unarchiveHandler(w http.ResponseWriter, r *http.Request, d *requestContext) if idxTo == nil { return http.StatusNotFound, fmt.Errorf("source %s not found", req.ToSource) } - userScopeTo, err := d.user.GetScopeForSourceName(req.ToSource) + userScopeTo, err := d.User.GetScopeForSourceName(req.ToSource) if err != nil { return http.StatusForbidden, err } fullDestPath := utils.JoinPathAsUnix(userScopeTo, req.Destination) - if store.Access != nil && !store.Access.Permitted(idxTo.Path, fullDestPath, d.user.Username) { + if !state.AccessPermitted(idxTo.Path, utils.IndexPathFromNormalized(fullDestPath, true), d.User.Username) { return http.StatusForbidden, fmt.Errorf("access denied to destination %s", req.Destination) } destReal, _, err := idxTo.GetRealPath(fullDestPath) @@ -467,10 +500,10 @@ func unarchiveHandler(w http.ResponseWriter, r *http.Request, d *requestContext) } // Check archive size limit if configured - if config.Server.MaxArchiveSizeGB > 0 { - maxSizeBytes := config.Server.MaxArchiveSizeGB * 1024 * 1024 * 1024 + if settings.Config.Server.MaxArchiveSizeGB > 0 { + maxSizeBytes := settings.Config.Server.MaxArchiveSizeGB * 1024 * 1024 * 1024 if info.Size() > maxSizeBytes { - return http.StatusRequestEntityTooLarge, fmt.Errorf("archive size would exceed the maximum allowed size (maxArchiveSize: %d GB)", config.Server.MaxArchiveSizeGB) + return http.StatusRequestEntityTooLarge, fmt.Errorf("archive size would exceed the maximum allowed size (maxArchiveSize: %d GB)", settings.Config.Server.MaxArchiveSizeGB) } } @@ -493,19 +526,20 @@ func unarchiveHandler(w http.ResponseWriter, r *http.Request, d *requestContext) } } - return renderJSON(w, r, map[string]string{"path": req.Destination, "source": req.ToSource}, http.StatusOK) + activity.RecordArchive(r, toActor(d), activitydb.EventUnarchive, req.FromSource, req.Destination, []string{req.Path}) + return RenderJSON(w, r, map[string]string{"path": req.Destination, "source": req.ToSource}, http.StatusOK) } // addFile adds a file or directory to a tar or zip archive, respecting access rules. -// For shares, path is already resolved; for users, access is checked via store.Access. -func addFile(source string, path string, d *requestContext, tarWriter *tar.Writer, zipWriter *zip.Writer, flatten bool) error { +// For shares, path is already resolved; for users, access is checked via state.AccessPermitted. +func addFile(source string, path string, d *Context, tarWriter *tar.Writer, zipWriter *zip.Writer, flatten bool) error { idx := indexing.GetIndex(source) if idx == nil { return fmt.Errorf("source %s is not available", source) } // Check access control directly for each file and silently skip if access is denied - if !store.Access.Permitted(idx.Path, path, d.user.Username) { + if !state.AccessPermitted(idx.Path, utils.IndexPathFromNormalized(path, true), d.User.Username) { return nil // Silently skip this file/folder } @@ -540,10 +574,11 @@ func addFile(source string, path string, d *requestContext, tarWriter *tar.Write } // Check access control for each file/folder during walk - if d.share == nil { + if d.Share.Hash == "" { indexRelPath := utils.JoinPathAsUnix(path, relPath) indexRelPath = filepath.ToSlash(indexRelPath) - if !store.Access.Permitted(idx.Path, indexRelPath, d.user.Username) { + indexPath := utils.IndexPathFromNormalized(indexRelPath, true) + if !state.AccessPermitted(idx.Path, indexPath, d.User.Username) { if fileInfo.IsDir() { return filepath.SkipDir } @@ -636,7 +671,7 @@ func addSingleFile(realPath, archivePath string, zipWriter *zip.Writer, tarWrite } // createZip writes a ZIP archive into w containing the given paths; access rules apply. -func createZip(d *requestContext, source string, w io.Writer, filenames ...string) error { +func createZip(d *Context, source string, w io.Writer, filenames ...string) error { zipWriter := zip.NewWriter(w) for _, filepath := range filenames { @@ -654,7 +689,7 @@ func createZip(d *requestContext, source string, w io.Writer, filenames ...strin } // createTarGz writes a tar.gz archive into w containing the given paths; access rules apply. -func createTarGz(d *requestContext, source string, w io.Writer, filenames ...string) error { +func createTarGz(d *Context, source string, w io.Writer, filenames ...string) error { gzWriter := gzip.NewWriter(w) tarWriter := tar.NewWriter(gzWriter) @@ -676,7 +711,7 @@ func createTarGz(d *requestContext, source string, w io.Writer, filenames ...str } // createTarGzWithLevel writes a tar.gz archive into w with the given gzip compression level (0=default, 1-9). -func createTarGzWithLevel(d *requestContext, source string, w io.Writer, level int, filenames ...string) error { +func createTarGzWithLevel(d *Context, source string, w io.Writer, level int, filenames ...string) error { var gzWriter *gzip.Writer if level >= 1 && level <= 9 { var err error @@ -712,7 +747,7 @@ func createTarGzWithLevel(d *requestContext, source string, w io.Writer, level i // archiveMultiRequestIdle without another request. // // server.maxArchiveSizeGB is enforced only for the HEAD/Range spool path. -func BuildAndStreamArchive(w http.ResponseWriter, r *http.Request, d *requestContext, source string, fileList []string) (int, error) { +func BuildAndStreamArchive(w http.ResponseWriter, r *http.Request, d *Context, source string, fileList []string) (int, error) { idx := indexing.GetIndex(source) if idx == nil { return http.StatusInternalServerError, fmt.Errorf("source %s is not available", source) @@ -771,15 +806,15 @@ func BuildAndStreamArchive(w http.ResponseWriter, r *http.Request, d *requestCon // HEAD or Range: same condition as chunked archive probing / retained spool (X-Archive-Token). needMultiRequestSession := r.Method == http.MethodHead || r.Header.Get("Range") != "" - if needMultiRequestSession && config.Server.MaxArchiveSizeGB > 0 { + if needMultiRequestSession && settings.Config.Server.MaxArchiveSizeGB > 0 { var estimatedSize int64 estimatedSize, err = computeArchiveSize(source, fileList, d) if err != nil { return http.StatusInternalServerError, fmt.Errorf("failed to compute archive size: %v", err) } - maxSizeBytes := config.Server.MaxArchiveSizeGB * 1024 * 1024 * 1024 + maxSizeBytes := settings.Config.Server.MaxArchiveSizeGB * 1024 * 1024 * 1024 if estimatedSize > maxSizeBytes { - return http.StatusRequestEntityTooLarge, fmt.Errorf("archive size would exceed the maximum allowed size (maxArchiveSize: %d GB)", config.Server.MaxArchiveSizeGB) + return http.StatusRequestEntityTooLarge, fmt.Errorf("archive size would exceed the maximum allowed size (maxArchiveSize: %d GB)", settings.Config.Server.MaxArchiveSizeGB) } } @@ -788,15 +823,15 @@ func BuildAndStreamArchive(w http.ResponseWriter, r *http.Request, d *requestCon if r.Method != http.MethodGet { return http.StatusMethodNotAllowed, fmt.Errorf("method not allowed") } - setContentDisposition(w, r, originalFileName) + SetContentDisposition(w, r, originalFileName, false) w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Cache-Control", "private") w.Header().Set("X-Content-Type-Options", "nosniff") writer := io.Writer(w) - if d.share != nil && d.share.MaxBandwidth > 0 { - limit := rate.Limit(d.share.MaxBandwidth * 1024) - burst := d.share.MaxBandwidth * 1024 + if d.Share.MaxBandwidth > 0 { + limit := rate.Limit(d.Share.MaxBandwidth * 1024) + burst := d.Share.MaxBandwidth * 1024 writer = newThrottledWriter(w, limit, burst, r.Context()) } if extension == ".zip" { @@ -842,7 +877,7 @@ func BuildAndStreamArchive(w http.ResponseWriter, r *http.Request, d *requestCon sizeInMB := fi.Size() / 1024 / 1024 if sizeInMB > 500 { - logger.Debugf("User %v is downloading large (%d MB) archive: %v", d.user.Username, sizeInMB, originalFileName) + logger.Debugf("User %v is downloading large (%d MB) archive: %v", d.User.Username, sizeInMB, originalFileName) } // needMultiRequestSession: HEAD or Range — always spool and use ServeContent (+ token for follow-ups). @@ -1227,7 +1262,7 @@ func extractTarGz(archivePath, destDir string) error { // computeArchiveSize returns the combined size of the given paths, respecting access rules. // Paths denied by access are skipped (not counted). -func computeArchiveSize(source string, fileList []string, d *requestContext) (int64, error) { +func computeArchiveSize(source string, fileList []string, d *Context) (int64, error) { var estimatedSize int64 idx := indexing.GetIndex(source) if idx == nil { @@ -1235,16 +1270,16 @@ func computeArchiveSize(source string, fileList []string, d *requestContext) (in } for _, path := range fileList { - if !store.Access.Permitted(idx.Path, path, d.user.Username) { + if !state.AccessPermitted(idx.Path, utils.IndexPathFromNormalized(path, true), d.User.Username) { continue } realPath, isDir, err := idx.GetRealPath(path) if err != nil { return 0, err } - indexPath := idx.MakeIndexPath(realPath, isDir) - info, ok := idx.GetReducedMetadata(indexPath, isDir) + info, ok := idx.GetReducedMetadata(realPath, isDir) if !ok { + indexPath := idx.MakeIndexPath(realPath, isDir).String() info, err = idx.GetFsInfo(indexPath, false, true) if err != nil { return 0, fmt.Errorf("failed to get file info for %s : %v", path, err) diff --git a/backend/http/archive_test.go b/backend/internal/web/archive_test.go similarity index 99% rename from backend/http/archive_test.go rename to backend/internal/web/archive_test.go index 2a59397bfd..68cfeed1a3 100644 --- a/backend/http/archive_test.go +++ b/backend/internal/web/archive_test.go @@ -1,4 +1,4 @@ -package http +package web import ( "archive/zip" diff --git a/backend/http/auth.go b/backend/internal/web/auth.go similarity index 51% rename from backend/http/auth.go rename to backend/internal/web/auth.go index 8ef98b5670..fbee904dd8 100644 --- a/backend/http/auth.go +++ b/backend/internal/web/auth.go @@ -1,4 +1,4 @@ -package http +package web import ( "crypto/hmac" @@ -14,32 +14,25 @@ import ( "github.com/golang-jwt/jwt/v4/request" "golang.org/x/crypto/bcrypt" - "github.com/gtsteffaniak/filebrowser/backend/auth" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/share" - "github.com/gtsteffaniak/filebrowser/backend/database/storage" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/auth" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/internal/activity" + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + "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" "github.com/gtsteffaniak/go-logger/logger" ) -// first checks for cookie -// then checks for header Authorization as Bearer token -// then checks for query parameter -func extractToken(r *http.Request) (string, error) { +// Prefer explicit ?auth= query and Authorization header over the session cookie so API +// clients can authenticate while a revoked browser cookie is present. ?auth= comes before +// Authorization so server callbacks (e.g. OnlyOffice) with both query session JWT and a +// third-party Bearer header resolve to the FileBrowser token (GitHub #2715). +func ExtractToken(r *http.Request) (string, error) { hasToken := false - tokenObj, err := r.Cookie("filebrowser_quantum_jwt") - if err == nil { - hasToken = true - token := tokenObj.Value - // Checks if the token isn't empty and if it contains two dots. - // The former prevents incompatibility with URLs that previously - // used basic auth. - if token != "" && strings.Count(token, ".") == 2 { - return token, nil - } - } auth := r.URL.Query().Get("auth") if auth != "" { @@ -49,28 +42,35 @@ func extractToken(r *http.Request) (string, error) { } } - // Check for Authorization header authHeader := r.Header.Get("Authorization") if authHeader != "" { hasToken = true - // Split the header to get "Bearer {token}" parts := strings.Split(authHeader, " ") if len(parts) > 1 { - // some clients don't respect RFC regarding cases switch strings.ToLower(parts[0]) { case "bearer": - return parts[1], nil + if strings.Count(parts[1], ".") == 2 { + return parts[1], nil + } case "basic": - // compatibility for basic auth - // user ignored, password is token + // compatibility for basic auth: user ignored, password is token _, token, ok := r.BasicAuth() - if ok { + if ok && token != "" && strings.Count(token, ".") == 2 { return token, nil } } } } + tokenObj, err := r.Cookie("filebrowser_quantum_jwt") + if err == nil { + hasToken = true + token := tokenObj.Value + if token != "" && strings.Count(token, ".") == 2 { + return token, nil + } + } + if hasToken { return "", fmt.Errorf("invalid token provided") } @@ -78,136 +78,103 @@ func extractToken(r *http.Request) (string, error) { return "", request.ErrNoTokenInRequest } -func setupProxyUser(r *http.Request, data *requestContext, proxyUser string) (*users.User, error) { - var err error - // Retrieve the user from the store and store it in the context - data.user, err = store.Users.Get(proxyUser) +// 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) { + // Try to get existing user + userValue, err := state.GetUserByUsername(username) if err != nil { - if err.Error() != "the resource does not exist" { + if !libError.Is(err, errors.ErrNotExist) { return nil, err } - // Auto-create user on first proxy authentication + // Auto-create user on first authentication user := users.User{ - LoginMethod: users.LoginMethodProxy, - Username: proxyUser, + FrontendUser: users.FrontendUser{ + LoginMethod: loginMethod, + Username: username, + }, } - settings.ApplyUserDefaults(&user) - if user.Username == config.Auth.AdminUsername { + state.ApplyUserDefaults(&user) + + if isAdmin { user.Permissions.Admin = true } - err = storage.CreateUser(user, user.Permissions) + + err = state.CreateUser(&user, "") if err != nil { return nil, err } - data.user, err = store.Users.Get(proxyUser) + if dirErr := files.MakeUserDirs(&user, true); dirErr != nil { + logger.Error(dirErr.Error()) + } + + // Fetch the created user + userValue, err = state.GetUserByUsername(username) if err != nil { return nil, err } } - if data.user.LoginMethod != users.LoginMethodProxy { + 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 + // No password change, pass empty string + err = state.UpdateUser(&userValue, "", "permissions") + if err != nil { + return nil, err + } + } + if err := state.SyncUserGroups(username, groups); err != nil { + logger.Warningf("failed to sync ldap user %s groups: %v", username, err) + } + // Verify login method matches + if userValue.LoginMethod != loginMethod { return nil, errors.ErrWrongLoginMethod } - if data.user.Username == config.Auth.AdminUsername && !data.user.Permissions.Admin { - data.user.Permissions.Admin = true - err = store.Users.Update(data.user, true, "Permissions") - if err != nil { - return nil, err - } - } - return data.user, nil + + return &userValue, nil +} + +func SetupProxyUser(r *http.Request, data *Context, proxyUser string) (*users.User, error) { + // Check if username matches admin username + isAdmin := proxyUser == settings.Config.Auth.AdminUsername + return getOrCreateAuthenticatedUser(proxyUser, users.LoginMethodProxy, isAdmin, []string{}) } // setupJwtUser retrieves or creates a user based on external JWT token claims -func setupJwtUser(r *http.Request, data *requestContext, username string, claims map[string]interface{}) (*users.User, error) { - var err error - // Retrieve the user from the store - data.user, err = store.Users.Get(username) - if err != nil { - if err.Error() != "the resource does not exist" { - return nil, err - } - // Auto-create user on first JWT authentication - user := users.User{ - LoginMethod: users.LoginMethodJwt, - Username: username, - } - settings.ApplyUserDefaults(&user) - - // Check if user should be admin based on groups - if config.Auth.Methods.JwtAuth.AdminGroup != "" { - groups := auth.ExtractGroupsFromClaims(claims, config.Auth.Methods.JwtAuth.GroupsClaim) - for _, group := range groups { - if group == config.Auth.Methods.JwtAuth.AdminGroup { - user.Permissions.Admin = true - break - } - } - } - - // Also check if username matches admin username - if user.Username == config.Auth.AdminUsername { - user.Permissions.Admin = true - } - - err = storage.CreateUser(user, user.Permissions) - if err != nil { - return nil, err - } - data.user, err = store.Users.Get(username) - if err != nil { - return nil, err +func SetupJwtUser(r *http.Request, data *Context, username string, claims map[string]interface{}) (*users.User, error) { + // Determine if user should be admin + isAdmin := username == settings.Config.Auth.AdminUsername + // Check if user should be admin based on groups + groups := auth.ExtractGroupsFromClaims(claims, settings.Config.Auth.Methods.JwtAuth.GroupsClaim) + for _, group := range groups { + if group == settings.Config.Auth.Methods.JwtAuth.AdminGroup { + isAdmin = true + break } } - // Verify login method matches - if data.user.LoginMethod != users.LoginMethodJwt { - return nil, errors.ErrWrongLoginMethod - } - - // Check if user is in allowed groups (if UserGroups is configured) - if len(config.Auth.Methods.JwtAuth.UserGroups) > 0 { - groups := auth.ExtractGroupsFromClaims(claims, config.Auth.Methods.JwtAuth.GroupsClaim) - allowed := false - for _, userGroup := range groups { - for _, allowedGroup := range config.Auth.Methods.JwtAuth.UserGroups { - if userGroup == allowedGroup { - allowed = true - break - } - } - if allowed { - break - } - } - if !allowed { - return nil, fmt.Errorf("user is not in allowed groups") - } - } - - // Update admin status if needed - shouldBeAdmin := false - if config.Auth.Methods.JwtAuth.AdminGroup != "" { - groups := auth.ExtractGroupsFromClaims(claims, config.Auth.Methods.JwtAuth.GroupsClaim) - for _, group := range groups { - if group == config.Auth.Methods.JwtAuth.AdminGroup { - shouldBeAdmin = true - break - } - } - } - if data.user.Username == config.Auth.AdminUsername { - shouldBeAdmin = true - } - - if shouldBeAdmin != data.user.Permissions.Admin { - data.user.Permissions.Admin = shouldBeAdmin - err = store.Users.Update(data.user, true, "Permissions") - if err != nil { - return nil, err - } - } - - return data.user, nil + return getOrCreateAuthenticatedUser(username, users.LoginMethodJwt, isAdmin, groups) } // loginHandler handles user authentication via password. @@ -226,17 +193,26 @@ func setupJwtUser(r *http.Request, data *requestContext, username string, claims // @Failure 429 {object} map[string]string "Too many requests - rate limited or temporarily locked out after failed attempts" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/auth/login [post] -func loginHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - passwordUser := d.user.LoginMethod == users.LoginMethodPassword - enforcedOtp := config.Auth.Methods.PasswordAuth.EnforcedOtp - missingOtp := d.user.TOTPSecret == "" +func loginHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + passwordUser := d.User.LoginMethod == users.LoginMethodPassword + enforcedOtp := settings.Config.Auth.Methods.PasswordAuth.EnforcedOtp + missingOtp := d.User.TOTPSecret == "" if passwordUser && enforcedOtp && missingOtp { return http.StatusForbidden, errors.ErrNoTotpConfigured } - if d.user.HasPasskeyMFA() && d.user.TOTPSecret == "" { + if d.User.HasPasskeyMFA() && d.User.TOTPSecret == "" { return http.StatusForbidden, errors.ErrPasskeyMFARequired } - return printToken(w, r, d.user) + status, err := printToken(w, r, d.User) + if err != nil || status != 0 { + return status, err + } + activity.RecordLogin(r, d.User) + return 0, nil +} + +func sessionCookieDomain(r *http.Request) string { + return strings.Split(requestHost(r), ":")[0] } // logoutHandler handles user logout @@ -247,21 +223,17 @@ func loginHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (in // @Param auth query string false "JWT token" // @Success 200 {object} map[string]string "{"logoutUrl": "http://..."}" // @Router /api/auth/logout [post] -func logoutHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if err := auth.RevokeApiToken(store.Access, d.token); err != nil { +func logoutHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if err := state.RevokeToken( d.Token); err != nil { logger.Errorf("Failed to revoke token on logout: %v", err) } // Clear the authentication cookie by setting it to expire in the past - // Get the correct domain for cookie - prefer X-Forwarded-Host from reverse proxy - host := r.Header.Get("X-Forwarded-Host") - if host == "" { - host = r.Host - } + host := sessionCookieDomain(r) cookie := &http.Cookie{ Name: "filebrowser_quantum_jwt", Value: "", - Domain: strings.Split(host, ":")[0], + Domain: host, Path: "/", SameSite: http.SameSiteStrictMode, Expires: time.Unix(0, 0), // Expire immediately @@ -269,31 +241,31 @@ func logoutHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i } http.SetCookie(w, cookie) - logoutUrl := fmt.Sprintf("%vlogin", config.Server.BaseURL) // Default fallback - if d.user != nil && d.user.LoginMethod == users.LoginMethodProxy { - proxyRedirectUrl := config.Auth.Methods.ProxyAuth.LogoutRedirectUrl + logoutUrl := fmt.Sprintf("%vlogin", settings.Config.Http.BaseURL) // Default fallback + if d.User != nil && d.User.LoginMethod == users.LoginMethodProxy { + proxyRedirectUrl := settings.Config.Auth.Methods.ProxyAuth.LogoutRedirectUrl if proxyRedirectUrl != "" { logoutUrl = proxyRedirectUrl } - } else if d.user != nil && d.user.LoginMethod == users.LoginMethodOidc { - oidcRedirectUrl := config.Auth.Methods.OidcAuth.LogoutRedirectUrl + } else if d.User != nil && d.User.LoginMethod == users.LoginMethodOidc { + oidcRedirectUrl := settings.Config.Auth.Methods.OidcAuth.LogoutRedirectUrl if oidcRedirectUrl != "" { logoutUrl = oidcRedirectUrl } - } else if d.user != nil && d.user.LoginMethod == users.LoginMethodLdap { - ldapRedirectUrl := config.Auth.Methods.LdapAuth.LogoutRedirectUrl + } else if d.User != nil && d.User.LoginMethod == users.LoginMethodLdap { + ldapRedirectUrl := settings.Config.Auth.Methods.LdapAuth.LogoutRedirectUrl if ldapRedirectUrl != "" { logoutUrl = ldapRedirectUrl } - } else if d.user != nil && d.user.LoginMethod == users.LoginMethodJwt { - jwtRedirectUrl := config.Auth.Methods.JwtAuth.LogoutRedirectUrl + } else if d.User != nil && d.User.LoginMethod == users.LoginMethodJwt { + jwtRedirectUrl := settings.Config.Auth.Methods.JwtAuth.LogoutRedirectUrl if jwtRedirectUrl != "" { logoutUrl = jwtRedirectUrl } } if logoutUrl == "" { logger.Debug("no logout url found, using default") - logoutUrl = fmt.Sprintf("%vlogin", config.Server.BaseURL) + logoutUrl = fmt.Sprintf("%vlogin", settings.Config.Http.BaseURL) } response := map[string]string{ "logoutUrl": logoutUrl, @@ -306,6 +278,12 @@ func logoutHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i return http.StatusInternalServerError, err } + if d.User != nil { + activity.RecordAuth(r, d.User, activitydb.EventLogout, activitydb.Details{ + LoginMethod: string(d.User.LoginMethod), + }) + } + return http.StatusOK, nil } @@ -321,8 +299,8 @@ func logoutHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i // @Failure 409 {object} map[string]string "Conflict - user already exists" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/auth/signup [post] -func signupHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !config.Auth.Methods.PasswordAuth.Signup { +func signupHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if !settings.Config.Auth.Methods.PasswordAuth.Signup { return http.StatusMethodNotAllowed, fmt.Errorf("signup is disabled") } @@ -336,18 +314,23 @@ func signupHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i } user := users.User{ - Username: username, - NonAdminEditable: users.NonAdminEditable{ - Password: password, + FrontendUser: users.FrontendUser{ + Username: username, + LoginMethod: users.LoginMethodPassword, + Permissions: settings.ConvertPermissionsToUsers(settings.Config.UserDefaults.Account.Permissions), }, - LoginMethod: users.LoginMethodPassword, } - err := storage.CreateUser(user, settings.ConvertPermissionsToUsers(config.UserDefaults.Account.Permissions)) + err := state.CreateUser(&user, password) if err != nil { logger.Debug(err.Error()) - // Return the actual error message instead of a generic one return http.StatusBadRequest, err } + if dirErr := files.MakeUserDirs(&user, true); dirErr != nil { + logger.Error(dirErr.Error()) + } + activity.RecordAuth(r, &user, activitydb.EventSignup, activitydb.Details{ + LoginMethod: string(users.LoginMethodPassword), + }) return 201, nil } @@ -361,13 +344,12 @@ func signupHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i // @Failure 401 {object} map[string]string "Unauthorized - invalid token" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/auth/renew [post] -func renewHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - // check if x-auth header is present and token is - return printToken(w, r, d.user) +func renewHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + return printToken(w, r, d.User) } func printToken(w http.ResponseWriter, r *http.Request, user *users.User) (int, error) { - expires := time.Hour * time.Duration(config.Auth.TokenExpirationHours) + expires := time.Hour * time.Duration(settings.Config.Auth.TokenExpirationHours) tokenString, _, err := auth.MakeSignedTokenAPI(user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), expires, user.Permissions, false) if err != nil { if strings.Contains(err.Error(), "key already exists with same name") { @@ -380,7 +362,7 @@ func printToken(w http.ResponseWriter, r *http.Request, user *users.User) (int, // This allows backend to identify expired sessions and provide better user feedback expiresTime := time.Now().Add(expires).Add(time.Minute * 30) - setSessionCookie(w, r, tokenString, expiresTime) + SetSessionCookie(w, r, tokenString, expiresTime) // Still return token in body for backward compatibility and state management w.Header().Set("Content-Type", "text/plain") @@ -390,7 +372,7 @@ func printToken(w http.ResponseWriter, r *http.Request, user *users.User) (int, return 0, nil } -func authenticateShareRequest(r *http.Request, l *share.Link) (int, error) { +func AuthenticateShareRequest(r *http.Request, l share.Share) (int, error) { if l.PasswordHash == "" { return 200, nil } @@ -405,7 +387,7 @@ func authenticateShareRequest(r *http.Request, l *share.Link) (int, error) { signature := parts[1] // Verify HMAC signature - mac := hmac.New(sha256.New, []byte(config.Auth.Key)) + mac := hmac.New(sha256.New, []byte(settings.Config.Auth.Key)) mac.Write([]byte(payload)) expectedSignature := base64.URLEncoding.EncodeToString(mac.Sum(nil)) @@ -423,11 +405,17 @@ func authenticateShareRequest(r *http.Request, l *share.Link) (int, error) { return 200, nil } } + logger.Debugf("share auth failed: hash=%s reason=invalid_token", l.Hash) } password := r.Header.Get("X-SHARE-PASSWORD") + if password == "" { + logger.Debugf("share auth failed: hash=%s reason=missing_password", l.Hash) + return http.StatusUnauthorized, nil + } if err := bcrypt.CompareHashAndPassword([]byte(l.PasswordHash), []byte(password)); err != nil { if libError.Is(err, bcrypt.ErrMismatchedHashAndPassword) { + logger.Debugf("share auth failed: hash=%s reason=wrong_password", l.Hash) return http.StatusUnauthorized, nil } return 401, err @@ -435,20 +423,30 @@ func authenticateShareRequest(r *http.Request, l *share.Link) (int, error) { return 200, nil } -// setSessionCookie - sets the authentication token as an HTTP cookie -// Get the correct domain for cookie - prefer X-Forwarded-Host from reverse proxy -func setSessionCookie(w http.ResponseWriter, r *http.Request, token string, expiresTime time.Time) { - host := r.Header.Get("X-Forwarded-Host") - if host == "" { - host = r.Host - } +// SetSessionCookie sets the authentication token as an HTTP cookie. +func SetSessionCookie(w http.ResponseWriter, r *http.Request, token string, expiresTime time.Time) { cookie := &http.Cookie{ Name: "filebrowser_quantum_jwt", Value: token, - Domain: strings.Split(host, ":")[0], // Set domain to the host without port + Domain: sessionCookieDomain(r), Path: "/", SameSite: http.SameSiteStrictMode, // strict mode prevents cookie from being sent to other domains Expires: expiresTime, } http.SetCookie(w, cookie) } + +// applyNamedApiTokenGlobalCaps intersects owner globals with JWT global caps for named custom API tokens. +// Session WEB_TOKEN_* tokens and minimal API tokens (no global caps in claims) keep full owner globals. +func applyNamedApiTokenGlobalCaps(user *users.User, tk users.AuthToken, tokenName string) { + if user == nil { + return + } + if strings.HasPrefix(tokenName, "WEB_TOKEN") { + return + } + if tk.BelongsTo == 0 || !users.HasAnyGlobalPermission(tk.Permissions) { + return + } + user.Permissions = users.IntersectGlobalPermissions(user.Permissions, tk.Permissions) +} diff --git a/backend/internal/web/auth_test.go b/backend/internal/web/auth_test.go new file mode 100644 index 0000000000..caea8342a4 --- /dev/null +++ b/backend/internal/web/auth_test.go @@ -0,0 +1,216 @@ +package web + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func findSessionCookie(t *testing.T, rec *httptest.ResponseRecorder) *http.Cookie { + t.Helper() + for _, c := range rec.Result().Cookies() { + if c.Name == "filebrowser_quantum_jwt" { + return c + } + } + t.Fatal("session cookie not found") + return nil +} + +func TestSetSessionCookieUsesTrustedHost(t *testing.T) { + orig := settings.Config.Http.TrustProxyHeaders + t.Cleanup(func() { settings.Config.Http.TrustProxyHeaders = orig }) + + settings.Config.Http.TrustProxyHeaders = true + req := httptest.NewRequest(http.MethodPost, "/api/auth/login", nil) + req.Host = "127.0.0.1:8080" + req.Header.Set("X-Forwarded-Host", "files.example.com") + + rec := httptest.NewRecorder() + SetSessionCookie(rec, req, "token", time.Now().Add(time.Hour)) + + cookie := findSessionCookie(t, rec) + if cookie.Domain != "files.example.com" { + t.Fatalf("cookie Domain = %q, want files.example.com", cookie.Domain) + } +} + +func TestSetSessionCookieIgnoresUntrustedForwardedHost(t *testing.T) { + settings.Config.Http.TrustProxyHeaders = false + t.Cleanup(func() { settings.Config.Http.TrustProxyHeaders = false }) + + req := httptest.NewRequest(http.MethodPost, "/api/auth/login", nil) + req.Host = "127.0.0.1:8080" + req.Header.Set("X-Forwarded-Host", "evil.example.com") + + rec := httptest.NewRecorder() + SetSessionCookie(rec, req, "token", time.Now().Add(time.Hour)) + + cookie := findSessionCookie(t, rec) + if cookie.Domain != "127.0.0.1" { + t.Fatalf("cookie Domain = %q, want 127.0.0.1", cookie.Domain) + } +} + +func TestLogoutClearsCookieForTrustedHost(t *testing.T) { + setupTestEnv(t) + + origTrust := settings.Config.Http.TrustProxyHeaders + origBaseURL := settings.Config.Http.BaseURL + t.Cleanup(func() { + settings.Config.Http.TrustProxyHeaders = origTrust + settings.Config.Http.BaseURL = origBaseURL + }) + + settings.Config.Http.TrustProxyHeaders = true + settings.Config.Http.BaseURL = "/" + + req := httptest.NewRequest(http.MethodPost, "/api/auth/logout", nil) + req.Host = "127.0.0.1:8080" + req.Header.Set("X-Forwarded-Host", "files.example.com") + + rec := httptest.NewRecorder() + status, err := logoutHandler(rec, req, &Context{User: &users.User{ + FrontendUser: users.FrontendUser{LoginMethod: users.LoginMethodPassword}, + }}) + if err != nil || status != http.StatusOK { + t.Fatalf("logoutHandler() status=%d err=%v", status, err) + } + + cookie := findSessionCookie(t, rec) + if cookie.Domain != "files.example.com" { + t.Fatalf("logout cookie Domain = %q, want files.example.com", cookie.Domain) + } + if cookie.MaxAge != -1 { + t.Fatalf("logout cookie MaxAge = %d, want -1", cookie.MaxAge) + } +} + +func TestExtractTokenPrefersAuthorizationOverCookie(t *testing.T) { + const apiToken = "aaa.bbb.ccc" + const cookieToken = "revoked.header.token" + + req := httptest.NewRequest(http.MethodGet, "/api/users", nil) + req.AddCookie(&http.Cookie{ + Name: "filebrowser_quantum_jwt", + Value: cookieToken, + }) + req.Header.Set("Authorization", "Bearer "+apiToken) + + got, err := ExtractToken(req) + if err != nil { + t.Fatalf("ExtractToken() error = %v", err) + } + if got != apiToken { + t.Fatalf("ExtractToken() = %q, want %q", got, apiToken) + } +} + +func TestExtractTokenUsesCookieWhenNoAuthorizationHeader(t *testing.T) { + const cookieToken = "session.header.token" + + req := httptest.NewRequest(http.MethodGet, "/api/users", nil) + req.AddCookie(&http.Cookie{ + Name: "filebrowser_quantum_jwt", + Value: cookieToken, + }) + + got, err := ExtractToken(req) + if err != nil { + t.Fatalf("ExtractToken() error = %v", err) + } + if got != cookieToken { + t.Fatalf("ExtractToken() = %q, want %q", got, cookieToken) + } +} + +func TestExtractTokenUsesAuthQueryBeforeCookie(t *testing.T) { + const queryToken = "query.header.token" + const cookieToken = "session.header.token" + + req := httptest.NewRequest(http.MethodGet, "/api/users?auth="+queryToken, nil) + req.AddCookie(&http.Cookie{ + Name: "filebrowser_quantum_jwt", + Value: cookieToken, + }) + + got, err := ExtractToken(req) + if err != nil { + t.Fatalf("ExtractToken() error = %v", err) + } + if got != queryToken { + t.Fatalf("ExtractToken() = %q, want %q", got, queryToken) + } +} + +func TestExtractTokenPrefersAuthQueryOverAuthorization(t *testing.T) { + const queryToken = "query.only.token" + const headerToken = "header.only.jwt" + + req := httptest.NewRequest(http.MethodGet, "/api/office/callback?auth="+queryToken, nil) + req.Header.Set("Authorization", "Bearer "+headerToken) + + got, err := ExtractToken(req) + if err != nil { + t.Fatalf("ExtractToken() error = %v", err) + } + if got != queryToken { + t.Fatalf("ExtractToken() = %q, want %q", got, queryToken) + } +} + +func TestApplyNamedApiTokenGlobalCaps(t *testing.T) { + owner := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "alice", + Permissions: users.Permissions{ + Admin: true, + Api: true, + Share: true, + }, + }, + ID: 1, + } + + t.Run("session token unchanged", func(t *testing.T) { + user := *owner + applyNamedApiTokenGlobalCaps(&user, users.AuthToken{ + BelongsTo: 1, + Permissions: users.Permissions{Admin: false}, + }, "WEB_TOKEN_abcd") + if !user.Permissions.Admin { + t.Fatal("session token should keep DB admin") + } + }) + + t.Run("minimal api token unchanged", func(t *testing.T) { + user := *owner + applyNamedApiTokenGlobalCaps(&user, users.AuthToken{}, "my-key") + if !user.Permissions.Admin { + t.Fatal("minimal token should keep DB admin") + } + }) + + t.Run("custom api token caps globals", func(t *testing.T) { + user := *owner + applyNamedApiTokenGlobalCaps(&user, users.AuthToken{ + BelongsTo: 1, + Permissions: users.Permissions{ + Admin: false, + Api: true, + Share: true, + Modify: true, + }, + }, "customized") + if user.Permissions.Admin { + t.Fatal("custom token should cap admin from JWT") + } + if !user.Permissions.Api || !user.Permissions.Share { + t.Fatalf("expected api and share, got %#v", user.Permissions) + } + }) +} diff --git a/backend/internal/web/download.go b/backend/internal/web/download.go new file mode 100644 index 0000000000..1d438bd289 --- /dev/null +++ b/backend/internal/web/download.go @@ -0,0 +1,293 @@ +package web + +import ( + "context" + "fmt" + "io" + "net/http" + "path/filepath" + + "github.com/gtsteffaniak/filebrowser/backend/internal/activity" + "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/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/go-logger/logger" + "golang.org/x/time/rate" +) + +// waitLimiterBytes applies rate limiting in chunks no larger than the limiter burst. +func waitLimiterBytes(ctx context.Context, lim *rate.Limiter, n int) error { + for remaining := n; remaining > 0; { + chunk := remaining + if burst := lim.Burst(); burst > 0 && chunk > burst { + chunk = burst + } + if chunk < 1 { + chunk = 1 + } + if err := lim.WaitN(ctx, chunk); err != nil { + return err + } + remaining -= chunk + } + return nil +} + +// throttledWriter wraps an io.Writer and rate-limits outbound bytes (streaming archives to the client). +type throttledWriter struct { + w io.Writer + limiter *rate.Limiter + ctx context.Context +} + +func newThrottledWriter(w io.Writer, limit rate.Limit, burst int, ctx context.Context) *throttledWriter { + return &throttledWriter{ + w: w, + limiter: rate.NewLimiter(limit, burst), + ctx: ctx, + } +} + +func (tw *throttledWriter) Write(p []byte) (n int, err error) { + n, err = tw.w.Write(p) + if n > 0 { + if waitErr := waitLimiterBytes(tw.ctx, tw.limiter, n); waitErr != nil && err == nil { + err = waitErr + } + } + return +} + +type throttledReadSeeker struct { + rs io.ReadSeeker + limiter *rate.Limiter + ctx context.Context +} + +// NewThrottledReadSeeker rate-limits reads from an io.ReadSeeker. +func NewThrottledReadSeeker(rs io.ReadSeeker, limit rate.Limit, burst int, ctx context.Context) io.ReadSeeker { + return &throttledReadSeeker{ + rs: rs, + limiter: rate.NewLimiter(limit, burst), + ctx: ctx, + } +} + +func (r *throttledReadSeeker) Read(p []byte) (n int, err error) { + n, err = r.rs.Read(p) + if n > 0 { + if waitErr := waitLimiterBytes(r.ctx, r.limiter, n); waitErr != nil && err == nil { + err = waitErr + } + } + return +} + +func (r *throttledReadSeeker) Seek(offset int64, whence int) (int64, error) { + return r.rs.Seek(offset, whence) +} + +// downloadHandler serves the raw content of a file, multiple files, or directory in various formats. +// @Summary Download content of a file, multiple files, or directory +// @Description Returns the raw content of a file, multiple files, or a directory. Supports downloading files as archives in various formats. +// @Description +// @Description **Filename Encoding:** +// @Description - The Content-Disposition header will always include both: +// @Description 1. `filename="..."`: An ASCII-safe version of the filename for compatibility. +// @Description 2. `filename*=utf-8"...`: The full UTF-8 encoded filename (RFC 6266/5987) for modern clients. +// @Description +// @Description **Multiple Files:** +// @Description - Use repeated query parameters: `?file=file1.txt&file=file2.txt&file=file3.txt` +// @Description - This supports filenames containing commas and special characters +// @Tags Resources +// @Accept json +// @Param source query string true "Source name for the files (required)" +// @Param file query []string true "File path (can be repeated for multiple files)" +// @Param inline query bool false "If true, sets 'Content-Disposition' to 'inline'. Otherwise, defaults to 'attachment'." +// @Param algo query string false "Compression algorithm for archiving multiple files or directories. Options: 'zip' and 'tar.gz'. Default is 'zip'." +// @Success 200 {file} file "Raw file or directory content, or archive for multiple files" +// @Failure 202 {object} map[string]string "Modify permissions required" +// @Failure 400 {object} map[string]string "Invalid request path" +// @Failure 404 {object} map[string]string "File or directory not found" +// @Failure 500 {object} map[string]string "Internal server error" +// @Router /api/resources/download [get] +func downloadHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + source := r.URL.Query().Get("source") + fileList := r.URL.Query()["file"] + + // Rule 1: Validate all user-provided file paths to prevent path traversal + for i, filePath := range fileList { + cleanPath, err := utils.SanitizePath(filePath) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid file path: %v", err) + } + fileList[i] = cleanPath + } + + return RawFilesHandler(w, r, d, source, fileList) +} + +// publicDownloadHandler serves the raw content of a file, multiple files, or directory via a public share. +// @Summary Download files from a public share +// @Description Downloads raw content from a public share. Supports single files, multiple files, or directories as archives. Enforces download limits (global or per-user) and blocks anonymous users when per-user limits are enabled. +// @Description +// @Description **Multiple Files:** +// @Description - Use repeated query parameters: `?file=file1.txt&file=file2.txt&file=file3.txt` +// @Description - This supports filenames containing commas and special characters +// @Tags Resources +// @Accept json +// @Produce octet-stream +// @Param hash query string true "Share hash for authentication" +// @Param file query []string true "File path (can be repeated for multiple files)" +// @Param inline query bool false "If true, sets 'Content-Disposition' to 'inline'. Otherwise, defaults to 'attachment'." +// @Param algo query string false "Compression algorithm for archiving multiple files or directories. Options: 'zip' and 'tar.gz'. Default is 'zip'." +// @Success 200 {file} file "Raw file or directory content, or archive for multiple files" +// @Failure 400 {object} map[string]string "Invalid request path or encoding" +// @Failure 403 {object} map[string]string "Download limit reached, anonymous access blocked, or share unavailable" +// @Failure 404 {object} map[string]string "Share not found or file not found" +// @Failure 500 {object} map[string]string "Internal server error" +// @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") + } + } + + files := r.URL.Query()["file"] + if len(files) == 0 { + files = []string{"/"} + } + + sourceInfo, ok := settings.Config.Server.SourceMap[d.Share.SourcePath] + if !ok { + return http.StatusInternalServerError, fmt.Errorf("source not found for share") + } + actualSourceName := sourceInfo.Name + + fileList := []string{} + for _, file := range files { + cleanFile, err := utils.SanitizePath(file) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid file path: %v", err) + } + filePath := utils.JoinPathAsUnix(d.Share.Path, cleanFile) + fileList = append(fileList, filePath) + } + + status, err := RawFilesHandler(w, r, d, actualSourceName, fileList) + if err != nil { + if err == errors.ErrDownloadNotAllowed { + return http.StatusForbidden, errors.ErrDownloadNotAllowed + } + if err == errors.ErrUseMediaStream { + return http.StatusForbidden, errors.ErrUseMediaStream + } + logger.Errorf("public share handler: error processing filelist: %v with error %v", files, err) + return status, fmt.Errorf("error processing filelist: %v", files) + } + // Audit row is written inside RawFilesHandler via activity.RecordDownload. + if downloadResponseRecordsActivity(status, err) { + if recErr := state.IncrementShareDownloadCount(d.Share.Hash, d.User.Username); recErr != nil { + logger.Errorf("public share handler: failed to increment share download count for %s: %v", d.Share.Hash, recErr) + } + } + return status, nil +} + +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) + if err != nil { + return http.StatusForbidden, err + } + if !filePerms.Download { + return http.StatusForbidden, fmt.Errorf("user is not allowed to download") + } + } + + if len(fileList) == 0 && d.Share.Hash == "" { + return http.StatusBadRequest, fmt.Errorf("no files specified") + } + + firstFilePath := fileList[0] + displayFileList := ResolveDisplayFileList(d, source, fileList) + var err error + var status int + var userscope string + fileName := filepath.Base(firstFilePath) + + // modify all filepaths for user scope + if d.Share.Hash == "" { + userscope, err = d.User.GetScopeForSourceName(source) + if err != nil { + return http.StatusForbidden, err + } + for i, filePath := range fileList { + fileList[i] = utils.JoinPathAsUnix(userscope, filePath) + } + } + firstFilePath = fileList[0] + idx := indexing.GetIndex(source) + if idx == nil { + return http.StatusInternalServerError, fmt.Errorf("source %s is not available", source) + } + _, isDir, err := idx.GetRealPath(firstFilePath) + if err != nil { + return http.StatusInternalServerError, err + } + + if len(fileList) == 1 && !isDir { + forceInline := false + forceInline, err = resolveDownloadInlineDisposition(fileName, r.URL.Query().Get("inline") == "true") + if err != nil { + return http.StatusForbidden, err + } + status, err = ServeSingleFile(w, r, d, source, firstFilePath, fileName, ServeSingleFileOptions{ForceInline: forceInline}) + if downloadResponseRecordsActivity(status, err) { + activity.RecordDownload(r, toActor(d), source, displayFileList) + } + return status, err + } + + status, err = BuildAndStreamArchive(w, r, d, source, fileList) + if status == 0 && err == nil { + status = http.StatusOK + } + if downloadResponseRecordsActivity(status, err) { + activity.RecordDownload(r, toActor(d), source, displayFileList) + } + return status, err +} + +func resolveDownloadInlineDisposition(fileName string, inlineRequested bool) (bool, error) { + if !IsMediaStreamFile(fileName) { + return inlineRequested, nil + } + if inlineRequested { + return false, errors.ErrUseMediaStream + } + return false, nil +} + +func downloadResponseRecordsActivity(status int, err error) bool { + return err == nil && status >= http.StatusOK && status < http.StatusMultipleChoices +} diff --git a/backend/internal/web/download_activity_test.go b/backend/internal/web/download_activity_test.go new file mode 100644 index 0000000000..b1e071605d --- /dev/null +++ b/backend/internal/web/download_activity_test.go @@ -0,0 +1,51 @@ +package web + +import ( + stderrors "errors" + "net/http" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" +) + +func TestResolveDownloadInlineDisposition(t *testing.T) { + t.Parallel() + force, err := resolveDownloadInlineDisposition("readme.txt", true) + if err != nil || !force { + t.Fatalf("text inline: force=%v err=%v", force, err) + } + force, err = resolveDownloadInlineDisposition("clip.mp4", false) + if err != nil || force { + t.Fatalf("video download: force=%v err=%v", force, err) + } + _, err = resolveDownloadInlineDisposition("clip.mp4", true) + if !stderrors.Is(err, errors.ErrUseMediaStream) { + t.Fatalf("expected ErrUseMediaStream for inline video, got %v", err) + } +} + +func TestDownloadResponseRecordsActivity(t *testing.T) { + t.Parallel() + tests := []struct { + name string + status int + err error + want bool + }{ + {name: "200 ok", status: http.StatusOK, want: true}, + {name: "206 partial", status: http.StatusPartialContent, want: true}, + {name: "416 range unsatisfiable", status: http.StatusRequestedRangeNotSatisfiable, want: false}, + {name: "403 forbidden", status: http.StatusForbidden, want: false}, + {name: "error with 200", status: http.StatusOK, err: stderrors.New("write failed"), want: false}, + {name: "zero status", status: 0, want: false}, + } + for _, tc := range tests { + tc := tc + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + if got := downloadResponseRecordsActivity(tc.status, tc.err); got != tc.want { + t.Fatalf("downloadResponseRecordsActivity(%d, err=%v) = %v, want %v", tc.status, tc.err != nil, got, tc.want) + } + }) + } +} diff --git a/backend/internal/web/download_throttle_test.go b/backend/internal/web/download_throttle_test.go new file mode 100644 index 0000000000..44734bdedf --- /dev/null +++ b/backend/internal/web/download_throttle_test.go @@ -0,0 +1,79 @@ +package web + +import ( + "bytes" + "context" + "io" + "strings" + "testing" + "time" + + "golang.org/x/time/rate" +) + +type fixedReadSeeker struct { + data []byte + off int64 +} + +func (f *fixedReadSeeker) Read(p []byte) (int, error) { + if f.off >= int64(len(f.data)) { + return 0, io.EOF + } + n := copy(p, f.data[f.off:]) + f.off += int64(n) + return n, nil +} + +func (f *fixedReadSeeker) Seek(offset int64, whence int) (int64, error) { + var base int64 + switch whence { + case io.SeekStart: + base = 0 + case io.SeekCurrent: + base = f.off + case io.SeekEnd: + base = int64(len(f.data)) + default: + return 0, io.ErrUnexpectedEOF + } + f.off = base + offset + if f.off < 0 { + f.off = 0 + } + return f.off, nil +} + +func TestThrottledReadSeekerChunksLargeRead(t *testing.T) { + t.Parallel() + const burst = 1024 + const readSize = 32 << 10 + payload := bytes.Repeat([]byte("x"), readSize) + rs := &fixedReadSeeker{data: payload} + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + tr := NewThrottledReadSeeker(rs, rate.Inf, burst, ctx) + + buf := make([]byte, readSize) + n, err := tr.Read(buf) + if err != nil { + t.Fatalf("Read: %v", err) + } + if n != readSize { + t.Fatalf("Read n = %d, want %d", n, readSize) + } +} + +func TestWaitLimiterBytesRejectsCancelledContext(t *testing.T) { + t.Parallel() + lim := rate.NewLimiter(1, 1024) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + err := waitLimiterBytes(ctx, lim, 4096) + if err == nil { + t.Fatal("expected context error") + } + if !strings.Contains(err.Error(), "context") { + t.Fatalf("unexpected error: %v", err) + } +} diff --git a/backend/http/duplicates.go b/backend/internal/web/duplicates.go similarity index 94% rename from backend/http/duplicates.go rename to backend/internal/web/duplicates.go index 245b7733d7..101d5c92b9 100644 --- a/backend/http/duplicates.go +++ b/backend/internal/web/duplicates.go @@ -1,4 +1,4 @@ -package http +package web import ( "crypto/md5" @@ -12,11 +12,15 @@ import ( "time" "unicode" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/indexing" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/activity" + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" "github.com/gtsteffaniak/go-cache/cache" "github.com/gtsteffaniak/go-logger/logger" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + ) // duplicateSearchMutex serializes duplicate searches to run one at a time @@ -142,8 +146,9 @@ func (s *duplicateProcessingStats) shouldStop() (bool, string) { // @Success 200 {object} duplicateResponse "List of duplicate file groups with metadata. Response includes 'incomplete' flag if processing stopped early due to resource limits." // @Failure 400 {object} map[string]string "Bad Request" // @Failure 503 {object} map[string]string "Service Unavailable (indexing in progress or another search running)" -// @Router /api/tools/duplicateFinder [get] -func duplicatesHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +// @Router /api/tools/duplicate-finder [get] +func duplicatesHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + started := time.Now() opts, err := prepDuplicatesOptions(r, d) if err != nil { return http.StatusBadRequest, err @@ -153,14 +158,14 @@ func duplicatesHandler(w http.ResponseWriter, r *http.Request, d *requestContext if index == nil { return http.StatusBadRequest, fmt.Errorf("index not found for source %s", opts.source) } - userscope, err := d.user.GetScopeForSourceName(index.Name) + userscope, err := d.User.GetScopeForSourceName(index.Name) if err != nil { return http.StatusForbidden, err } userscope = strings.TrimRight(userscope, "/") scopePath := utils.JoinPathAsUnix(userscope, opts.searchScope) fullPath := index.MakeIndexPath(scopePath, true) - if !store.Access.Permitted(index.Path, fullPath, d.user.Username) { + if !state.AccessPermitted(index.Path, fullPath, d.User.Username) { return http.StatusForbidden, fmt.Errorf("user is not allowed to access this location") } @@ -170,17 +175,32 @@ func duplicatesHandler(w http.ResponseWriter, r *http.Request, d *requestContext return http.StatusServiceUnavailable, fmt.Errorf("duplicate search is not available while indexing is in progress - please try again when indexing completes") } - userscope, err = d.user.GetScopeForSourceName(index.Name) + userscope, err = d.User.GetScopeForSourceName(index.Name) if err != nil { return http.StatusForbidden, err } userscope = strings.TrimRight(userscope, "/") scopePath = utils.JoinPathAsUnix(userscope, opts.searchScope) fullPath = index.MakeIndexPath(scopePath, true) - if !store.Access.Permitted(index.Path, fullPath, d.user.Username) { + if !state.AccessPermitted(index.Path, fullPath, d.User.Username) { return http.StatusForbidden, fmt.Errorf("user is not allowed to access this location") } + logDuplicateFinder := func(response duplicateResponse, cached bool) { + details := activitydb.Details{ + Source: index.Name, + Path: scopePath, + FileCount: len(response.Groups), + DurationMs: time.Since(started).Milliseconds(), + Truncated: response.Incomplete, + Cached: cached, + } + if response.Reason != "" { + details.Error = response.Reason + } + activity.RecordTool(r, toActor(d), activitydb.EventDuplicateFinder, details) + } + // 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) @@ -192,7 +212,8 @@ func duplicatesHandler(w http.ResponseWriter, r *http.Request, d *requestContext w.Header().Set("X-Search-Incomplete", "true") w.Header().Set("X-Search-Incomplete-Reason", cachedResults.Reason) } - return renderJSON(w, r, cachedResults) + logDuplicateFinder(cachedResults, true) + return RenderJSON(w, r, cachedResults) } // Reject concurrent requests @@ -208,7 +229,8 @@ func duplicatesHandler(w http.ResponseWriter, r *http.Request, d *requestContext w.Header().Set("X-Search-Incomplete", "true") w.Header().Set("X-Search-Incomplete-Reason", cachedResults.Reason) } - return renderJSON(w, r, cachedResults) + logDuplicateFinder(cachedResults, true) + return RenderJSON(w, r, cachedResults) } // Find duplicates using index-native approach with resource limits @@ -241,7 +263,8 @@ func duplicatesHandler(w http.ResponseWriter, r *http.Request, d *requestContext w.Header().Set("X-Search-Incomplete-Reason", stats.stopReason) } - return renderJSON(w, r, response) + logDuplicateFinder(response, false) + return RenderJSON(w, r, response) } // findDuplicatesInIndex finds duplicates using the shared IndexDB with resource limits @@ -553,9 +576,9 @@ func mergeGroupsByChecksum(groups []duplicateGroupWithChecksums) []duplicateGrou return merged } -func prepDuplicatesOptions(r *http.Request, d *requestContext) (*duplicatesOptions, error) { +func prepDuplicatesOptions(r *http.Request, d *Context) (*duplicatesOptions, error) { source := r.URL.Query().Get("source") - scope, err := utils.SanitizeUserPath(r.URL.Query().Get("scope")) + scope, err := utils.SanitizePath(r.URL.Query().Get("scope")) if err != nil { return nil, fmt.Errorf("invalid scope: %v", err) } @@ -581,7 +604,7 @@ func prepDuplicatesOptions(r *http.Request, d *requestContext) (*duplicatesOptio return nil, fmt.Errorf("index not found for source %s", source) } - userscope, err := d.user.GetScopeForSourceName(source) + userscope, err := d.User.GetScopeForSourceName(source) if err != nil { return nil, err } @@ -591,10 +614,10 @@ func prepDuplicatesOptions(r *http.Request, d *requestContext) (*duplicatesOptio return &duplicatesOptions{ source: source, searchScope: searchScope, - combinedPath: combinedPath, + combinedPath: combinedPath.String(), minSize: minSize, useChecksum: useChecksum, - username: d.user.Username, + username: d.User.Username, }, nil } @@ -944,7 +967,7 @@ func groupFilesByType(files []*iteminfo.FileInfo) map[string][]*iteminfo.FileInf // filterFilesByPermission filters files to only include those the user is permitted to access // This is called early in the duplicate search process to avoid processing files the user can't see func filterFilesByPermission(files []*iteminfo.FileInfo, index *indexing.Index, username string) []*iteminfo.FileInfo { - if store.Access == nil { + if false { // No access control configured, return all files return files } @@ -952,7 +975,7 @@ func filterFilesByPermission(files []*iteminfo.FileInfo, index *indexing.Index, filtered := make([]*iteminfo.FileInfo, 0, len(files)) for _, file := range files { // Check permission using index.Path (source root) and file.Path (index-relative path) - if store.Access.Permitted(index.Path, file.Path, username) { + if state.AccessPermitted(index.Path, utils.IndexPathFromNormalized(file.Path, true), username) { filtered = append(filtered, file) } } diff --git a/backend/http/embed/.gitignore b/backend/internal/web/embed/.gitignore similarity index 100% rename from backend/http/embed/.gitignore rename to backend/internal/web/embed/.gitignore diff --git a/backend/http/fileWatcher.go b/backend/internal/web/fileWatcher.go similarity index 89% rename from backend/http/fileWatcher.go rename to backend/internal/web/fileWatcher.go index 167ea73c57..208f09c43f 100644 --- a/backend/http/fileWatcher.go +++ b/backend/internal/web/fileWatcher.go @@ -1,4 +1,4 @@ -package http +package web import ( "bufio" @@ -11,9 +11,11 @@ import ( "strings" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/events" - "github.com/gtsteffaniak/filebrowser/backend/indexing" + "github.com/gtsteffaniak/filebrowser/backend/internal/events" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + ) // fileWatchResponse represents the response from file watch @@ -122,8 +124,8 @@ func readLastNLines(filePath string, n int) (string, error) { // @Failure 403 {object} map[string]string "Permission denied" // @Failure 404 {object} map[string]string "File not found" // @Failure 500 {object} map[string]string "Internal server error" -// @Router /api/tools/fileWatcher [get] -func fileWatchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +// @Router /api/tools/file-watcher [get] +func fileWatchHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { // Check for latency check request - return immediately with minimal response if r.URL.Query().Get("latencyCheck") != "" { return http.StatusOK, nil @@ -137,7 +139,7 @@ func fileWatchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) return http.StatusBadRequest, fmt.Errorf("path and source are required") } var err error - path, err = utils.SanitizeUserPath(path) + path, err = utils.SanitizePath(path) if err != nil { return http.StatusBadRequest, err } @@ -157,13 +159,17 @@ func fileWatchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) } // Validate user has access to the source - userScope, err := d.user.GetScopeForSourceName(source) + userScope, err := d.User.GetScopeForSourceName(source) if err != nil { return http.StatusForbidden, err } // Check download permission (required to read file content) - if !d.user.Permissions.Download { + filePerms, err := effectiveFilePerms(d, source) + if err != nil { + return http.StatusForbidden, err + } + if !filePerms.Download { return http.StatusForbidden, fmt.Errorf("user is not allowed to read file content") } @@ -177,10 +183,8 @@ func fileWatchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) } // Check access control - if store.Access != nil { - if !store.Access.Permitted(idx.Path, scopePath, d.user.Username) { - return http.StatusForbidden, fmt.Errorf("access denied to file") - } + if !state.AccessPermitted(idx.Path, utils.IndexPathFromNormalized(scopePath, true), d.User.Username) { + return http.StatusForbidden, fmt.Errorf("access denied to file") } // Get real file path @@ -252,29 +256,32 @@ type fileWatchSSEEvent struct { // @Failure 400 {object} map[string]string "Invalid request" // @Failure 403 {object} map[string]string "Permission denied" // @Failure 404 {object} map[string]string "File not found" -// @Router /api/tools/fileWatcher/sse [get] -func fileWatchSSEHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +// @Router /api/tools/file-watcher/sse [get] +func fileWatchSSEHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { // Check realtime permissions - if !(d.user.Permissions.Realtime) { + if !(d.User.Permissions.Realtime) { return http.StatusForbidden, fmt.Errorf("realtime permission required for SSE file watching") } - if !d.user.Permissions.Download { + source := r.URL.Query().Get("source") + filePerms, err := effectiveFilePerms(d, source) + if err != nil { + return http.StatusForbidden, err + } + if !filePerms.Download { return http.StatusForbidden, fmt.Errorf("user is not allowed to read file content") } path := r.URL.Query().Get("path") - source := r.URL.Query().Get("source") linesStr := r.URL.Query().Get("lines") intervalStr := r.URL.Query().Get("interval") - var err error if path == "" || source == "" { return http.StatusBadRequest, fmt.Errorf("path and source are required") } // Rule 1: Validate user-provided path to prevent path traversal - cleanPath, err := utils.SanitizeUserPath(path) + cleanPath, err := utils.SanitizePath(path) if err != nil { return http.StatusBadRequest, err } @@ -310,7 +317,7 @@ func fileWatchSSEHandler(w http.ResponseWriter, r *http.Request, d *requestConte } // Validate user has access to the source - userScope, err := d.user.GetScopeForSourceName(source) + userScope, err := d.User.GetScopeForSourceName(source) if err != nil { return http.StatusForbidden, err } @@ -324,10 +331,8 @@ func fileWatchSSEHandler(w http.ResponseWriter, r *http.Request, d *requestConte } // Check access control - if store.Access != nil { - if !store.Access.Permitted(idx.Path, scopePath, d.user.Username) { - return http.StatusForbidden, fmt.Errorf("access denied to file") - } + if !state.AccessPermitted(idx.Path, utils.IndexPathFromNormalized(scopePath, true), d.User.Username) { + return http.StatusForbidden, fmt.Errorf("access denied to file") } // Get real file path @@ -353,13 +358,13 @@ func fileWatchSSEHandler(w http.ResponseWriter, r *http.Request, d *requestConte return http.StatusInternalServerError, fmt.Errorf("streaming not supported") } - msgr := messenger{flusher: flusher, writer: w} + msgr := NewMessenger(flusher, w) clientGone := r.Context().Done() - username := d.user.Username + username := d.User.Username // Initial ack statusMsg, _ := json.Marshal(map[string]interface{}{"status": "connected"}) - if err := msgr.sendEvent("fileWatch", string(statusMsg)); err != nil { + if err := msgr.SendEvent("fileWatch", string(statusMsg)); err != nil { return http.StatusInternalServerError, fmt.Errorf("error sending initial message: %v", err) } @@ -399,15 +404,15 @@ func fileWatchSSEHandler(w http.ResponseWriter, r *http.Request, d *requestConte // Main loop: listen for events from events system (like general SSE handler) // Use server context if available, otherwise use request context serverCtx := r.Context() - if d.ctx != nil { - serverCtx = d.ctx + if d.Ctx != nil { + serverCtx = d.Ctx } for { select { case <-serverCtx.Done(): close(stopTicker) - _ = msgr.sendEvent("fileWatch", "\"server shutting down\"") + _ = msgr.SendEvent("fileWatch", "\"server shutting down\"") return http.StatusOK, nil case <-clientGone: @@ -421,7 +426,7 @@ func fileWatchSSEHandler(w http.ResponseWriter, r *http.Request, d *requestConte } // Only process fileWatch events for this connection if msg.EventType == "fileWatch" { - if err := msgr.sendEvent(msg.EventType, msg.Message); err != nil { + if err := msgr.SendEvent(msg.EventType, msg.Message); err != nil { close(stopTicker) return http.StatusInternalServerError, fmt.Errorf("error sending event: %v", err) } diff --git a/backend/internal/web/http.go b/backend/internal/web/http.go new file mode 100644 index 0000000000..4744e4fa3b --- /dev/null +++ b/backend/internal/web/http.go @@ -0,0 +1,482 @@ +package web + +import ( + "compress/gzip" + "context" + "encoding/json" + "errors" + "fmt" + "math" + "net" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "time" + + libErrors "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/go-cache/cache" + "golang.org/x/time/rate" +) + +// Context carries per-request state for HTTP handlers. +type Context struct { + User *users.User + ShareUser *users.User + FileInfo iteminfo.ExtendedFileInfo + Token string + Share share.Share + ShareValid bool + Ctx context.Context + MaxBandwidth int + Data interface{} + IndexPath string +} + +// HandleFunc is the signature used by middleware-wrapped handlers. +type HandleFunc func(w http.ResponseWriter, r *http.Request, d *Context) (int, error) + +func effectiveFilePerms(d *Context, sourceName string) (users.SourceFilePermissions, error) { + if d == nil { + return users.DenyAllSourceFilePermissions(), fmt.Errorf("user context not set") + } + var link *share.Share + if d.Share.Hash != "" { + link = &d.Share + } + return share.EffectiveFilePermissions(d.User, link, sourceName) +} + +// HttpResponse is the standard JSON error/success envelope. +type HttpResponse struct { + Status int `json:"status,omitempty"` + Message string `json:"message,omitempty"` + Token string `json:"token,omitempty"` +} + +// ResponseWriterWrapper wraps http.ResponseWriter to capture status code and username. +type ResponseWriterWrapper struct { + http.ResponseWriter + StatusCode int + WroteHeader bool + User string +} + +// Built-in auth rate limits (per process). Toggle all off with http.disableRateLimit. +// +// Credential tier (login, OTP verify): dual token buckets (per IP + per username) plus +// failed-login lockout (per IP+username). Tune burst ≤ maxAttempts so rapid floods hit +// HTTP 429 from the bucket before lockout; lockout covers paced attacks that stay under RPM. +const ( + authCredentialRPM = 10 // sustained ~1 attempt / 6s per IP and per username + authCredentialBurst = 8 // rapid burst; 9th immediate attempt gets 429 + authModerateRPM = 30 // signup, logout, OTP generate + authModerateBurst = 10 + authOIDCRPM = 60 // OIDC redirects (browser-driven, higher ceiling) + authOIDCBurst = 20 + authAuthenticatedRPM = 180 // session/token management for logged-in users + authAuthenticatedBurst = 60 + authFailedLoginMaxAttempts = 8 // lockout after N consecutive 401s (same IP + username) + authFailedLoginLockoutMins = 15 + // Evict idle per-key token buckets so unique IPs/usernames cannot grow without bound. + authLimiterEntryTTL = 24 * time.Hour +) + +// AuthRateLimitKind selects which /api/auth rate limit tier applies (see withRateLimit and withRateLimitChain). +type AuthRateLimitKind int + +const ( + // AuthRateLimitCredential: strict per-IP and per-username limits; no failed-login lockout. + AuthRateLimitCredential AuthRateLimitKind = iota + // AuthRateLimitCredentialLockout: same limits as Credential, plus lockout after repeated 401s. + AuthRateLimitCredentialLockout + AuthRateLimitModerate + AuthRateLimitOIDC + // AuthRateLimitAuthenticated: per logged-in username (compose: withUser(withRateLimitChain(AuthRateLimitAuthenticated, h))). + AuthRateLimitAuthenticated +) + +const authRateKeySep = "\x1e" + +// In-memory failed-attempt counters and lockout flags (per server process). +var ( + authFailCounts = cache.NewCache[int](time.Minute, 10*time.Minute) + authLockouts = cache.NewCache[bool](time.Minute, 10*time.Minute) +) + +// Per-route-class token buckets (keys: IP or username). Expired entries are dropped by go-cache. +var ( + authRateLimitCredentialByIP = cache.NewCache[*rate.Limiter](authLimiterEntryTTL) + authRateLimitCredentialByUsername = cache.NewCache[*rate.Limiter](authLimiterEntryTTL) + authRateLimitModerateByIP = cache.NewCache[*rate.Limiter](authLimiterEntryTTL) + authRateLimitOIDCByIP = cache.NewCache[*rate.Limiter](authLimiterEntryTTL) + authRateLimitAuthenticatedByUser = cache.NewCache[*rate.Limiter](authLimiterEntryTTL) +) + +// ErrToStatus maps domain errors to HTTP status codes. +func ErrToStatus(err error) int { + switch { + case err == nil: + return http.StatusOK + case os.IsPermission(err): + return http.StatusForbidden + case errors.Is(err, libErrors.ErrAccessDenied): + return http.StatusForbidden + case os.IsNotExist(err), err == libErrors.ErrNotExist: + return http.StatusNotFound + case os.IsExist(err), err == libErrors.ErrExist: + return http.StatusConflict + case errors.Is(err, libErrors.ErrPermissionDenied): + return http.StatusForbidden + case errors.Is(err, libErrors.ErrInvalidRequestParams): + return http.StatusBadRequest + case errors.Is(err, libErrors.ErrIsDirectory): + return http.StatusMethodNotAllowed + default: + return http.StatusInternalServerError + } +} + +// RenderJSON writes a JSON response, optionally gzip-compressed. +func RenderJSON(w http.ResponseWriter, r *http.Request, data interface{}, statusCode ...int) (int, error) { + code := http.StatusOK + if len(statusCode) > 0 && statusCode[0] != 0 { + code = statusCode[0] + } + + marsh, err := json.Marshal(data) + if err != nil { + return http.StatusInternalServerError, err + } + payloadSizeKB := len(marsh) / 1024 + w.Header().Set("Content-Type", "application/json; charset=utf-8") + if acceptsGzip(r) && payloadSizeKB > 10 { + w.Header().Set("Content-Encoding", "gzip") + w.WriteHeader(code) + gz := gzip.NewWriter(w) + defer gz.Close() + if _, err := gz.Write(marsh); err != nil { + return http.StatusInternalServerError, err + } + } else { + w.WriteHeader(code) + if _, err := w.Write(marsh); err != nil { + return http.StatusInternalServerError, err + } + } + return code, nil +} + +func acceptsGzip(r *http.Request) bool { + ae := r.Header.Get("Accept-Encoding") + return ae != "" && strings.Contains(ae, "gzip") +} + +// WriteHeader captures the status code and ensures it is only written once. +func (w *ResponseWriterWrapper) WriteHeader(statusCode int) { + if !w.WroteHeader { + if statusCode == 0 { + statusCode = http.StatusInternalServerError + } + w.StatusCode = statusCode + w.ResponseWriter.WriteHeader(statusCode) + w.WroteHeader = true + } +} + +// Write ensures WriteHeader is called before writing the body. +func (w *ResponseWriterWrapper) Write(b []byte) (int, error) { + if !w.WroteHeader { + w.WriteHeader(http.StatusOK) + } + return w.ResponseWriter.Write(b) +} + +// Flush implements http.Flusher when the underlying writer supports it. +func (w *ResponseWriterWrapper) Flush() { + if flusher, ok := w.ResponseWriter.(http.Flusher); ok { + flusher.Flush() + } +} + +// SetUserInResponseWriter records the authenticated username on the wrapper when present. +func SetUserInResponseWriter(w http.ResponseWriter, user *users.User) { + if wrappedWriter, ok := w.(*ResponseWriterWrapper); ok && user != nil { + wrappedWriter.User = user.Username + } +} + +// GetRemoteIP resolves the client IP, honoring trusted proxy headers when configured. +func GetRemoteIP(r *http.Request) string { + cfg := &settings.Config + + xff := r.Header.Get("X-Forwarded-For") + if cfg.Http.TrustProxyHeaders && xff != "" { + ips := strings.Split(xff, ",") + return strings.TrimSpace(ips[0]) + } + + xri := r.Header.Get("X-Real-IP") + if cfg.Http.TrustProxyHeaders && xri != "" { + return xri + } + + ip, _, _ := net.SplitHostPort(r.RemoteAddr) + return ip +} + +// GetScheme returns the request scheme (http or https). +func GetScheme(r *http.Request) string { + return requestScheme(r) +} + +func toASCIIFilename(fileName string) string { + var result strings.Builder + for _, r := range fileName { + if r > 127 { + result.WriteRune('_') + } else { + result.WriteRune(r) + } + } + return result.String() +} + +func SetContentDisposition(w http.ResponseWriter, r *http.Request, fileName string, forceInline bool) { + dispositionType := "attachment" + if forceInline || r.URL.Query().Get("inline") == "true" { + dispositionType = "inline" + w.Header().Set("Content-Security-Policy", "script-src 'none'") + } + asciiFileName := toASCIIFilename(fileName) + encodedFileName := url.PathEscape(fileName) + w.Header().Set("Content-Disposition", fmt.Sprintf("%s; filename=%q; filename*=utf-8''%s", dispositionType, asciiFileName, encodedFileName)) +} + +func IsOnlyOfficeCompatibleFile(fileName string) bool { + return iteminfo.IsOnlyOffice(fileName) +} + +// WithRateLimitChain applies a rate limit tier then fn for nesting inside withUser / withOrWithoutUser / withoutUser. +func WithRateLimitChain(kind AuthRateLimitKind, fn HandleFunc) HandleFunc { + switch kind { + case AuthRateLimitCredential: + return withAuthRateLimitCredential(false, fn) + case AuthRateLimitCredentialLockout: + return withAuthRateLimitCredential(true, fn) + case AuthRateLimitModerate: + return withAuthRateLimitModerate(fn) + case AuthRateLimitOIDC: + return withAuthRateLimitOIDC(fn) + case AuthRateLimitAuthenticated: + return withAuthRateLimitAuthenticated(fn) + default: + return fn + } +} + +func authRateLimitActive() bool { + if settings.Config.Http.DisableRateLimit { + return false + } + if settings.Config.Auth.Methods.NoAuth { + return false + } + return true +} + +func tokenBucketLimiter(c *cache.KeyCache[*rate.Limiter], key string, requestsPerMinute, burst int) *rate.Limiter { + if requestsPerMinute < 1 { + requestsPerMinute = 1 + } + if burst < 1 { + burst = 1 + } + if lim, ok := c.Get(key); ok && lim != nil { + c.SetWithExp(key, lim, authLimiterEntryTTL) + return lim + } + lim := rate.NewLimiter(rate.Limit(float64(requestsPerMinute))/60.0, burst) + c.SetWithExp(key, lim, authLimiterEntryTTL) + return lim +} + +func retryAfterSeconds(lim *rate.Limiter) int { + res := lim.Reserve() + delay := res.Delay() + res.Cancel() + secs := int(math.Ceil(delay.Seconds())) + if secs < 1 { + secs = 1 + } + return secs +} + +func allowCredential(r *http.Request, loginUsername string) (retryAfter int, ok bool) { + ip := GetRemoteIP(r) + limIP := tokenBucketLimiter(authRateLimitCredentialByIP, ip, authCredentialRPM, authCredentialBurst) + if !limIP.Allow() { + return retryAfterSeconds(limIP), false + } + if loginUsername != "" { + limUser := tokenBucketLimiter(authRateLimitCredentialByUsername, loginUsername, authCredentialRPM, authCredentialBurst) + if !limUser.Allow() { + return retryAfterSeconds(limUser), false + } + } + return 0, true +} + +func allowModerate(r *http.Request) (retryAfter int, ok bool) { + ip := GetRemoteIP(r) + lim := tokenBucketLimiter(authRateLimitModerateByIP, ip, authModerateRPM, authModerateBurst) + if !lim.Allow() { + return retryAfterSeconds(lim), false + } + return 0, true +} + +func allowOIDC(r *http.Request) (retryAfter int, ok bool) { + ip := GetRemoteIP(r) + lim := tokenBucketLimiter(authRateLimitOIDCByIP, ip, authOIDCRPM, authOIDCBurst) + if !lim.Allow() { + return retryAfterSeconds(lim), false + } + return 0, true +} + +func allowAuthenticated(username string) (retryAfter int, ok bool) { + lim := tokenBucketLimiter(authRateLimitAuthenticatedByUser, username, authAuthenticatedRPM, authAuthenticatedBurst) + if !lim.Allow() { + return retryAfterSeconds(lim), false + } + return 0, true +} + +func authFailKey(ip, username string) string { + return "fail" + authRateKeySep + ip + authRateKeySep + username +} + +func authLockKey(ip, username string) string { + return "lock" + authRateKeySep + ip + authRateKeySep + username +} + +func authLockoutRetryAfterSecs() int { + return authFailedLoginLockoutMins * 60 +} + +func isAuthLockout(ip, username string) bool { + locked, ok := authLockouts.Get(authLockKey(ip, username)) + return ok && locked +} + +func clearAuthLockout(ip, username string) { + authLockouts.Delete(authLockKey(ip, username)) + authFailCounts.Delete(authFailKey(ip, username)) +} + +func recordAuthFailure(ip, username string) { + if username == "" { + return + } + window := time.Duration(authFailedLoginLockoutMins) * time.Minute + fk := authFailKey(ip, username) + n := 0 + if v, ok := authFailCounts.Get(fk); ok { + n = v + } + n++ + authFailCounts.SetWithExp(fk, n, window) + if n >= authFailedLoginMaxAttempts { + authLockouts.SetWithExp(authLockKey(ip, username), true, window) + } +} + +// withRateLimit registers a rate-limited route (same shape as withTimeout: option first, handler second). +func withRateLimit(kind AuthRateLimitKind, fn HandleFunc) http.HandlerFunc { + return wrapHandler(WithRateLimitChain(kind, fn)) +} + +// withRateLimitChain applies a rate limit tier then fn for nesting inside withUser / withOrWithoutUser / withoutUser. +func withRateLimitChain(kind AuthRateLimitKind, fn HandleFunc) HandleFunc { + return WithRateLimitChain(kind, fn) +} + +func withRateLimitInternal(fn HandleFunc, allow func(*http.Request, *Context) (retryAfter int, ok bool)) HandleFunc { + return func(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if !authRateLimitActive() { + return fn(w, r, d) + } + if after, ok := allow(r, d); !ok { + w.Header().Set("Retry-After", strconv.Itoa(after)) + return http.StatusTooManyRequests, fmt.Errorf("too many requests") + } + return fn(w, r, d) + } +} + +// withAuthRateLimitCredential enforces the credential tier (and optional per-username limits). +// When trackFailures is true, 401 responses increment failed-attempt state for lockout; success clears it. +func withAuthRateLimitCredential(trackFailures bool, fn HandleFunc) HandleFunc { + return func(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if !authRateLimitActive() { + return fn(w, r, d) + } + username := r.URL.Query().Get("username") + if isAuthLockout(GetRemoteIP(r), username) { + w.Header().Set("Retry-After", strconv.Itoa(authLockoutRetryAfterSecs())) + return http.StatusTooManyRequests, fmt.Errorf("too many failed authentication attempts") + } + if after, ok := allowCredential(r, username); !ok { + w.Header().Set("Retry-After", strconv.Itoa(after)) + return http.StatusTooManyRequests, fmt.Errorf("too many requests") + } + status, err := fn(w, r, d) + if !trackFailures { + return status, err + } + ip := GetRemoteIP(r) + if status == http.StatusUnauthorized && username != "" { + recordAuthFailure(ip, username) + } + if err == nil && (status == 0 || status == http.StatusOK) { + clearAuthLockout(ip, username) + } + return status, err + } +} + +func withAuthRateLimitModerate(fn HandleFunc) HandleFunc { + return withRateLimitInternal(fn, func(r *http.Request, _ *Context) (int, bool) { + return allowModerate(r) + }) +} + +func withAuthRateLimitOIDC(fn HandleFunc) HandleFunc { + return withRateLimitInternal(fn, func(r *http.Request, _ *Context) (int, bool) { + return allowOIDC(r) + }) +} + +func withAuthRateLimitAuthenticated(fn HandleFunc) HandleFunc { + return withRateLimitInternal(fn, func(_ *http.Request, d *Context) (int, bool) { + if d.User == nil || d.User.Username == "" || d.User.Username == "anonymous" { + return 0, true + } + return allowAuthenticated(d.User.Username) + }) +} + +// healthHandler returns a simple JSON health check response. +func healthHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + response := HttpResponse{Message: "ok"} + if err := json.NewEncoder(w).Encode(response); err != nil { + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + } +} diff --git a/backend/http/httpEvents.go b/backend/internal/web/httpEvents.go similarity index 59% rename from backend/http/httpEvents.go rename to backend/internal/web/httpEvents.go index b0984f5bf1..f773dc4d38 100644 --- a/backend/http/httpEvents.go +++ b/backend/internal/web/httpEvents.go @@ -1,4 +1,4 @@ -package http +package web import ( "encoding/json" @@ -8,17 +8,23 @@ import ( "sync" "time" - "github.com/gtsteffaniak/filebrowser/backend/events" + "github.com/gtsteffaniak/filebrowser/backend/internal/events" "github.com/gtsteffaniak/go-logger/logger" ) -type messenger struct { +// Messenger streams Server-Sent Events to a client. +type Messenger struct { flusher http.Flusher writer io.Writer } -// expects message with double quotes around string -func (msgr messenger) sendEvent(eventType, message string) error { +// NewMessenger creates an SSE messenger for the given writer/flusher pair. +func NewMessenger(flusher http.Flusher, writer io.Writer) Messenger { + return Messenger{flusher: flusher, writer: writer} +} + +// SendEvent writes one SSE data frame. +func (msgr Messenger) SendEvent(eventType, message string) error { _, err := fmt.Fprintf(msgr.writer, "data: {\"eventType\":\"%s\",\"message\":%s}\n\n", eventType, message) if err != nil { return err @@ -27,8 +33,9 @@ func (msgr messenger) sendEvent(eventType, message string) error { return nil } -func sseHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !(d.user.Permissions.Realtime || d.user.Permissions.Admin) { +// SSEHandler streams server events to authenticated users with realtime permission. +func SSEHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if !(d.User.Permissions.Realtime || d.User.Permissions.Admin) { return http.StatusForbidden, fmt.Errorf("realtime is disabled for this user") } @@ -38,7 +45,7 @@ func sseHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, w.Header().Set("Access-Control-Allow-Origin", "*") sessionId := r.URL.Query().Get("sessionId") - username := d.user.Username + username := d.User.Username f, ok := w.(http.Flusher) if !ok { @@ -46,39 +53,35 @@ func sseHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, return http.StatusInternalServerError, fmt.Errorf("streaming not supported") } - msgr := messenger{flusher: f, writer: w} + msgr := NewMessenger(f, w) clientGone := r.Context().Done() - // Initial ack - if err := msgr.sendEvent("acknowledge", "\"connection established\""); err != nil { + if err := msgr.SendEvent("acknowledge", "\"connection established\""); err != nil { return http.StatusInternalServerError, fmt.Errorf("error sending message: %v, user: %s, SessionId: %s", err, username, sessionId) } - // Register this client with the events system - sendChan := events.Register(username, d.user.GetSourceNames()) + sendChan := events.Register(username, d.User.GetSourceNames()) defer events.Unregister(username, sendChan) - // Heartbeat ticker - send every 30 seconds to keep connection alive heartbeatTicker := time.NewTicker(30 * time.Second) defer heartbeatTicker.Stop() for { select { - case <-d.ctx.Done(): - _ = msgr.sendEvent("notification", "\"the server is shutting down\"") + case <-d.Ctx.Done(): + _ = msgr.SendEvent("notification", "\"the server is shutting down\"") return http.StatusOK, nil case <-clientGone: return http.StatusOK, nil case <-heartbeatTicker.C: - // Send minimal heartbeat message (ignored by frontend) - if err := msgr.sendEvent("heartbeat", "\"hb\""); err != nil { + if err := msgr.SendEvent("heartbeat", "\"hb\""); err != nil { return http.StatusInternalServerError, fmt.Errorf("error sending heartbeat: %v, user: %s", err, username) } case msg := <-events.BroadcastChan: - if err := msgr.sendEvent(msg.EventType, msg.Message); err != nil { + if err := msgr.SendEvent(msg.EventType, msg.Message); err != nil { return http.StatusInternalServerError, fmt.Errorf("error sending broadcast: %v, user: %s", err, username) } @@ -86,14 +89,14 @@ func sseHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, if !ok { return http.StatusOK, nil } - if err := msgr.sendEvent(msg.EventType, msg.Message); err != nil { + if err := msgr.SendEvent(msg.EventType, msg.Message); err != nil { return http.StatusInternalServerError, fmt.Errorf("error sending targeted message: %v, user: %s", err, username) } } } } -// OnlyOfficeLogContext stores context for OnlyOffice operations +// OnlyOfficeLogContext stores context for OnlyOffice operations. type OnlyOfficeLogContext struct { Username string SessionID string @@ -105,24 +108,13 @@ type OnlyOfficeLogContext struct { StartTime time.Time } -// OnlyOfficeLogEvent represents a log event for SSE -type OnlyOfficeLogEvent struct { - EventType string `json:"eventType"` - DocumentID string `json:"documentId"` - Username string `json:"username"` - SessionID string `json:"sessionId"` - LogLevel string `json:"logLevel"` - Message string `json:"message"` - Timestamp string `json:"timestamp"` - Component string `json:"component"` -} +var ( + onlyOfficeContexts = make(map[string]*OnlyOfficeLogContext) + onlyOfficeContextsMutex sync.RWMutex +) -// Global map to store OnlyOffice log contexts -var onlyOfficeContexts = make(map[string]*OnlyOfficeLogContext) -var onlyOfficeContextsMutex sync.RWMutex - -// Helper functions for OnlyOffice log context management -func createOnlyOfficeLogContext(username, sessionID, documentID, filePath, source, shareHash string, isAdmin bool) *OnlyOfficeLogContext { +// CreateOnlyOfficeLogContext stores metadata for an OnlyOffice editing session. +func CreateOnlyOfficeLogContext(username, sessionID, documentID, filePath, source, shareHash string, isAdmin bool) *OnlyOfficeLogContext { return &OnlyOfficeLogContext{ Username: username, SessionID: sessionID, @@ -135,33 +127,33 @@ func createOnlyOfficeLogContext(username, sessionID, documentID, filePath, sourc } } -func storeOnlyOfficeLogContext(documentID string, context *OnlyOfficeLogContext) { +// StoreOnlyOfficeLogContext registers a log context by document ID. +func StoreOnlyOfficeLogContext(documentID string, context *OnlyOfficeLogContext) { onlyOfficeContextsMutex.Lock() defer onlyOfficeContextsMutex.Unlock() onlyOfficeContexts[documentID] = context } -func getOnlyOfficeLogContext(documentID string) *OnlyOfficeLogContext { +// GetOnlyOfficeLogContext returns a stored log context. +func GetOnlyOfficeLogContext(documentID string) *OnlyOfficeLogContext { onlyOfficeContextsMutex.RLock() defer onlyOfficeContextsMutex.RUnlock() return onlyOfficeContexts[documentID] } -func removeOnlyOfficeLogContext(documentID string) { +// RemoveOnlyOfficeLogContext drops a stored log context. +func RemoveOnlyOfficeLogContext(documentID string) { onlyOfficeContextsMutex.Lock() defer onlyOfficeContextsMutex.Unlock() delete(onlyOfficeContexts, documentID) } -func sendOnlyOfficeLogEvent(context *OnlyOfficeLogContext, level, component, message string) { - if context == nil { - return - } - if !context.isAdmin { +// SendOnlyOfficeLogEvent emits an OnlyOffice log event over SSE. +func SendOnlyOfficeLogEvent(context *OnlyOfficeLogContext, level, component, message string) { + if context == nil || !context.isAdmin { return } - // Create the log event message logData := map[string]interface{}{ "documentId": context.DocumentID, "username": context.Username, @@ -172,13 +164,14 @@ func sendOnlyOfficeLogEvent(context *OnlyOfficeLogContext, level, component, mes "component": component, } - // Convert to JSON jsonData, err := json.Marshal(logData) if err != nil { logger.Errorf("Failed to marshal OnlyOffice log event: %v", err) return } - // Send to specific user only (not broadcast to all users) - events.SendToUsers("onlyOfficeLog", string(jsonData), []string{context.Username}) + events.BroadcastChan <- events.EventMessage{ + EventType: "onlyOfficeLog", + Message: string(jsonData), + } } diff --git a/backend/internal/web/httpRouter.go b/backend/internal/web/httpRouter.go new file mode 100644 index 0000000000..b61ee62c66 --- /dev/null +++ b/backend/internal/web/httpRouter.go @@ -0,0 +1,207 @@ +package web + +import ( + "fmt" + "net/http" + "time" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +const ( + time60s = 60 * time.Second + time30s = 30 * time.Second + time10s = 10 * time.Second + time5s = 5 * time.Second +) + +// configureHTTPRouter registers all API, public, and static routes. +func configureHTTPRouter(router, api, publicRoutes, publicApi *http.ServeMux) { + // health routes + api.HandleFunc("GET /health", healthHandler) + publicApi.HandleFunc("GET /health", healthHandler) + + // ======================================== + // User Routes - /api/users/ (with public routes) + // ======================================== + api.HandleFunc("GET /users", withUser(userGetHandler)) + api.HandleFunc("POST /users", withSelfOrAdmin(usersPostHandler)) + api.HandleFunc("PATCH /users", withUser(userPatchHandler)) + api.HandleFunc("PATCH /users/pinned-items", withUser(userPatchPinnedItemsHandler)) + api.HandleFunc("DELETE /users", withSelfOrAdmin(userDeleteHandler)) + publicApi.HandleFunc("GET /users", withUser(userGetHandler)) + + // ======================================== + // Auth Routes - /api/auth/ + // ======================================== + api.HandleFunc("POST /auth/login", withRateLimit(AuthRateLimitCredentialLockout, loginHelper(loginHandler))) + 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))) + api.HandleFunc("POST /auth/otp/verify", withOrWithoutUser(withRateLimitChain(AuthRateLimitCredentialLockout, verifyOTPHandler))) + api.HandleFunc("POST /auth/renew", withUser(withRateLimitChain(AuthRateLimitAuthenticated, renewHandler))) + api.HandleFunc("POST /auth/token", withUser(withRateLimitChain(AuthRateLimitAuthenticated, createApiTokenHandler))) + api.HandleFunc("DELETE /auth/token", withUser(withRateLimitChain(AuthRateLimitAuthenticated, deleteApiTokenHandler))) + api.HandleFunc("GET /auth/token/list", withUser(withRateLimitChain(AuthRateLimitAuthenticated, listApiTokensHandler))) + api.HandleFunc("GET /auth/token", withUser(withRateLimitChain(AuthRateLimitAuthenticated, getApiTokenHandler))) + api.HandleFunc("GET /auth/oidc/callback", withRateLimit(AuthRateLimitOIDC, oidcCallbackHandler)) + api.HandleFunc("GET /auth/oidc/login", withRateLimit(AuthRateLimitOIDC, oidcLoginHandler)) + api.HandleFunc("POST /auth/webauthn/begin-login", withoutUser(withRateLimitChain(AuthRateLimitCredential, beginPasskeyLoginHandler))) + api.HandleFunc("POST /auth/webauthn/finish-login", withoutUser(withRateLimitChain(AuthRateLimitCredential, finishPasskeyLoginHandler))) + api.HandleFunc("POST /auth/webauthn/begin-register", withUser(withRateLimitChain(AuthRateLimitAuthenticated, beginPasskeyRegistrationHandler))) + api.HandleFunc("POST /auth/webauthn/finish-register", withUser(withRateLimitChain(AuthRateLimitAuthenticated, finishPasskeyRegistrationHandler))) + api.HandleFunc("DELETE /auth/webauthn/{id}", withUser(withRateLimitChain(AuthRateLimitAuthenticated, deletePasskeyCredentialHandler))) + + // ======================================== + // Resources Routes - /api/resources/ (with public routes) + // ======================================== + api.HandleFunc("GET /resources", withUser(resourceGetHandler)) + api.HandleFunc("GET /resources/items", withUser(itemsGetHandler)) + api.HandleFunc("DELETE /resources", withUser(resourceDeleteHandler)) + api.HandleFunc("POST /resources", withUser(ResourcePostHandler)) + api.HandleFunc("PUT /resources", withUser(resourcePutHandler)) + api.HandleFunc("PATCH /resources", withUser(ResourcePatchHandler)) + api.HandleFunc("DELETE /resources/bulk", withUser(ResourceBulkDeleteHandler)) + api.HandleFunc("POST /resources/archive", withUser(archiveCreateHandler)) + api.HandleFunc("POST /resources/unarchive", withUser(unarchiveHandler)) + api.HandleFunc("GET /resources/download", withUser(downloadHandler)) + api.HandleFunc("POST /resources/view-token", withOrWithoutUser(viewTokenHandler)) + api.HandleFunc("GET /resources/view", withTimeout(time60s, withUserHelper(viewHandler))) + api.HandleFunc("GET /resources/preview", withTimeout(time30s, withUserHelper(previewHandler))) + api.HandleFunc("POST /resources/pause", withUser(resourcePauseHandler)) + publicApi.HandleFunc("GET /resources", withHashFile(publicGetResourceHandler)) + publicApi.HandleFunc("GET /resources/items", withHashFile(publicItemsGetHandler)) + publicApi.HandleFunc("POST /resources", withHashFile(publicUploadHandler)) + publicApi.HandleFunc("PUT /resources", withHashFile(publicPutHandler)) + publicApi.HandleFunc("DELETE /resources", withHashFile(publicDeleteHandler)) + publicApi.HandleFunc("DELETE /resources/bulk", withHashFile(publicBulkDeleteHandler)) + publicApi.HandleFunc("PATCH /resources", withHashFile(publicPatchHandler)) + publicApi.HandleFunc("GET /resources/download", withHashFile(publicDownloadHandler)) + publicApi.HandleFunc("POST /resources/view-token", withHashFile(viewTokenHandler)) + publicApi.HandleFunc("GET /resources/view", withTimeout(time60s, withHashFileHelper(PublicViewHandler))) + publicApi.HandleFunc("GET /resources/preview", withTimeout(time30s, withHashFileHelper(publicPreviewHandler))) + publicApi.HandleFunc("POST /resources/pause", withHashFile(PublicPauseHandler)) + // Legacy routes (backwards compatibility) + api.HandleFunc("GET /raw", withUser(downloadHandler)) + publicApi.HandleFunc("GET /raw", withHashFile(publicDownloadHandler)) + + // ======================================== + // Access Routes - /api/access/ + // ======================================== + api.HandleFunc("GET /access", withAdmin(accessGetHandler)) + api.HandleFunc("POST /access", withAdmin(accessPostHandler)) + api.HandleFunc("PATCH /access", withAdmin(accessPatchHandler)) + api.HandleFunc("DELETE /access", withAdmin(accessDeleteHandler)) + api.HandleFunc("GET /access/groups", withAdmin(groupGetHandler)) + api.HandleFunc("POST /access/group", withAdmin(groupPostHandler)) + api.HandleFunc("DELETE /access/group", withAdmin(groupDeleteHandler)) + + // ======================================== + // Share Routes - /api/share/ + // ======================================== + api.HandleFunc("GET /share/list", withPermShare(shareListHandler)) + api.HandleFunc("GET /share/direct", withPermShare(shareDirectDownloadHandler)) + api.HandleFunc("GET /share", withUser(shareGetHandler)) + api.HandleFunc("POST /share", withPermShare(sharePostHandler)) + api.HandleFunc("PATCH /share", withPermShare(sharePatchHandler)) + api.HandleFunc("DELETE /share", withPermShare(shareDeleteHandler)) + publicApi.HandleFunc("GET /share/info", withOrWithoutUser(shareInfoHandler)) + publicApi.HandleFunc("PATCH /share/pinned-items", withPermShare(sharePatchPinnedItemsHandler)) + publicApi.HandleFunc("GET /share/image", withHashFile(getShareImage)) + + // ======================================== + // Settings Routes - /api/settings/ + // ======================================== + api.HandleFunc("GET /settings", withAdmin(settingsGetHandler)) + api.HandleFunc("GET /settings/config", withAdmin(settingsConfigHandler)) + api.HandleFunc("GET /settings/analytics", withTimeout(time5s, withAdminHelper(settingsAnalyticsGetHandler))) + api.HandleFunc("PUT /settings/analytics", withTimeout(time5s, withAdminHelper(settingsAnalyticsUpdateHandler))) + api.HandleFunc("PATCH /settings/analytics", withTimeout(time5s, withAdminHelper(settingsAnalyticsUpdateHandler))) + api.HandleFunc("GET /settings/analytics/preview", withTimeout(time30s, withAdminHelper(settingsAnalyticsPreviewHandler))) + api.HandleFunc("GET /settings/user-defaults", withTimeout(time5s, withUserHelper(settingsUserDefaultsGetHandler))) + api.HandleFunc("PATCH /settings/user-defaults", withTimeout(time5s, withAdminHelper(settingsUserDefaultsPatchHandler))) + publicApi.HandleFunc("GET /settings/user-defaults", withTimeout(time5s, withUserHelper(settingsUserDefaultsGetHandler))) + api.HandleFunc("GET /settings/source", withTimeout(time5s, withUserHelper(settingsSourceGetHandler))) + api.HandleFunc("PATCH /settings/source", withTimeout(time5s, withAdminHelper(settingsSourcePatchHandler))) + api.HandleFunc("GET /settings/sources", withUser(getSourceInfoHandler)) + + // ======================================== + // Tools Routes - /api/tools/ + // ======================================== + api.HandleFunc("GET /tools/search", withUser(searchHandler)) + api.HandleFunc("GET /tools/duplicate-finder", withUser(duplicatesHandler)) + api.HandleFunc("GET /tools/file-watcher", withUser(fileWatchHandler)) + api.HandleFunc("GET /tools/file-watcher/sse", withUser(fileWatchSSEHandler)) + api.HandleFunc("GET /tools/activity", withUser(ListHandler)) + api.HandleFunc("GET /tools/activity/grouped", withUser(GroupedHandler)) + api.HandleFunc("GET /tools/activity/export", withUser(ExportHandler)) + + // ======================================== + // Media Routes - /api/media/ (with public routes) + // ======================================== + api.HandleFunc("GET /media/subtitles", withTimeout(time60s, withUserHelper(subtitlesHandler))) + api.HandleFunc("GET /media/metadata", withTimeout(time60s, withUserHelper(metadataHandler))) + api.HandleFunc("GET /media/lyrics", withTimeout(time60s, withUserHelper(lyricsHandler))) + api.HandleFunc("GET /media/stream", withTimeout(time60s, withUserHelper(streamHandler))) + publicApi.HandleFunc("GET /media/metadata", withTimeout(time60s, withHashFileHelper(publicMetadataHandler))) + publicApi.HandleFunc("GET /media/lyrics", withTimeout(time60s, withHashFileHelper(publicLyricsHandler))) + publicApi.HandleFunc("GET /media/stream", withTimeout(time60s, withHashFileHelper(publicStreamHandler))) + + // ======================================== + // OnlyOffice Routes - /api/office/ (with public routes) + // ======================================== + api.HandleFunc("GET /office/config", withUser(onlyofficeClientConfigGetHandler)) + api.HandleFunc("POST /office/callback", withUser(onlyofficeCallbackHandler)) + api.HandleFunc("GET /office/callback", withUser(onlyofficeCallbackHandler)) + publicApi.HandleFunc("POST /office/callback", withHashFile(onlyofficeCallbackHandler)) + publicApi.HandleFunc("GET /office/callback", withHashFile(onlyofficeCallbackHandler)) + publicApi.HandleFunc("GET /office/config", withHashFile(onlyofficeClientConfigGetHandler)) + + // ======================================== + // Misc Routes + // ======================================== + api.HandleFunc("GET /events", withUser(SSEHandler)) + if settings.Env.IsDevMode { + api.HandleFunc("GET /inspect-index", inspectIndex) + api.HandleFunc("GET /mock-data", mockData) + } + + // Mount public API + publicRoutes.Handle("/api/", http.StripPrefix("/api", publicApi)) + + // ======================================== + // Configure Main Router + // ======================================== + apiPath := settings.Config.Http.BaseURL + "api" + publicPath := settings.Config.Http.BaseURL + "public" + webDavPath := settings.Config.Http.BaseURL + "dav" + + // Mount primary API and public routes + router.Handle(apiPath+"/", http.StripPrefix(apiPath, api)) + router.Handle(publicPath+"/", http.StripPrefix(publicPath, publicRoutes)) + + // WebDAV handler + if !settings.Config.Http.DisableWebDAV { + // Uses Basic Auth where password is JWT token + // Note: do not trim /dav prefix here - webdav library requires it + router.Handle(webDavPath+"/{source}/{path...}", withBasicAuth(webDAVHandler)) + } + + publicRoutes.HandleFunc("GET /share/", withOrWithoutUser(indexHandler)) + + // Static assets + publicRoutes.Handle("GET /static/", http.HandlerFunc(staticAssetHandler)) + router.HandleFunc("GET /favicon.svg", http.HandlerFunc(staticAssetHandler)) + + // Index and utility routes + router.HandleFunc(settings.Config.Http.BaseURL, withOrWithoutUser(indexHandler)) + router.HandleFunc(fmt.Sprintf("GET %vhealth", settings.Config.Http.BaseURL), healthHandler) + router.Handle(fmt.Sprintf("%vswagger/", settings.Config.Http.BaseURL), withUser(swaggerHandler)) + + // Base URL redirect (non-root deployments) + if settings.Config.Http.BaseURL != "/" { + router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, settings.Config.Http.BaseURL, http.StatusMovedPermanently) + }) + } +} diff --git a/backend/http/ldap.go b/backend/internal/web/ldap.go similarity index 81% rename from backend/http/ldap.go rename to backend/internal/web/ldap.go index 0f1a04f8a7..fa3d053ddc 100644 --- a/backend/http/ldap.go +++ b/backend/internal/web/ldap.go @@ -1,4 +1,4 @@ -package http +package web import ( "crypto/tls" @@ -6,11 +6,10 @@ import ( "strings" ldap "github.com/go-ldap/ldap/v3" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/database/storage" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" "github.com/gtsteffaniak/go-logger/logger" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + ) // AuthenticateLDAPUser attempts LDAP authentication and returns the filebrowser user if successful. @@ -26,7 +25,7 @@ func AuthenticateLDAPUser(username, password string) (*users.User, error) { } // Use the configured UserIdentifier if available, otherwise use the login username - ldapCfg := config.Auth.Methods.LdapAuth + ldapCfg := settings.Config.Auth.Methods.LdapAuth mappedUsername := username if ldapCfg.UserIdentifier != "" { if val, ok := userAttributes[ldapCfg.UserIdentifier]; ok && val != "" { @@ -42,7 +41,7 @@ func AuthenticateLDAPUser(username, password string) (*users.User, error) { } func authenticateLDAP(username, password string) ([]string, map[string]string, error) { - c := config.Auth.Methods.LdapAuth + c := settings.Config.Auth.Methods.LdapAuth logger.Debugf("ldap: connecting to %s", c.Server) var opts []ldap.DialOpt @@ -186,7 +185,7 @@ func ldapGroupMatchesAdmin(groupDN, adminGroup string) bool { // getOrCreateLdapUser returns the filebrowser user for an LDAP-authenticated username, creating one if configured. func getOrCreateLdapUser(username string, groups []string) (*users.User, error) { logger.Debugf("getting or creating ldap user %s", username) - ldapCfg := config.Auth.Methods.LdapAuth + ldapCfg := settings.Config.Auth.Methods.LdapAuth // Check if user is in required groups (if userGroups is configured) if len(ldapCfg.UserGroups) > 0 { @@ -220,44 +219,10 @@ func getOrCreateLdapUser(username string, groups []string) (*users.User, error) if isAdmin { logger.Debugf("User %s is in admin group %s, granting admin privileges.", username, ldapCfg.AdminGroup) } - } - - user, err := store.Users.Get(username) - if err != nil { - if err.Error() != "the resource does not exist" { - return nil, err - } - // Auto-create user on first LDAP authentication - if ldapCfg.AdminGroup == "" { - isAdmin = config.UserDefaults.Account.Permissions.Admin - } - user = &users.User{ - Username: username, - LoginMethod: users.LoginMethodLdap, - } - settings.ApplyUserDefaults(user) - if isAdmin { - user.Permissions.Admin = true - } - if err = storage.CreateUser(*user, user.Permissions); err != nil { - return nil, err - } - user, err = store.Users.Get(username) - if err != nil { - return nil, err - } } else { - if user.LoginMethod != users.LoginMethodLdap { - return nil, errors.ErrWrongLoginMethod - } - if ldapCfg.AdminGroup != "" && isAdmin != user.Permissions.Admin { - user.Permissions.Admin = isAdmin - _ = store.Users.Update(user, true, "Permissions") - } + // If no admin group configured, use default permissions + isAdmin = settings.Config.UserDefaults.Account.Permissions.Admin } - if err := store.Access.SyncUserGroups(username, groups); err != nil { - logger.Warningf("failed to sync ldap user %s groups: %v", username, err) - } - return user, nil + return getOrCreateAuthenticatedUser(username, users.LoginMethodLdap, isAdmin, groups) } diff --git a/backend/http/ldap_test.go b/backend/internal/web/ldap_test.go similarity index 99% rename from backend/http/ldap_test.go rename to backend/internal/web/ldap_test.go index a4865b4584..404c68a787 100644 --- a/backend/http/ldap_test.go +++ b/backend/internal/web/ldap_test.go @@ -1,4 +1,4 @@ -package http +package web import ( "testing" diff --git a/backend/http/media.go b/backend/internal/web/media.go similarity index 74% rename from backend/http/media.go rename to backend/internal/web/media.go index 21b868c671..3b829169c9 100644 --- a/backend/http/media.go +++ b/backend/internal/web/media.go @@ -1,4 +1,4 @@ -package http +package web import ( "bytes" @@ -9,15 +9,17 @@ import ( "strings" "time" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/ffmpeg" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/internal/ffmpeg" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + ) // subtitlesHandler handles subtitle requests for both external files and embedded streams // @Summary Get subtitle content // @Description Returns raw subtitle content from external files or embedded streams -// @Tags Resources +// @Tags Media // @Accept json // @Produce text/plain // @Param path query string true "Index path to the video file" @@ -30,7 +32,7 @@ import ( // @Failure 404 {object} map[string]string "Resource not found" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/media/subtitles [get] -func subtitlesHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func subtitlesHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { path := r.URL.Query().Get("path") source := r.URL.Query().Get("source") name := r.URL.Query().Get("name") @@ -42,6 +44,13 @@ func subtitlesHandler(w http.ResponseWriter, r *http.Request, d *requestContext) if name == "" { return http.StatusBadRequest, fmt.Errorf("name parameter is required") } + filePerms, err := effectiveFilePerms(d, source) + 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") + } fileInfo, err := files.FileInfoFaster(utils.FileOptions{ FollowSymlinks: true, @@ -50,13 +59,13 @@ func subtitlesHandler(w http.ResponseWriter, r *http.Request, d *requestContext) Expand: true, Content: false, Metadata: true, - ExtractEmbeddedSubtitles: config.Integrations.Media.ExtractEmbeddedSubtitles, - ShowHidden: d.user.ShowHidden, - HideFileExt: d.user.HideFileExt, + ExtractEmbeddedSubtitles: settings.Config.Integrations.Media.ExtractEmbeddedSubtitles, + ShowHidden: d.User.ShowHidden, + HideFileExt: d.User.HideFileExt, SkipExtendedAttrs: false, - }, store.Access, d.user, store.Share) + }, d.User) if err != nil { - return errToStatus(err), err + return ErrToStatus(err), err } if !strings.HasPrefix(fileInfo.Type, "video") { return http.StatusNotFound, fmt.Errorf("file is not a video") @@ -78,7 +87,11 @@ func subtitlesHandler(w http.ResponseWriter, r *http.Request, d *requestContext) if track.Index == nil { return http.StatusNotFound, fmt.Errorf("embedded subtitle track '%s' not found", name) } - content, err = ffmpeg.ExtractSubtitleContent(fileInfo.RealPath, *track.Index) + svc := ffmpeg.Get() + if svc == nil { + return http.StatusInternalServerError, fmt.Errorf("ffmpeg service not available") + } + content, err = svc.ExtractSubtitle(r.Context(), fileInfo.RealPath, *track.Index) if err != nil { return http.StatusInternalServerError, fmt.Errorf("failed to extract embedded subtitle: %v", err) } @@ -106,7 +119,7 @@ func findSubtitleTrack(subtitles []utils.SubtitleTrack, name string, embedded bo // for client-side patching after a fast listing load. // @Summary Directory with media metadata // @Description Same ExtendedFileInfo as resources GET with metadata=true (typically used for directories). -// @Tags Resources +// @Tags Media // @Accept json // @Produce json // @Param path query string true "Path to the directory or file" @@ -116,9 +129,16 @@ func findSubtitleTrack(subtitles []utils.SubtitleTrack, name string, embedded bo // @Failure 403 {object} map[string]string "Forbidden" // @Failure 404 {object} map[string]string "Not found" // @Router /api/media/metadata [get] -func metadataHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func metadataHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { path := r.URL.Query().Get("path") source := r.URL.Query().Get("source") + filePerms, err := effectiveFilePerms(d, source) + 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") + } albumArt := r.URL.Query().Get("albumArt") == "true" fileInfo, err := files.FileInfoFaster(utils.FileOptions{ FollowSymlinks: true, @@ -128,34 +148,34 @@ func metadataHandler(w http.ResponseWriter, r *http.Request, d *requestContext) Content: false, Metadata: true, AlbumArt: albumArt, - ExtractEmbeddedSubtitles: config.Integrations.Media.ExtractEmbeddedSubtitles, - ShowHidden: d.user.ShowHidden, - HideFileExt: d.user.HideFileExt, + ExtractEmbeddedSubtitles: settings.Config.Integrations.Media.ExtractEmbeddedSubtitles, + ShowHidden: d.User.ShowHidden, + HideFileExt: d.User.HideFileExt, SkipExtendedAttrs: false, ShowSharedAttr: true, - }, store.Access, d.user, store.Share) + }, d.User) if err != nil { - return errToStatus(err), err + return ErrToStatus(err), err } - return renderJSON(w, r, fileInfo) + return RenderJSON(w, r, fileInfo) } // publicMetadataHandler is the share-link variant of metadataHandler. // @Summary Directory with media metadata (public share) -// @Tags Shares +// @Tags Media // @Produce json // @Param hash query string true "Share hash" // @Param path query string false "Path within the share" // @Param albumArt query bool false "When true, include embedded album art bytes in audio metadata (heavier)" // @Success 200 {object} iteminfo.ExtendedFileInfo // @Router /public/api/media/metadata [get] -func publicMetadataHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if d.share.ShareType == "upload" { +func publicMetadataHandler(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") } path := r.URL.Query().Get("path") albumArt := r.URL.Query().Get("albumArt") == "true" - sourceCfg, ok := config.Server.SourceMap[d.share.Source] + sourceCfg, ok := settings.Config.Server.SourceMap[d.Share.SourcePath] if !ok { return http.StatusNotFound, fmt.Errorf("source not found") } @@ -166,22 +186,22 @@ func publicMetadataHandler(w http.ResponseWriter, r *http.Request, d *requestCon Content: false, Metadata: true, AlbumArt: albumArt, - ExtractEmbeddedSubtitles: config.Integrations.Media.ExtractEmbeddedSubtitles && d.share.ExtractEmbeddedSubtitles, - ShowHidden: d.share.ShowHidden, - HideFileExt: d.user.HideFileExt, + ExtractEmbeddedSubtitles: settings.Config.Integrations.Media.ExtractEmbeddedSubtitles && d.Share.ExtractEmbeddedSubtitles, + ShowHidden: d.Share.ShowHidden, + HideFileExt: d.User.HideFileExt, FollowSymlinks: false, - }, store.Access, d.shareUser, store.Share) + }, d.ShareUser) if err != nil { - return errToStatus(err), err + return ErrToStatus(err), err } fileInfo.Path = utils.AddTrailingSlashIfNotExists(path) - return renderJSON(w, r, fileInfo) + return RenderJSON(w, r, fileInfo) } // lyricsHandler returns synced/unsynced lyrics (with or without timestamps) for an audio file (embedded or from .lrc files). // @Summary Get lyrics for an audio file // @Description Returns parsed lyrics with optional timestamps from embedded tags or sidecar .lrc files. -// @Tags Resources +// @Tags Media // @Accept json // @Produce json // @Param path query string true "Path to the directory or file" @@ -190,12 +210,19 @@ func publicMetadataHandler(w http.ResponseWriter, r *http.Request, d *requestCon // @Failure 403 {object} map[string]string "Forbidden" // @Failure 404 {object} map[string]string "Not found" // @Router /api/media/lyrics [get] -func lyricsHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +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 == "" { return http.StatusBadRequest, fmt.Errorf("path and source are required") } + filePerms, err := effectiveFilePerms(d, source) + 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") + } fileInfo, err := files.FileInfoFaster(utils.FileOptions{ FollowSymlinks: true, @@ -204,12 +231,12 @@ func lyricsHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i Expand: true, Content: false, Metadata: false, - ShowHidden: d.user.ShowHidden, - HideFileExt: d.user.HideFileExt, + ShowHidden: d.User.ShowHidden, + HideFileExt: d.User.HideFileExt, SkipExtendedAttrs: false, - }, store.Access, d.user, store.Share) + }, d.User) if err != nil { - return errToStatus(err), err + return ErrToStatus(err), err } if !strings.HasPrefix(fileInfo.Type, "audio") { return http.StatusNotFound, fmt.Errorf("file is not an audio file") @@ -219,12 +246,12 @@ func lyricsHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i if err != nil { return http.StatusInternalServerError, fmt.Errorf("failed to extract lyrics: %v", err) } - return renderJSON(w, r, map[string]any{"lyrics": lyrics}) + return RenderJSON(w, r, map[string]any{"lyrics": lyrics}) } // publicLyricsHandler is the share-link variant of lyricsHandler. // @Summary Get lyrics for an audio file (public share) -// @Tags Shares +// @Tags Media // @Produce json // @Param hash query string true "Share hash" // @Param path query string false "Path within the share" @@ -232,8 +259,8 @@ func lyricsHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i // @Failure 403 {object} map[string]string "Forbidden" // @Failure 404 {object} map[string]string "Not found" // @Router /public/api/media/lyrics [get] -func publicLyricsHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - sourceCfg, ok := config.Server.SourceMap[d.share.Source] +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") } @@ -244,13 +271,13 @@ func publicLyricsHandler(w http.ResponseWriter, r *http.Request, d *requestConte Expand: true, Content: false, Metadata: false, - ShowHidden: d.share.ShowHidden, - HideFileExt: d.user.HideFileExt, + ShowHidden: d.Share.ShowHidden, + HideFileExt: d.User.HideFileExt, FollowSymlinks: false, SkipExtendedAttrs: false, - }, store.Access, d.shareUser, store.Share) + }, d.ShareUser) if err != nil { - return errToStatus(err), err + return ErrToStatus(err), err } if !strings.HasPrefix(fileInfo.Type, "audio") { return http.StatusNotFound, fmt.Errorf("file is not an audio file") @@ -260,5 +287,5 @@ func publicLyricsHandler(w http.ResponseWriter, r *http.Request, d *requestConte if err != nil { return http.StatusInternalServerError, errors.New("failed to extract lyrics") } - return renderJSON(w, r, map[string]any{"lyrics": lyrics}) + return RenderJSON(w, r, map[string]any{"lyrics": lyrics}) } diff --git a/backend/http/middleware.go b/backend/internal/web/middleware.go similarity index 65% rename from backend/http/middleware.go rename to backend/internal/web/middleware.go index a7bed5e476..3e64f46ed3 100644 --- a/backend/http/middleware.go +++ b/backend/internal/web/middleware.go @@ -1,97 +1,94 @@ -package http +package web import ( - "compress/gzip" "context" "encoding/json" "fmt" - "net" "net/http" "net/url" - "path/filepath" "runtime" "slices" "strings" "time" jwt "github.com/golang-jwt/jwt/v4" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files" - "github.com/gtsteffaniak/filebrowser/backend/auth" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/share" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/internal/auth" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + "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/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" "github.com/gtsteffaniak/go-logger/logger" ) -type requestContext struct { - user *users.User - shareUser *users.User - fileInfo iteminfo.ExtendedFileInfo - token string - share *share.Link - ctx context.Context - MaxBandwidth int - Data interface{} - IndexPath string +type requestContext = Context + +// requestTimeoutError is returned by withTimeout when the handler exceeds its budget. +type requestTimeoutError struct { + timeout time.Duration } -type HttpResponse struct { - Status int `json:"status,omitempty"` - Message string `json:"message,omitempty"` - Token string `json:"token,omitempty"` +func newRequestTimeoutError(timeout time.Duration) error { + return &requestTimeoutError{timeout: timeout} } -var FileInfoFasterFunc = files.FileInfoFaster +func (e *requestTimeoutError) Error() string { + return fmt.Sprintf("request timed out after %s", e.timeout) +} -// Updated handleFunc to match the new signature -type handleFunc func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) +var FileInfoFasterFunc = func(opts utils.FileOptions, user *users.User) (*iteminfo.ExtendedFileInfo, error) { + if runtimeDeps.Files != nil { + return runtimeDeps.Files.FileInfoFaster(opts, user) + } + return files.FileInfoFaster(opts, user) +} + +type handleFunc = HandleFunc // Middleware to handle file requests by hash and pass it to the handler func withHashFileHelper(fn handleFunc) handleFunc { return withOrWithoutUserHelper(func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) { hash := r.URL.Query().Get("hash") inputPath := r.URL.Query().Get("path") - path, err := utils.SanitizeUserPath(inputPath) + path, err := utils.SanitizePath(inputPath) if err != nil && inputPath != "" { return http.StatusBadRequest, err } - path = filepath.ToSlash(path) - // Get the file link by hash - link, err := store.Share.GetByHash(hash) + link, err := state.GetShare(hash) if err != nil { - data.share = &share.Link{} + data.Share = share.Share{} return http.StatusNotFound, fmt.Errorf("share hash not found") } - if link.DisableAnonymous && data.user.Username == "anonymous" { + // Defensive check: data.User should be set by withOrWithoutUserHelper + if data.User == nil { + return http.StatusInternalServerError, fmt.Errorf("internal error: user context not set") + } + 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" { + if link.PerUserDownloadLimit && data.User.Username == "anonymous" { return http.StatusForbidden, fmt.Errorf("anonymous downloads are not allowed with per-user limits") } if len(link.AllowedUsernames) > 0 { - if !slices.Contains(link.AllowedUsernames, data.user.Username) { + if !slices.Contains(link.AllowedUsernames, data.User.Username) { return http.StatusForbidden, fmt.Errorf("share is not available to this user") } } - // Check per-user download limit - if link.PerUserDownloadLimit && link.HasReachedUserLimit(data.user.Username) { - return http.StatusForbidden, fmt.Errorf("user download limit reached for this share") - } - data.share = link + data.Share = link // Authenticate the share request if needed var status int if link.Hash != "" { - status, err = authenticateShareRequest(r, link) + status, err = AuthenticateShareRequest(r, link) if err != nil || status != http.StatusOK { return status, fmt.Errorf("could not authenticate share request") } } - source, ok := config.Server.SourceMap[link.Source] + source, ok := settings.Config.Server.SourceMap[link.SourcePath] if !ok { return http.StatusNotFound, fmt.Errorf("source not found") } @@ -105,12 +102,15 @@ func withHashFileHelper(fn handleFunc) handleFunc { if link.DisableFileViewer || reachedDownloadsLimit { getContent = false } - data.shareUser, err = store.Users.Get(link.UserID) + userValue, err := state.UserForShareOwner(link) + if err == nil { + data.ShareUser = &userValue + } if err != nil { return http.StatusNotFound, fmt.Errorf("user for share no longer exists") } // get user scope path from share - userScope, err := data.shareUser.GetScopeForSourceName(source.Name) + userScope, err := data.ShareUser.GetScopeForSourceName(source.Name) if err != nil { return http.StatusForbidden, err } @@ -122,8 +122,12 @@ func withHashFileHelper(fn handleFunc) handleFunc { data.IndexPath = pathWithoutUserScope // skip file fetch for certain apis if (r.Method == "POST" && strings.Contains(r.URL.Path, "/resources")) || + (r.Method == "POST" && strings.Contains(r.URL.Path, "/resources/view-token")) || (r.Method == "GET" && strings.Contains(r.URL.Path, "/resources/items")) || - (r.Method == "GET" && strings.Contains(r.URL.Path, "/media/metadata")) { + (r.Method == "GET" && strings.Contains(r.URL.Path, "/media/metadata")) || + (r.Method == "GET" && strings.Contains(r.URL.Path, "/resources/download")) || + (r.Method == "GET" && strings.Contains(r.URL.Path, "/resources/view")) || + (r.Method == "GET" && strings.Contains(r.URL.Path, "/media/stream")) { return fn(w, r, data) } file, err := FileInfoFasterFunc(utils.FileOptions{ @@ -133,16 +137,16 @@ func withHashFileHelper(fn handleFunc) handleFunc { Content: getContent, Metadata: getMetadata, AlbumArt: strings.Contains(r.URL.Path, "/preview"), - ExtractEmbeddedSubtitles: config.Integrations.Media.ExtractEmbeddedSubtitles && link.ExtractEmbeddedSubtitles, + ExtractEmbeddedSubtitles: settings.Config.Integrations.Media.ExtractEmbeddedSubtitles && link.ExtractEmbeddedSubtitles, ShowHidden: link.ShowHidden, HideFileExt: link.HideFileExt, FollowSymlinks: true, ShowPinnedItems: true, ShareHash: hash, - }, store.Access, data.shareUser, store.Share) + }, data.ShareUser) if err != nil { logger.Errorf("error fetching file info for share. hash=%v path=%v error=%v", hash, path, err) - return errToStatus(err), fmt.Errorf("error fetching share from server") + return ErrToStatus(err), fmt.Errorf("error fetching share from server") } file.Token = link.Token file.Source = link.Hash @@ -150,18 +154,14 @@ func withHashFileHelper(fn handleFunc) handleFunc { if !link.EnableOnlyOffice || link.DisableFileViewer || reachedDownloadsLimit { file.OnlyOfficeId = "" } - if getContent && file.Content != "" { - link.Mu.Lock() - link.Downloads++ - link.Mu.Unlock() - // Track per-user download if enabled - if link.PerUserDownloadLimit { - link.IncrementUserDownload(data.user.Username) - } + if file.Type != "directory" { + AttachViewToken(data, source.Name, file) + } else { + AttachViewTokensForDirectory(data, source.Name, file) } file.Path = utils.AddTrailingSlashIfNotExists(path) // Set the file info in the `data` object - data.fileInfo = *file + data.FileInfo = *file // Call the next handler with the data return fn(w, r, data) }) @@ -171,7 +171,7 @@ func withHashFileHelper(fn handleFunc) handleFunc { func withAdminHelper(fn handleFunc) handleFunc { return withUserHelper(func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) { // Ensure the user has admin permissions - if !data.user.Permissions.Admin { + if !data.User.Permissions.Admin { return http.StatusForbidden, nil } return fn(w, r, data) @@ -181,25 +181,25 @@ func withAdminHelper(fn handleFunc) handleFunc { // extractUserFromExpiredToken attempts to extract user information from an expired token // This is used by withOrWithoutUserHelper to get user context even when tokens are expired func extractUserFromExpiredToken(r *http.Request, data *requestContext) *users.User { - if config.Auth.Methods.NoAuth { - user, err := store.Users.Get(uint(1)) + if settings.Config.Auth.Methods.NoAuth { + userValue, err := state.ResolveNoAuthUser() if err != nil { logger.Errorf("no auth: %v", err) return nil } - return user + return &userValue } keyFunc := func(token *jwt.Token) (interface{}, error) { - return []byte(config.Auth.Key), nil + return []byte(settings.Config.Auth.Key), nil } - tokenString, err := extractToken(r) + tokenString, err := ExtractToken(r) if err != nil { return nil } - data.token = tokenString + data.Token = tokenString var tk users.AuthToken token, err := jwt.ParseWithClaims(tokenString, &tk, keyFunc) if err != nil { @@ -212,9 +212,13 @@ func extractUserFromExpiredToken(r *http.Request, data *requestContext) *users.U // Token is valid (but might be expired or revoked) // Try to get the user regardless of expiration status - user, err := store.Users.Get(tk.BelongsTo) + var user *users.User + userValue, err := state.UserFromAPIToken(tk, tokenString) + if err == nil { + user = &userValue + } if err != nil { - logger.Errorf("Failed to get user with ID %v: %v", tk.BelongsTo, err) + logger.Errorf("Failed to get user from token: %v", err) return nil } @@ -230,19 +234,59 @@ func extractUserFromExpiredToken(r *http.Request, data *requestContext) *users.U // If authentication fails, the request continues without a user. func withOrWithoutUserHelper(fn handleFunc) handleFunc { return func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) { + var snap share.Share + var haveSnap bool + var isShareRequest bool + var shareHash string + hash := r.URL.Query().Get("hash") if hash != "" { - _, err := store.Share.GetByHash(hash) - if err != nil { - return http.StatusNotFound, fmt.Errorf("share hash not found") + isShareRequest = true + shareHash = hash + if l, err := state.GetShare(hash); err == nil { + snap = l + haveSnap = true + } + } else { + prefix := settings.Config.Http.BaseURL + "public/share/" + reconstructed := settings.Config.Http.BaseURL + "public" + r.URL.Path + if strings.HasPrefix(reconstructed, prefix) { + remaining := strings.TrimPrefix(reconstructed, prefix) + if remaining != "" { + if idx := strings.IndexByte(remaining, '/'); idx >= 0 { + remaining = remaining[:idx] + } + if remaining != "" { + isShareRequest = true + shareHash = remaining + if l, err := state.GetShare(remaining); err == nil { + snap = l + haveSnap = true + } else { + logger.Debugf("error getting share by hash: %v", err) + } + } + } + } + } + + if isShareRequest { + if haveSnap { + data.Share = snap + data.ShareValid = true + } else { + data.Share = share.Share{ShareColumns: share.ShareColumns{Hash: shareHash}} + data.ShareValid = false } } // Try to authenticate user first status, err := withUserHelper(nil)(w, r, data) if err == nil && status < 400 { - if data.share != nil && data.user != nil { - data.user.CustomTheme = data.share.ShareTheme + if data.ShareValid && data.Share.Hash != "" { + if data.User != nil { + data.User.CustomTheme = data.Share.ShareTheme + } } return fn(w, r, data) } @@ -252,21 +296,23 @@ func withOrWithoutUserHelper(fn handleFunc) handleFunc { // Try to extract user info from potentially expired token userFromExpiredToken := extractUserFromExpiredToken(r, data) if userFromExpiredToken != nil { - data.user = userFromExpiredToken - if data.share != nil { - data.user.CustomTheme = data.share.ShareTheme + data.User = userFromExpiredToken + if data.ShareValid && data.Share.Hash != "" { + data.User.CustomTheme = data.Share.ShareTheme } - setUserInResponseWriter(w, data.user) + SetUserInResponseWriter(w, data.User) return fn(w, r, data) } // No valid token or user found, fall back to anonymous - data.user = &users.User{Username: "anonymous"} - settings.ApplyUserDefaults(data.user) + data.User = &users.User{ + FrontendUser: users.FrontendUser{Username: "anonymous"}, + } + state.ApplyUserDefaults(data.User) // Clear any user data that might have been partially set - data.token = "" - if data.share != nil { - data.user.CustomTheme = data.share.ShareTheme + data.Token = "" + if data.ShareValid && data.Share.Hash != "" { + data.User.CustomTheme = data.Share.ShareTheme } // Call the handler function without user context return fn(w, r, data) @@ -283,19 +329,35 @@ func withoutUserHelper(fn handleFunc) handleFunc { } } -// allow user without OTP to pass +// LoginHelper authenticates login/signup requests. When disableOtp is false, users with TOTPSecret must supply X-Secret. func LoginHelper(disableOtp bool, fn handleFunc) handleFunc { return func(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - - if config.Auth.Methods.ProxyAuth.Enabled { - proxyUser := r.Header.Get(config.Auth.Methods.ProxyAuth.Header) + if settings.Config.Auth.Methods.ProxyAuth.Enabled { + proxyUser := r.Header.Get(settings.Config.Auth.Methods.ProxyAuth.Header) if proxyUser != "" { return getProxyUser(w, r, d, fn, proxyUser) } } + // Check if request has a valid admin token first + if tokenStr, err := ExtractToken(r); err == nil && tokenStr != "" { + keyFunc := func(token *jwt.Token) (interface{}, error) { + return []byte(settings.Config.Auth.Key), nil + } + var tk users.AuthToken + if token, err := jwt.ParseWithClaims(tokenStr, &tk, keyFunc); err == nil && token.Valid { + if !state.IsTokenRevoked( tokenStr) { + userValue, err := state.UserFromAPIToken(tk, tokenStr) + if err == nil && userValue.Permissions.Admin { + u := userValue + d.User = &u + return fn(w, r, d) + } + } + } + } - // Try LDAP first if enabled; on success set d.user and continue to handler - if config.Auth.Methods.LdapAuth.Enabled { + // Try LDAP first if enabled; on success set d.User and continue to handler + if settings.Config.Auth.Methods.LdapAuth.Enabled { // No valid admin token - proceed with username/password authentication username := r.URL.Query().Get("username") password := r.Header.Get("X-Password") @@ -308,23 +370,13 @@ func LoginHelper(disableOtp bool, fn handleFunc) handleFunc { ldapUser, err := AuthenticateLDAPUser(username, password) if err == nil { logger.Debugf("ldap auth successful, calling handler") - d.user = ldapUser + d.User = ldapUser return fn(w, r, d) } logger.Debug("ldap auth failed, calling password auth", err) } - if config.Auth.Methods.PasswordAuth.Enabled { - auther, err := store.Auth.Get("password") - if err != nil { - return 401, errors.ErrUnauthorized - } - // OTP routes: password only (do not mutate stored *JSONAuth). - if ja, ok := auther.(*auth.JSONAuth); ok { - x := *ja - x.DisableOtp = disableOtp - auther = &x - } - user, err := auther.Auth(r, store.Users) + if settings.Config.Auth.Methods.PasswordAuth.Enabled { + user, err := auth.AuthenticatePassword(r, disableOtp) if err != nil { logger.Debug("password auth failed, calling handler:", err) if err == errors.ErrNoTotpProvided { @@ -332,7 +384,7 @@ func LoginHelper(disableOtp bool, fn handleFunc) handleFunc { } return 401, errors.ErrUnauthorized } - d.user = user + d.User = user return fn(w, r, d) } return withUserHelper(fn)(w, r, d) @@ -342,10 +394,11 @@ func LoginHelper(disableOtp bool, fn handleFunc) handleFunc { // Middleware to retrieve and authenticate user func withUserHelper(fn handleFunc) handleFunc { return func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) { - if config.Auth.Methods.NoAuth { - var err error - // Retrieve the user from the store and store it in the context - data.user, err = store.Users.Get(uint(1)) + if settings.Config.Auth.Methods.NoAuth { + userValue, err := state.ResolveNoAuthUser() + if err == nil { + data.User = &userValue + } if err != nil { logger.Errorf("no auth: %v", err) return http.StatusInternalServerError, err @@ -357,8 +410,8 @@ func withUserHelper(fn handleFunc) handleFunc { } // Check for JWT external auth first (header or query param) - if config.Auth.Methods.JwtAuth.Enabled { - jwtToken := r.Header.Get(config.Auth.Methods.JwtAuth.Header) + if settings.Config.Auth.Methods.JwtAuth.Enabled { + jwtToken := r.Header.Get(settings.Config.Auth.Methods.JwtAuth.Header) if jwtToken == "" { // Check query parameter (hardcoded to "jwt") jwtToken = r.URL.Query().Get("jwt") @@ -369,21 +422,21 @@ func withUserHelper(fn handleFunc) handleFunc { } } - proxyUser := r.Header.Get(config.Auth.Methods.ProxyAuth.Header) - isProxyUser := config.Auth.Methods.ProxyAuth.Enabled && proxyUser != "" + proxyUser := r.Header.Get(settings.Config.Auth.Methods.ProxyAuth.Header) + isProxyUser := settings.Config.Auth.Methods.ProxyAuth.Enabled && proxyUser != "" keyFunc := func(token *jwt.Token) (interface{}, error) { - return []byte(config.Auth.Key), nil + return []byte(settings.Config.Auth.Key), nil } - if data.token == "" { + if data.Token == "" { var err error - data.token, err = extractToken(r) + data.Token, err = ExtractToken(r) if err != nil && !isProxyUser { return http.StatusUnauthorized, err } } var tk users.AuthToken - token, err := jwt.ParseWithClaims(data.token, &tk, keyFunc) + token, err := jwt.ParseWithClaims(data.Token, &tk, keyFunc) if err != nil { if isProxyUser { return getProxyUser(w, r, data, fn, proxyUser) @@ -394,7 +447,7 @@ func withUserHelper(fn handleFunc) handleFunc { if !token.Valid { return http.StatusUnauthorized, fmt.Errorf("invalid token") } - if auth.IsRevokedApiToken(store.Access, data.token) { + if state.IsTokenRevoked( data.Token) { return http.StatusUnauthorized, fmt.Errorf("token is expired or revoked") } // ExpiresAt should always be set in valid tokens created by our system @@ -406,27 +459,24 @@ func withUserHelper(fn handleFunc) handleFunc { if tk.RegisteredClaims.ExpiresAt.Unix() < time.Now().Add(time.Minute*30).Unix() { w.Header().Add("X-Renew-Token", "true") } - // Check if token is minimal/stateful (no BelongsTo in claim) - if tk.BelongsTo == 0 { - // Hash the token and look up user ID in access storage - userID, found := store.Access.GetUserIDFromToken(data.token) - if !found { - return http.StatusUnauthorized, fmt.Errorf("token is invalid or revoked") - } - tk.BelongsTo = userID + userValue, err := state.UserFromAPIToken(tk, data.Token) + if err == nil { + data.User = &userValue } - data.user, err = store.Users.Get(tk.BelongsTo) if err != nil { - logger.Errorf("Failed to get user with ID %v: %v", tk.BelongsTo, err) - return http.StatusInternalServerError, err + logger.Errorf("Failed to get user from token: %v", err) + return http.StatusUnauthorized, fmt.Errorf("token is invalid or revoked") + } + if tokenName, ok := state.TokenNameForRawToken(data.User, data.Token); ok { + applyNamedApiTokenGlobalCaps(data.User, tk, tokenName) } // Set cookie. Some clients like gvfs relies on it for concurrent uploads if tk.RegisteredClaims.ExpiresAt != nil { - setSessionCookie(w, r, data.token, tk.RegisteredClaims.ExpiresAt.Time) + SetSessionCookie(w, r, data.Token, tk.RegisteredClaims.ExpiresAt.Time) } - setUserInResponseWriter(w, data.user) - if data.user.Username == "" { + SetUserInResponseWriter(w, data.User) + if data.User.Username == "" { return http.StatusForbidden, errors.ErrUnauthorized } // Call the handler function, passing in the context (or return OK if no handler) @@ -441,9 +491,9 @@ func getJwtUser(w http.ResponseWriter, r *http.Request, data *requestContext, fn // Verify the external JWT token username, claims, err := auth.VerifyExternalJWT( jwtToken, - config.Auth.Methods.JwtAuth.Secret, - config.Auth.Methods.JwtAuth.Algorithm, - config.Auth.Methods.JwtAuth.UserIdentifier, + settings.Config.Auth.Methods.JwtAuth.Secret, + settings.Config.Auth.Methods.JwtAuth.Algorithm, + settings.Config.Auth.Methods.JwtAuth.UserIdentifier, ) if err != nil { logger.Debugf("JWT verification failed: %v", err) @@ -451,25 +501,26 @@ func getJwtUser(w http.ResponseWriter, r *http.Request, data *requestContext, fn } // Setup user based on JWT claims - user, err := setupJwtUser(r, data, username, claims) + user, err := SetupJwtUser(r, data, username, claims) if err != nil { return http.StatusForbidden, err } - data.user = user - setUserInResponseWriter(w, data.user) - if data.user.Username == "" { + data.User = user + SetUserInResponseWriter(w, data.User) + if data.User.Username == "" { return http.StatusForbidden, errors.ErrUnauthorized } // Generate a FileBrowser session token for JWT users if they don't have one - if data.token == "" { - expires := time.Hour * time.Duration(config.Auth.TokenExpirationHours) + if data.Token == "" { + expires := time.Hour * time.Duration(settings.Config.Auth.TokenExpirationHours) tokenString, _, err := auth.MakeSignedTokenAPI(user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), expires, user.Permissions, false) if err != nil { logger.Errorf("Failed to generate token for JWT user %s: %v", username, err) return http.StatusInternalServerError, fmt.Errorf("failed to generate token") } - data.token = tokenString + data.Token = tokenString + SetSessionCookie(w, r, tokenString, time.Now().Add(expires).Add(time.Minute*30)) } // Call the handler function, passing in the context (or return OK if no handler) @@ -481,24 +532,25 @@ func getJwtUser(w http.ResponseWriter, r *http.Request, data *requestContext, fn func getProxyUser(w http.ResponseWriter, r *http.Request, data *requestContext, fn handleFunc, proxyUser string) (int, error) { // proxy user logic - user, err := setupProxyUser(r, data, proxyUser) + user, err := SetupProxyUser(r, data, proxyUser) if err != nil { return http.StatusForbidden, err } - data.user = user - setUserInResponseWriter(w, data.user) - if data.user.Username == "" { + data.User = user + SetUserInResponseWriter(w, data.User) + if data.User.Username == "" { return http.StatusForbidden, errors.ErrUnauthorized } // Generate a token for proxy users if they don't have one - if data.token == "" { - expires := time.Hour * time.Duration(config.Auth.TokenExpirationHours) + if data.Token == "" { + expires := time.Hour * time.Duration(settings.Config.Auth.TokenExpirationHours) tokenString, _, err := auth.MakeSignedTokenAPI(user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), expires, user.Permissions, false) if err != nil { logger.Errorf("Failed to generate token for proxy user %s: %v", proxyUser, err) return http.StatusInternalServerError, fmt.Errorf("failed to generate token") } - data.token = tokenString + data.Token = tokenString + SetSessionCookie(w, r, tokenString, time.Now().Add(expires).Add(time.Minute*30)) } // Call the handler function, passing in the context (or return OK if no handler) if fn == nil { @@ -511,7 +563,7 @@ func getProxyUser(w http.ResponseWriter, r *http.Request, data *requestContext, func withSelfOrAdminHelper(fn handleFunc) handleFunc { return withUserHelper(func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) { // Check if the current user is the same as the requested user or if they are an admin - if !data.user.Permissions.Admin { + if !data.User.Permissions.Admin { return http.StatusForbidden, nil } // Call the actual handler function with the updated context @@ -522,7 +574,7 @@ func withSelfOrAdminHelper(fn handleFunc) handleFunc { func wrapHandler(fn handleFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { data := &requestContext{ - ctx: r.Context(), + Ctx: r.Context(), } // Call the actual handler function and get status code and error @@ -578,15 +630,13 @@ func wrapHandlerBasicAuth(fn handleFunc) http.HandlerFunc { func withPermShareHelper(fn handleFunc) handleFunc { return withUserHelper(func(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !d.user.Permissions.Share { + if !d.User.Permissions.Share { return http.StatusForbidden, nil } return fn(w, r, d) }) } -// withBasicAuthHelper extracts Basic Auth credentials and uses the password as a JWT token -// to authenticate the user. The username is ignored, and the password should be a JWT token. func withBasicAuthHelper(fn handleFunc) handleFunc { return func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) { _, password, ok := r.BasicAuth() @@ -594,7 +644,7 @@ func withBasicAuthHelper(fn handleFunc) handleFunc { // Return 401 - wrapHandlerBasicAuth will set WWW-Authenticate header return http.StatusUnauthorized, fmt.Errorf("basic authentication required") } - data.token = password + data.Token = password return withUserHelper(fn)(w, r, data) } } @@ -637,7 +687,7 @@ func withSelfOrAdmin(fn handleFunc) http.HandlerFunc { return wrapHandler(withSelfOrAdminHelper(fn)) } -// withTimeoutHelper adds a configurable timeout context to any operation +// withTimeoutHelper adds a configurable timeout context to any operation. func withTimeoutHelper(timeout time.Duration, fn handleFunc) handleFunc { return func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) { // Create a context with the specified timeout @@ -660,13 +710,12 @@ func withTimeoutHelper(timeout time.Duration, fn handleFunc) handleFunc { // Replace the request context with the timeout context r = r.WithContext(ctx) - data.ctx = ctx + data.Ctx = ctx // Call the handler and check for timeout status, err := fn(w, r, data) - // Check if the context was cancelled due to timeout if ctx.Err() == context.DeadlineExceeded { - return http.StatusRequestTimeout, fmt.Errorf("request timed out after %.0f seconds", timeout.Seconds()) + return http.StatusRequestTimeout, newRequestTimeoutError(timeout) } return status, err @@ -682,67 +731,6 @@ func muxWithMiddleware(mux *http.ServeMux) *http.ServeMux { wrappedMux.Handle("/", LoggingMiddleware(mux)) return wrappedMux } - -// ResponseWriterWrapper wraps the standard http.ResponseWriter to capture the status code -type ResponseWriterWrapper struct { - http.ResponseWriter - StatusCode int - wroteHeader bool - PayloadSize int - User string -} - -// WriteHeader captures the status code and ensures it's only written once -func (w *ResponseWriterWrapper) WriteHeader(statusCode int) { - if !w.wroteHeader { // Prevent WriteHeader from being called multiple times - if statusCode == 0 { - statusCode = http.StatusInternalServerError - } - w.StatusCode = statusCode - w.ResponseWriter.WriteHeader(statusCode) - w.wroteHeader = true - } -} - -// Write is the method to write the response body and ensure WriteHeader is called -func (w *ResponseWriterWrapper) Write(b []byte) (int, error) { - if !w.wroteHeader { // Default to 200 if WriteHeader wasn't called explicitly - w.WriteHeader(http.StatusOK) - } - return w.ResponseWriter.Write(b) -} - -// Helper function to set the user in the ResponseWriterWrapper -func setUserInResponseWriter(w http.ResponseWriter, user *users.User) { - // Wrap the response writer to set the user field - if wrappedWriter, ok := w.(*ResponseWriterWrapper); ok { - if user != nil { - wrappedWriter.User = user.Username - } - } -} - -func getRemoteIP(r *http.Request) string { - // 1. Check X-Forwarded-For - xff := r.Header.Get("X-Forwarded-For") - if config.Http.TrustedHeaders["x-forwarded-for"] && xff != "" { - // The first IP is the original client - ips := strings.Split(xff, ",") - return strings.TrimSpace(ips[0]) - } - - // 2. Check X-Real-IP - xri := r.Header.Get("X-Real-IP") - if config.Http.TrustedHeaders["x-real-ip"] && xri != "" { - return xri - } - - // 3. Fallback to RemoteAddr (strip port if necessary) - ip, _, _ := net.SplitHostPort(r.RemoteAddr) - return ip -} - -// LoggingMiddleware logs each request and its status code. func LoggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // DEFER RECOVERY FUNCTION @@ -762,17 +750,17 @@ func LoggingMiddleware(next http.Handler) http.Handler { stackTrace := string(buf[:n]) logger.Errorf("PANIC RECOVERED: %v\nUser: %s\nMethod: %s\nURL: %s\nRemoteAddr: %s\nGo Stack Trace:\n%s", - rcv, username, method, url, getRemoteIP(r), stackTrace) + rcv, username, method, url, GetRemoteIP(r), stackTrace) // Attempt to send a 500 error response to the client // This is a best-effort; the connection might be broken or process too unstable. - if ww, ok := w.(*ResponseWriterWrapper); ok { // Check if it's our wrapper - if !ww.wroteHeader { // Only write if headers haven't been sent + if ww, ok := w.(*ResponseWriterWrapper); ok { + if !ww.WroteHeader { ww.Header().Set("Content-Type", "application/json; charset=utf-8") ww.WriteHeader(http.StatusInternalServerError) } } else { - _, _ = renderJSON(w, r, &HttpResponse{ + _, _ = RenderJSON(w, r, &HttpResponse{ Status: 500, Message: "A critical internal error occurred. Please try again later.", }, http.StatusInternalServerError) @@ -805,67 +793,9 @@ func LoggingMiddleware(next http.Handler) http.Handler { fmt.Sprintf("%-7s | %3d | %-15s | %-12s | %-12s | \"%s\"", r.Method, wrappedWriter.StatusCode, - getRemoteIP(r), + GetRemoteIP(r), truncUser, fmt.Sprintf("%vms", duration.Milliseconds()), fullURL)) }) } - -func renderJSON(w http.ResponseWriter, r *http.Request, data interface{}, statusCode ...int) (int, error) { - // Default to 200 if status code not provided - code := http.StatusOK - if len(statusCode) > 0 && statusCode[0] != 0 { - code = statusCode[0] - } - - marsh, err := json.Marshal(data) - if err != nil { - return http.StatusInternalServerError, err - } - // Calculate size in KB - payloadSizeKB := len(marsh) / 1024 - // Set headers before writing - w.Header().Set("Content-Type", "application/json; charset=utf-8") - // Check if the client accepts gzip encoding and hasn't explicitly disabled it - if acceptsGzip(r) && payloadSizeKB > 10 { - // Enable gzip compression - w.Header().Set("Content-Encoding", "gzip") - w.WriteHeader(code) - gz := gzip.NewWriter(w) - defer gz.Close() - - if _, err := gz.Write(marsh); err != nil { - return http.StatusInternalServerError, err - } - } else { - // Normal response without compression - w.WriteHeader(code) - if _, err := w.Write(marsh); err != nil { - return http.StatusInternalServerError, err - } - } - - return code, nil -} - -func acceptsGzip(r *http.Request) bool { - ae := r.Header.Get("Accept-Encoding") - return ae != "" && strings.Contains(ae, "gzip") -} - -func (w *ResponseWriterWrapper) Flush() { - if flusher, ok := w.ResponseWriter.(http.Flusher); ok { - flusher.Flush() - } -} - -func getScheme(r *http.Request) string { - if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" { - return proto - } - if r.TLS != nil { - return "https" - } - return "http" -} diff --git a/backend/internal/web/middleware_test.go b/backend/internal/web/middleware_test.go new file mode 100644 index 0000000000..ad7a69b8bf --- /dev/null +++ b/backend/internal/web/middleware_test.go @@ -0,0 +1,379 @@ +package web + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + "time" + + "github.com/gtsteffaniak/filebrowser/backend/internal/app" + "github.com/gtsteffaniak/filebrowser/backend/internal/auth" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + _ "github.com/gtsteffaniak/filebrowser/backend/internal/database/sqldb" // Import to register SQL driver + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func setupTestEnv(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "test.sqlite") + + // Initialize state with SQLite database + _, err := state.Initialize(dbPath) + if err != nil { + t.Fatal(err) + } + app.MustWireServices(state.Default()) + t.Cleanup(func() { + state.Close() + }) + + settings.Config.Server.SourceMap = map[string]*settings.Source{ + "/srv": { + Path: "/srv", + Name: "srv", + }, + } + settings.Config.Server.NameToSource = map[string]*settings.Source{ + "srv": { + Path: "/srv", + Name: "srv", + }, + } + // Initialize user resolvers so users package can resolve source names + settings.InitializeUserResolvers() + mockFileInfoFaster(t) // Mock FileInfoFasterFunc for this test +} + +func mockFileInfoFaster(t *testing.T) { + // Backup the original function + originalFileInfoFaster := FileInfoFasterFunc + // Defer restoration of the original function + t.Cleanup(func() { FileInfoFasterFunc = originalFileInfoFaster }) + + // Mock the function to skip execution + FileInfoFasterFunc = func(opts utils.FileOptions, user *users.User) (*iteminfo.ExtendedFileInfo, error) { + return &iteminfo.ExtendedFileInfo{ + FileInfo: iteminfo.FileInfo{ + Path: opts.Path, + ItemInfo: iteminfo.ItemInfo{ + Name: "mocked_file", + Size: 12345, + }, + }, + }, nil + } +} + +func TestWithAdminHelper(t *testing.T) { + setupTestEnv(t) + // Mock a user who has admin permissions + adminUser := &users.User{ + ID: 1, + FrontendUser: users.FrontendUser{ + Username: "admin", + Permissions: users.Permissions{Admin: true}, // Ensure the user is an admin + }, + } + nonAdminUser := &users.User{ + ID: 2, + FrontendUser: users.FrontendUser{ + Username: "non-admin", + Permissions: users.Permissions{Admin: false}, // Non-admin user + }, + } + // Save the users to the mock database + if err := state.CreateUser(adminUser, ""); err != nil { + t.Fatal("failed to create admin user:", err) + } + // CreateUser runs ApplyUserDefaults, which replaces permissions from global UserDefaults. + adminUser.Permissions = users.Permissions{Admin: true} + if err := state.UpdateUser(adminUser, "", "permissions"); err != nil { + t.Fatal("failed to set admin permissions:", err) + } + if err := state.CreateUser(nonAdminUser, ""); err != nil { + t.Fatal("failed to create non-admin user:", err) + } + nonAdminUser.Permissions = users.Permissions{Admin: false} + if err := state.UpdateUser(nonAdminUser, "", "permissions"); err != nil { + t.Fatal("failed to set non-admin permissions:", err) + } + // Test cases for different scenarios + testCases := []struct { + name string + expectedStatusCode int + user *users.User + }{ + { + name: "Admin access allowed", + expectedStatusCode: http.StatusOK, // Admin should be able to access + user: adminUser, + }, + { + name: "Non-admin access forbidden", + expectedStatusCode: http.StatusForbidden, // Non-admin should be forbidden + user: nonAdminUser, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + tokenString, _, err := auth.MakeSignedTokenAPI(tc.user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), time.Hour*2, tc.user.Permissions, false) + if err != nil { + t.Fatalf("Error making token for request: %v", err) + } + + handler := withAdmin(mockHandler) + + recorder := httptest.NewRecorder() + req, err := http.NewRequest(http.MethodGet, "/users", http.NoBody) + if err != nil { + t.Fatalf("Error creating request: %v", err) + } + req.AddCookie(&http.Cookie{ + Name: "filebrowser_quantum_jwt", + Value: tokenString, + }) + + handler(recorder, req) + + if recorder.Code != tc.expectedStatusCode { + t.Errorf("\"%v\" expected status code %d, got %d", tc.name, tc.expectedStatusCode, recorder.Code) + } + }) + } +} + +func TestPublicShareHandlerAuthentication(t *testing.T) { + setupTestEnv(t) + + const passwordBcrypt = "$2y$10$TFAmdCbyd/mEZDe5fUeZJu.MaJQXRTwdqb/IQV.eTn6dWrF58gCSe" // bcrypt hashed password + + // Create and save a dummy user (shares reference owner by UserID) + dummyUser := &users.User{ + ID: 1, + FrontendUser: users.FrontendUser{ + Username: "testuser", + Permissions: users.Permissions{Admin: false}, + }, + BackendScopes: []users.BackendScope{ + {Path: "/srv", Scope: "/"}, // Must match SourceMap key (canonical path, no trailing slash) + }, + } + if err := state.CreateUser(dummyUser, ""); err != nil { + t.Fatal("failed to create dummy user:", err) + } + + originalAuthKey := settings.Config.Auth.Key + settings.Config.Auth.Key = "key" + t.Cleanup(func() { settings.Config.Auth.Key = originalAuthKey }) + + testCases := []struct { + name string + share *share.Share + token string + password string + extraHeaders map[string]string + expectedStatusCode int + }{ + { + name: "Public share, no auth required", + share: &share.Share{ + ShareSettings: share.ShareSettings{ + ShareLimits: share.ShareLimits{SourceName: "srv"}, + }, + ShareColumns: share.ShareColumns{Hash: "public_hash", Path: "/"}, + SourcePath: "/srv", + UserID: 1, + }, + expectedStatusCode: http.StatusOK, // zero means 200 on helpers + }, + { + name: "Private share, valid password when token exists", + share: &share.Share{ + ShareSettings: share.ShareSettings{ + ShareLimits: share.ShareLimits{SourceName: "srv"}, + }, + ShareColumns: share.ShareColumns{Hash: "pw_and_token_hash", Path: "/"}, + SourcePath: "/srv", + UserID: 1, + PasswordHash: passwordBcrypt, + Token: "some_random_token", + }, + extraHeaders: map[string]string{ + "X-SHARE-PASSWORD": "password", + }, + expectedStatusCode: http.StatusOK, // zero means 200 on helpers + }, + { + name: "Private share, no auth provided", + share: &share.Share{ + ShareSettings: share.ShareSettings{ + ShareLimits: share.ShareLimits{SourceName: "srv"}, + }, + ShareColumns: share.ShareColumns{Hash: "private_hash", Path: "/"}, + SourcePath: "/srv", + UserID: 1, + PasswordHash: passwordBcrypt, + Token: "123", + }, + expectedStatusCode: http.StatusUnauthorized, + }, + { + name: "Private share, valid token", + share: &share.Share{ + ShareSettings: share.ShareSettings{ + ShareLimits: share.ShareLimits{SourceName: "srv"}, + }, + ShareColumns: share.ShareColumns{Hash: "token_hash", Path: "/"}, + SourcePath: "/srv", + UserID: 1, + PasswordHash: passwordBcrypt, + Token: "123", + }, + token: "123", + expectedStatusCode: http.StatusOK, // zero means 200 on helpers + }, + { + name: "Private share, invalid password", + share: &share.Share{ + ShareSettings: share.ShareSettings{ + ShareLimits: share.ShareLimits{SourceName: "srv"}, + }, + ShareColumns: share.ShareColumns{Hash: "pw_hash", Path: "/"}, + SourcePath: "/srv", + UserID: 1, + PasswordHash: passwordBcrypt, + Token: "123", + }, + extraHeaders: map[string]string{ + "X-SHARE-PASSWORD": "wrong-password", + }, + expectedStatusCode: http.StatusUnauthorized, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + // Save the share in the state + if err := state.CreateShare(tc.share); err != nil { + t.Fatal("failed to save share:", err) + } + + // Create a response recorder to capture handler output + recorder := httptest.NewRecorder() + + // Wrap the handler with authentication middleware + handler := withHashFile(publicGetResourceHandler) + + // Prepare the request with query parameters and optional headers + req := newTestRequest(t, tc.share.Hash, tc.token, tc.password, tc.extraHeaders) + + // Serve the request + handler(recorder, req) + + if recorder.Code != tc.expectedStatusCode { + t.Errorf("expected status code %d, got %d", tc.expectedStatusCode, recorder.Code) + } + }) + } +} + +// Helper function to create a new HTTP request with optional parameters +func newTestRequest(t *testing.T, hash, token, password string, headers map[string]string) *http.Request { + req := newHTTPRequest(t, hash, func(r *http.Request) { + // Set query parameters based on provided values + q := r.URL.Query() + q.Set("path", "/") + q.Set("hash", hash) + if token != "" { + q.Set("token", token) + } + if password != "" { + q.Set("password", password) + } + r.URL.RawQuery = q.Encode() + + // Set any extra headers if provided + for key, value := range headers { + r.Header.Set(key, value) + } + }) + return req +} + +func mockHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { + return http.StatusOK, nil // mock response +} + +// Modify newHTTPRequest to accept the hash and use it in the URL path. +func newHTTPRequest(t *testing.T, hash string, requestModifiers ...func(*http.Request)) *http.Request { + t.Helper() + url := "/public/share/" + hash + "/" // Dynamically include the hash in the URL path + r, err := http.NewRequest(http.MethodGet, url, http.NoBody) + if err != nil { + t.Fatalf("failed to create request: %v", err) + } + for _, modify := range requestModifiers { + modify(r) + } + return r +} + +func TestWithTimeoutReturnsJSONTimeoutReason(t *testing.T) { + t.Parallel() + timeout := 50 * time.Millisecond + handler := withTimeout(timeout, func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) { + <-r.Context().Done() + return http.StatusOK, nil + }) + + req := httptest.NewRequest(http.MethodGet, "/test", nil) + rec := httptest.NewRecorder() + handler(rec, req) + + if rec.Code != http.StatusRequestTimeout { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusRequestTimeout) + } + if ct := rec.Header().Get("Content-Type"); ct != "application/json; charset=utf-8" { + t.Fatalf("content-type = %q", ct) + } + + var body HttpResponse + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if body.Status != http.StatusRequestTimeout { + t.Fatalf("body.status = %d", body.Status) + } + if body.Message != "request timed out after "+timeout.String() { + t.Fatalf("body.message = %q, want request timed out after %q", body.Message, timeout.String()) + } +} + +func TestWithTimeoutHandlerErrorBeforeDeadline(t *testing.T) { + t.Parallel() + handler := withTimeout(time.Second, func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) { + return http.StatusBadRequest, context.Canceled + }) + + req := httptest.NewRequest(http.MethodGet, "/test", nil) + rec := httptest.NewRecorder() + handler(rec, req) + + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusBadRequest) + } + var body HttpResponse + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if body.Message != context.Canceled.Error() { + t.Fatalf("body.message = %q", body.Message) + } +} diff --git a/backend/http/oidc.go b/backend/internal/web/oidc.go similarity index 82% rename from backend/http/oidc.go rename to backend/internal/web/oidc.go index fb3fa3af39..3fd5870062 100644 --- a/backend/http/oidc.go +++ b/backend/internal/web/oidc.go @@ -1,4 +1,4 @@ -package http +package web import ( "crypto/tls" @@ -12,14 +12,14 @@ import ( "time" "github.com/coreos/go-oidc/v3/oidc" - "github.com/gtsteffaniak/filebrowser/backend/auth" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/storage" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "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/utils" "github.com/gtsteffaniak/go-logger/logger" "golang.org/x/oauth2" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + ) // userInfo holds all claims dynamically, plus pre-parsed Groups. @@ -150,6 +150,12 @@ func parseOIDCGroupsValue(groupsVal interface{}) []string { return groups } +// OidcRedirectURL builds the OAuth redirect_uri from trusted forwarded headers and the request host. +func OidcRedirectURL(r *http.Request) string { + host, scheme := shareURLParams(r) + return fmt.Sprintf("%s://%s%sapi/auth/oidc/callback", scheme, host, settings.Config.Http.BaseURL) +} + // oidcLoginHandler initiates OIDC login. // @Summary OIDC login // @Description Initiates OIDC login flow. @@ -158,21 +164,17 @@ func parseOIDCGroupsValue(groupsVal interface{}) []string { // @Produce json // @Success 302 {string} string "Redirect to OIDC provider" // @Router /api/auth/oidc/login [get] -func oidcLoginHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - oidcCfg := config.Auth.Methods.OidcAuth +func oidcLoginHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + oidcCfg := settings.Config.Auth.Methods.OidcAuth if !oidcCfg.Enabled { return http.StatusForbidden, fmt.Errorf("oidc authentication is not enabled") } - origin := r.Header.Get("Origin") - if origin == "" { - origin = fmt.Sprintf("%s://%s", getScheme(r), r.Host) - } oauth2Config := &oauth2.Config{ ClientID: oidcCfg.ClientID, ClientSecret: oidcCfg.ClientSecret, Endpoint: oidcCfg.Provider.Endpoint(), - RedirectURL: fmt.Sprintf("%s%sapi/auth/oidc/callback", origin, config.Server.BaseURL), + RedirectURL: OidcRedirectURL(r), Scopes: strings.Fields(oidcCfg.Scopes), } @@ -195,9 +197,9 @@ func oidcLoginHandler(w http.ResponseWriter, r *http.Request, d *requestContext) // @Success 200 {object} map[string]string "OIDC callback result" // @Failure 400 {object} map[string]string "Bad request" // @Router /api/auth/oidc/callback [get] -func oidcCallbackHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func oidcCallbackHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { ctx := r.Context() - oidcCfg := config.Auth.Methods.OidcAuth + oidcCfg := settings.Config.Auth.Methods.OidcAuth if oidcCfg.Provider == nil || oidcCfg.Verifier == nil { // Ensure Provider and Verifier are initialized on application startup // This check is good, keep it. @@ -219,17 +221,11 @@ func oidcCallbackHandler(w http.ResponseWriter, r *http.Request, d *requestConte code := r.URL.Query().Get("code") // state := r.URL.Query().Get("state") // You might want to validate the state parameter for CSRF protection - // The redirect URI MUST match the one registered with the OIDC provider - // and used in the initial /api/auth/oidc/login handler. - // Using r.Host here might be tricky if running behind a proxy. - // Consider using a fixed redirect URL from settings if possible. - redirectURL := fmt.Sprintf("%s://%s%sapi/auth/oidc/callback", getScheme(r), r.Host, config.Server.BaseURL) - oauth2Config := &oauth2.Config{ ClientID: oidcCfg.ClientID, ClientSecret: oidcCfg.ClientSecret, Endpoint: oidcCfg.Provider.Endpoint(), // Use endpoint from discovered provider - RedirectURL: redirectURL, // Use the dynamically determined redirect URL + RedirectURL: OidcRedirectURL(r), Scopes: strings.Fields(oidcCfg.Scopes), } @@ -322,7 +318,7 @@ func oidcCallbackHandler(w http.ResponseWriter, r *http.Request, d *requestConte // based on the configured UserIdentifier and logs the user into the application. // It creates a new user if one doesn't exist. func loginWithOidcUser(w http.ResponseWriter, r *http.Request, username string, groups []string) (int, error) { - oidcCfg := config.Auth.Methods.OidcAuth + oidcCfg := settings.Config.Auth.Methods.OidcAuth // Check if user is in required groups (if userGroups is configured) if len(oidcCfg.UserGroups) > 0 { @@ -340,60 +336,26 @@ func loginWithOidcUser(w http.ResponseWriter, r *http.Request, username string, logger.Debugf("User %s is in required group, allowing access.", username) } - isAdmin := false // Default to non-admin user + // Determine if user should be admin + isAdmin := false if oidcCfg.AdminGroup != "" { if slices.Contains(groups, oidcCfg.AdminGroup) { - isAdmin = true // User is in the admin group, grant admin privileges + isAdmin = true logger.Debugf("User %s is in admin group %s, granting admin privileges.", username, oidcCfg.AdminGroup) } - } - logger.Debugf("Successfully authenticated OIDC username: %s isAdmin: %v", username, isAdmin) - // Retrieve the user from the store and store it in the context - user, err := store.Users.Get(username) - if err != nil { - if err.Error() != "the resource does not exist" { - return http.StatusInternalServerError, err - } - // Auto-create user on first OIDC authentication - if oidcCfg.AdminGroup == "" { - isAdmin = config.UserDefaults.Permissions.Admin - } - user = &users.User{ - Username: username, - LoginMethod: users.LoginMethodOidc, - } - settings.ApplyUserDefaults(user) - if isAdmin { - user.Permissions.Admin = true - } - err = storage.CreateUser(*user, user.Permissions) - if err != nil { - return http.StatusInternalServerError, err - } - user, err = store.Users.Get(username) - if err != nil { - return http.StatusInternalServerError, err - } } else { - // update user admin perms - if isAdmin != user.Permissions.Admin && oidcCfg.AdminGroup != "" { - user.Permissions.Admin = isAdmin - err = store.Users.Update(user, true, "Permissions") - if err != nil { - logger.Warningf("failed to update oidc user %s admin permissions: %v", username, err) - } - } - } - if user.LoginMethod != users.LoginMethodOidc { - return http.StatusForbidden, errors.ErrWrongLoginMethod + // If no admin group configured, use default permissions + isAdmin = settings.Config.UserDefaults.Account.Permissions.Admin } - // Sync OIDC groups with access control system - if err = store.Access.SyncUserGroups(username, groups); err != nil { - logger.Warningf("failed to sync oidc user %s groups: %v", username, err) + logger.Debugf("Successfully authenticated OIDC username: %s isAdmin: %v", username, isAdmin) + + user, err := getOrCreateAuthenticatedUser(username, users.LoginMethodOidc, isAdmin, groups) + if err != nil { + return http.StatusUnauthorized, err } - expires := time.Hour * time.Duration(config.Auth.TokenExpirationHours) + expires := time.Hour * time.Duration(settings.Config.Auth.TokenExpirationHours) // Generate a signed token for the user tokenString, _, err2 := auth.MakeSignedTokenAPI(user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), expires, user.Permissions, false) if err2 != nil { @@ -409,11 +371,7 @@ func loginWithOidcUser(w http.ResponseWriter, r *http.Request, username string, expiresTime := time.Now().Add(expires).Add(time.Minute * 30) // Set the authentication token as an HTTP cookie - // Get the correct domain for cookie - prefer X-Forwarded-Host from reverse proxy - host := r.Header.Get("X-Forwarded-Host") - if host == "" { - host = r.Host - } + host := requestHost(r) cookie := &http.Cookie{ Name: "filebrowser_quantum_jwt", Value: tokenString, @@ -428,14 +386,16 @@ func loginWithOidcUser(w http.ResponseWriter, r *http.Request, username string, // Set the authenticated user in the request context or response writer // This allows subsequent handlers to access the current user. - setUserInResponseWriter(w, user) + SetUserInResponseWriter(w, user) + + activity.RecordLogin(r, user) // Redirect the user to the page they were trying to access before login, // or to the root ("/") if no specific redirect was requested. // The 'fb_redirect' parameter is extracted from the 'state' parameter for security. state := r.URL.Query().Get("state") - fbRedirect := config.Server.BaseURL // Default redirect to the base URL + fbRedirect := settings.Config.Http.BaseURL // Default redirect to the base URL if state != "" { parts := strings.SplitN(state, ":", 2) diff --git a/backend/http/oidc_test.go b/backend/internal/web/oidc_test.go similarity index 72% rename from backend/http/oidc_test.go rename to backend/internal/web/oidc_test.go index 1fdb450645..3fd9f46a30 100644 --- a/backend/http/oidc_test.go +++ b/backend/internal/web/oidc_test.go @@ -1,9 +1,12 @@ -package http +package web import ( "encoding/json" + "net/http/httptest" "reflect" "testing" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" ) func TestUserInfoUnmarshaller(t *testing.T) { @@ -19,9 +22,9 @@ func TestUserInfoUnmarshaller(t *testing.T) { groupsClaim: "groups", expected: userInfo{ Claims: map[string]interface{}{ - "name": "John", - "email": "john@example.com", - "groups": []interface{}{"admin","users"}, + "name": "John", + "email": "john@example.com", + "groups": []interface{}{"admin", "users"}, }, Groups: []string{"admin", "users"}, }, @@ -32,9 +35,9 @@ func TestUserInfoUnmarshaller(t *testing.T) { groupsClaim: "roles", expected: userInfo{ Claims: map[string]interface{}{ - "name": "Jane", + "name": "Jane", "email": "jane@example.com", - "roles": []interface{}{"admin","users"}, + "roles": []interface{}{"admin", "users"}, }, Groups: []string{"admin", "users"}, }, @@ -45,8 +48,8 @@ func TestUserInfoUnmarshaller(t *testing.T) { groupsClaim: "groups", expected: userInfo{ Claims: map[string]interface{}{ - "name": "Bob", - "email": "bob@example.com", + "name": "Bob", + "email": "bob@example.com", "groups": "admin, users, guests", }, Groups: []string{"admin", "users", "guests"}, @@ -58,7 +61,7 @@ func TestUserInfoUnmarshaller(t *testing.T) { groupsClaim: "groups", expected: userInfo{ Claims: map[string]interface{}{ - "name": "Alice", + "name": "Alice", "email": "alice@example.com", }, Groups: nil, @@ -70,8 +73,8 @@ func TestUserInfoUnmarshaller(t *testing.T) { groupsClaim: "groups", expected: userInfo{ Claims: map[string]interface{}{ - "name": "Charlie", - "email": "charlie@example.com", + "name": "Charlie", + "email": "charlie@example.com", "groups": []interface{}{}, }, Groups: []string{}, @@ -83,7 +86,7 @@ func TestUserInfoUnmarshaller(t *testing.T) { groupsClaim: "groups", expected: userInfo{ Claims: map[string]interface{}{ - "sub": "auth0|123", + "sub": "auth0|123", "preferred_username": "jdoe", "email": "jdoe@example.com", }, @@ -122,7 +125,7 @@ func TestUserInfoUnmarshaller(t *testing.T) { Claims: map[string]interface{}{ "username": "john", "custom": map[string]interface{}{ - "groups": []interface{}{"admin","users"}, + "groups": []interface{}{"admin", "users"}, }, }, Groups: []string{"admin", "users"}, @@ -137,7 +140,7 @@ func TestUserInfoUnmarshaller(t *testing.T) { "sub": "user123", "resource_access": map[string]interface{}{ "filebrowser-client": map[string]interface{}{ - "roles": []interface{}{"admin","editor","viewer"}, + "roles": []interface{}{"admin", "editor", "viewer"}, }, }, }, @@ -202,3 +205,43 @@ func TestUserInfoUnmarshaller_InvalidJSON(t *testing.T) { t.Fatal("Unmarshal expected to fail on invalid JSON") } } + +func TestOidcRedirectURLTrustProxyHeaders(t *testing.T) { + settings.Config.Http.BaseURL = "/" + settings.Config.Http.TrustProxyHeaders = true + t.Cleanup(func() { + settings.Config.Http.BaseURL = "/" + settings.Config.Http.TrustProxyHeaders = false + }) + + req := httptest.NewRequest("GET", "http://127.0.0.1:8080/api/auth/oidc/login", nil) + req.Host = "127.0.0.1:8080" + req.Header.Set("X-Forwarded-Proto", "https") + req.Header.Set("X-Forwarded-Host", "filebrowser.example.com") + + got := OidcRedirectURL(req) + want := "https://filebrowser.example.com/api/auth/oidc/callback" + if got != want { + t.Fatalf("OidcRedirectURL = %q, want %q", got, want) + } +} + +func TestOidcRedirectURLWithoutTrustProxyHeaders(t *testing.T) { + settings.Config.Http.BaseURL = "/files/" + settings.Config.Http.TrustProxyHeaders = false + t.Cleanup(func() { + settings.Config.Http.BaseURL = "/" + settings.Config.Http.TrustProxyHeaders = false + }) + + req := httptest.NewRequest("GET", "http://filebrowser.example.com/files/api/auth/oidc/login", nil) + req.Host = "filebrowser.example.com" + req.Header.Set("X-Forwarded-Proto", "https") + req.Header.Set("X-Forwarded-Host", "spoofed.example.com") + + got := OidcRedirectURL(req) + want := "http://filebrowser.example.com/files/api/auth/oidc/callback" + if got != want { + t.Fatalf("OidcRedirectURL = %q, want %q", got, want) + } +} diff --git a/backend/http/onlyOffice.go b/backend/internal/web/onlyOffice.go similarity index 73% rename from backend/http/onlyOffice.go rename to backend/internal/web/onlyOffice.go index 53606206f5..c386b08e67 100644 --- a/backend/http/onlyOffice.go +++ b/backend/internal/web/onlyOffice.go @@ -1,4 +1,4 @@ -package http +package web import ( "encoding/base64" @@ -14,11 +14,11 @@ import ( "time" jwt "github.com/golang-jwt/jwt/v4" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "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" ) @@ -89,8 +89,8 @@ type OnlyOfficeJWTPayload struct { // @Failure 500 {object} map[string]string "Server error" // @Router /api/office/config [get] // @Security ApiKeyAuth -func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if config.Integrations.OnlyOffice.Url == "" { +func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if settings.Config.Integrations.OnlyOffice.Url == "" { return http.StatusInternalServerError, errors.New("only-office integration must be configured in settings") } @@ -106,23 +106,23 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d } // Rule 1: Validate user-provided path to prevent path traversal - cleanPath, err := utils.SanitizeUserPath(providedPath) + cleanPath, err := utils.SanitizePath(providedPath) if err != nil { return http.StatusBadRequest, err } providedPath = cleanPath - themeMode := utils.Ternary(d.user.DarkMode, "dark", "light") + themeMode := utils.Ternary(d.User.DarkMode, "dark", "light") var sourceInfo *settings.Source var ok bool if hash != "" { - sourceInfo, ok = config.Server.SourceMap[d.share.Source] + sourceInfo, ok = settings.Config.Server.SourceMap[d.Share.SourcePath] if !ok { logger.Error("OnlyOffice: source not found") return http.StatusInternalServerError, fmt.Errorf("source not found") } } else { - sourceInfo, ok = config.Server.NameToSource[source] + sourceInfo, ok = settings.Config.Server.NameToSource[source] if !ok { logger.Error("OnlyOffice: source not found") return http.StatusInternalServerError, fmt.Errorf("source not found") @@ -140,41 +140,42 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d Source: source, Expand: false, FollowSymlinks: true, - }, store.Access, d.user, store.Share) + }, d.User) if err != nil { logger.Errorf("OnlyOffice: failed to get file info for source=%s, path=%s: %v", source, path, err) - return errToStatus(err), err + return ErrToStatus(err), err } - d.fileInfo = *fileInfo + d.FileInfo = *fileInfo } else { // path is index path, so we build from share path - path = utils.JoinPathAsUnix(d.share.Path, providedPath) - if d.share.EnforceDarkLightMode == "dark" { + path = utils.JoinPathAsUnix(d.Share.Path, providedPath) + if d.Share.EnforceDarkLightMode == "dark" { themeMode = "dark" } - if d.share.EnforceDarkLightMode == "light" { + if d.Share.EnforceDarkLightMode == "light" { themeMode = "light" } } // Determine file type and editing permissions - fileType := strings.TrimPrefix(filepath.Ext(d.fileInfo.Name), ".") + fileType := strings.TrimPrefix(filepath.Ext(d.FileInfo.Name), ".") - // Determine modify permissions based on whether this is a share or regular request - var modifyPerms bool - if d.fileInfo.Hash != "" && d.share != nil { - // Share request - check share permissions - modifyPerms = d.share.AllowModify - } else { - // Regular user request - check user permissions - modifyPerms = d.user.Permissions.Modify + filePerms, permErr := effectiveFilePerms(d, source) + if permErr != nil { + return http.StatusForbidden, permErr } + if !filePerms.View { + return http.StatusForbidden, fmt.Errorf("user is not allowed to view files in this source") + } + modifyPerms := filePerms.Modify + allowDownload := filePerms.Download + allowPrint := filePerms.View canEdit := iteminfo.CanEditOnlyOffice(modifyPerms, fileType) canEditMode := utils.Ternary(canEdit, "edit", "view") // Generate document ID for OnlyOffice - documentId, err := getOnlyOfficeId(d.fileInfo.RealPath) + documentId, err := GetOnlyOfficeId(d.FileInfo.RealPath) if err != nil { logger.Errorf("OnlyOffice: failed to generate document ID for source=%s, path=%s: %v", source, path, err) return http.StatusNotFound, fmt.Errorf("failed to generate document ID: %v", err) @@ -187,63 +188,70 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d } shareHash := "" - if d.fileInfo.Hash != "" { - shareHash = d.fileInfo.Hash + if d.FileInfo.Hash != "" { + shareHash = d.FileInfo.Hash } - logContext := createOnlyOfficeLogContext( - d.user.Username, + logContext := CreateOnlyOfficeLogContext( + d.User.Username, sessionID, documentId, path, source, shareHash, - d.user.Permissions.Admin, + d.User.Permissions.Admin, ) - storeOnlyOfficeLogContext(documentId, logContext) + StoreOnlyOfficeLogContext(documentId, logContext) // Send initial log event with detailed path information - sendOnlyOfficeLogEvent(logContext, "INFO", "config", fmt.Sprintf("OnlyOffice session started for document: %s ", path)) + SendOnlyOfficeLogEvent(logContext, "INFO", "config", fmt.Sprintf("OnlyOffice session started for document: %s ", path)) - // Build download URL that OnlyOffice server will use - downloadURL := buildOnlyOfficeDownloadURL(r, source, providedPath, d.fileInfo.Hash, d.token) + // Mint source-scoped view grant for OnlyOffice document fetch (viewing, not download) + viewToken, err := mintViewGrant(d, source) + if err != nil { + logger.Errorf("OnlyOffice: failed to mint view grant: %v", err) + return http.StatusForbidden, err + } + + // Build view URL that OnlyOffice server will use to fetch the file + documentURL := buildOnlyOfficeViewURL(r, source, providedPath, d.FileInfo.Hash, viewToken, d.Token) // Build callback URL for OnlyOffice to notify us of changes - callbackURL := buildOnlyOfficeCallbackURL(r, source, providedPath, d.fileInfo.Hash, d.token) + callbackURL := buildOnlyOfficeCallbackURL(r, source, providedPath, d.FileInfo.Hash, d.Token) // Build OnlyOffice client configuration clientConfig := map[string]interface{}{ "document": map[string]interface{}{ "fileType": fileType, "key": documentId, - "title": d.fileInfo.Name, - "url": downloadURL, + "title": d.FileInfo.Name, + "url": documentURL, "permissions": map[string]interface{}{ - "edit": utils.Ternary(config.Integrations.OnlyOffice.ViewOnly, "view", canEditMode), - "download": true, - "print": true, + "edit": utils.Ternary(settings.Config.Integrations.OnlyOffice.ViewOnly, "view", canEditMode), + "download": allowDownload, + "print": allowPrint, }, }, "editorConfig": map[string]interface{}{ "callbackUrl": callbackURL, "user": map[string]interface{}{ - "id": strconv.FormatUint(uint64(d.user.ID), 10), - "name": d.user.Username, + "id": strconv.FormatUint(uint64(d.User.ID), 10), + "name": d.User.Username, }, "customization": map[string]interface{}{ "autosave": true, "forcesave": true, "uiTheme": themeMode, }, - "lang": d.user.Locale, - "mode": utils.Ternary(config.Integrations.OnlyOffice.ViewOnly, "view", canEditMode), + "lang": d.User.Locale, + "mode": utils.Ternary(settings.Config.Integrations.OnlyOffice.ViewOnly, "view", canEditMode), }, } // Sign configuration with JWT if secret is configured - if config.Integrations.OnlyOffice.Secret != "" { + if settings.Config.Integrations.OnlyOffice.Secret != "" { token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(clientConfig)) - signature, err := token.SignedString([]byte(config.Integrations.OnlyOffice.Secret)) + signature, err := token.SignedString([]byte(settings.Config.Integrations.OnlyOffice.Secret)) if err != nil { logger.Errorf("OnlyOffice: failed to sign JWT: %v", err) return http.StatusInternalServerError, fmt.Errorf("failed to sign configuration") @@ -251,109 +259,76 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d clientConfig["token"] = signature } - return renderJSON(w, r, clientConfig) + return RenderJSON(w, r, clientConfig) } -// buildOnlyOfficeDownloadURL constructs the download URL that OnlyOffice server will use to fetch the file -func buildOnlyOfficeDownloadURL(r *http.Request, source, path, hash, token string) string { - // Determine base URL (internal URL takes priority for OnlyOffice server communication) - var baseURL string - if config.Server.InternalUrl != "" { - // InternalUrl is a full URL (e.g., http://localhost:8080), so use it directly - internalURL := strings.TrimSuffix(config.Server.InternalUrl, "/") - baseURLPath := strings.TrimPrefix(config.Server.BaseURL, "/") +// onlyOfficeFileBrowserBaseURL returns the base URL OnlyOffice uses to reach FileBrowser. +// Priority: http.internalUrl → http.externalUrl → incoming request (with trustProxyHeaders). +// The result always ends with a single trailing slash when a base path is configured. +func onlyOfficeFileBrowserBaseURL(r *http.Request) string { + for _, configured := range []string{ + settings.Config.Http.InternalUrl, + settings.Config.Http.ExternalUrl, + } { + if configured == "" { + continue + } + root := strings.TrimSuffix(configured, "/") + baseURLPath := strings.Trim(settings.Config.Http.BaseURL, "/") if baseURLPath != "" { - baseURL = internalURL + "/" + baseURLPath - } else { - baseURL = internalURL + return root + "/" + baseURLPath + "/" } - } else { - // Extract scheme and host from request (respecting X-Forwarded-* headers) - var host string - var scheme string - - if forwardedHost := r.Header.Get("X-Forwarded-Host"); forwardedHost != "" { - host = forwardedHost - // Use X-Forwarded-Proto if available, otherwise default to https for proxied requests - if forwardedProto := r.Header.Get("X-Forwarded-Proto"); forwardedProto != "" { - scheme = forwardedProto - } else { - scheme = "https" - } - } else { - // Fallback to simple approach - host = r.Host - scheme = getScheme(r) - } - baseURL = fmt.Sprintf("%s://%s%s", scheme, host, config.Server.BaseURL) + return root + "/" } + host := requestHost(r) + scheme := requestSchemeForPublicURL(r) + baseURLPath := strings.Trim(settings.Config.Http.BaseURL, "/") + if baseURLPath == "" { + return fmt.Sprintf("%s://%s/", scheme, host) + } + return fmt.Sprintf("%s://%s/%s/", scheme, host, baseURLPath) +} - escapedPath := url.QueryEscape(path) - downloadURL := fmt.Sprintf("%s/api/resources/download?file=%s&auth=%s&source=%s", - strings.TrimSuffix(baseURL, "/"), escapedPath, token, url.QueryEscape(source)) +// joinOnlyOfficeAPIURL appends an API path to a base URL that may end with "/". +func joinOnlyOfficeAPIURL(baseURL, apiPath string) string { + base := strings.TrimRight(baseURL, "/") + path := strings.TrimLeft(apiPath, "/") + return base + "/" + path +} + +// buildOnlyOfficeViewURL constructs the view URL that OnlyOffice server uses to fetch the document. +func buildOnlyOfficeViewURL(r *http.Request, source, path, hash, viewToken, authToken string) string { + baseURL := onlyOfficeFileBrowserBaseURL(r) + params := url.Values{} + params.Set("file", path) + params.Set("viewToken", viewToken) if hash != "" { - downloadURL = fmt.Sprintf("%s/public/api/resources/download?file=%s&auth=%s&hash=%s", - strings.TrimSuffix(baseURL, "/"), escapedPath, token, hash) + params.Set("hash", hash) + return joinOnlyOfficeAPIURL(baseURL, "public/api/resources/view") + "?" + params.Encode() } - return downloadURL + params.Set("source", source) + params.Set("auth", authToken) + return joinOnlyOfficeAPIURL(baseURL, "api/resources/view") + "?" + params.Encode() } // buildOnlyOfficeCallbackURL constructs the callback URL that OnlyOffice server will use to notify us of changes func buildOnlyOfficeCallbackURL(r *http.Request, source, path, hash, token string) string { - // Determine base URL (internal URL takes priority for OnlyOffice server communication) - var baseURL string - if config.Server.InternalUrl != "" { - // InternalUrl is a full URL (e.g., http://localhost:8080), so use it directly - internalURL := strings.TrimSuffix(config.Server.InternalUrl, "/") - baseURLPath := strings.TrimPrefix(config.Server.BaseURL, "/") - if baseURLPath != "" { - baseURL = internalURL + "/" + baseURLPath - } else { - baseURL = internalURL - } - } else { - // Extract scheme and host from request (respecting X-Forwarded-* headers) - var host string - var scheme string + baseURL := onlyOfficeFileBrowserBaseURL(r) - if forwardedHost := r.Header.Get("X-Forwarded-Host"); forwardedHost != "" { - host = forwardedHost - // Use X-Forwarded-Proto if available, otherwise default to https for proxied requests - if forwardedProto := r.Header.Get("X-Forwarded-Proto"); forwardedProto != "" { - scheme = forwardedProto - } else { - scheme = "https" - } - } else { - // Fallback to simple approach - host = r.Host - scheme = getScheme(r) - } - baseURL = fmt.Sprintf("%s://%s%s", scheme, host, config.Server.BaseURL) - } - - var callbackURL string + params := url.Values{} if hash != "" { // Share callback URL - use public API and don't expose source, use path relative to share - params := url.Values{} params.Set("hash", hash) - params.Set("path", path) // This should be the path relative to the share, not the full filesystem path - params.Set("auth", token) - - callbackURL = fmt.Sprintf("%s/public/api/office/callback?%s", - strings.TrimSuffix(baseURL, "/"), params.Encode()) - } else { - // Regular callback URL - include source for non-share requests - params := url.Values{} - params.Set("source", source) params.Set("path", path) params.Set("auth", token) - - callbackURL = fmt.Sprintf("%s/api/office/callback?%s", - strings.TrimSuffix(baseURL, "/"), params.Encode()) + return joinOnlyOfficeAPIURL(baseURL, "public/api/office/callback") + "?" + params.Encode() } - return callbackURL + // Regular callback URL - include source for non-share requests + params.Set("source", source) + params.Set("path", path) + params.Set("auth", token) + return joinOnlyOfficeAPIURL(baseURL, "api/office/callback") + "?" + params.Encode() } // resolveOnlyOfficeDownloadURL validates a callback document URL against @@ -365,7 +340,7 @@ func resolveOnlyOfficeDownloadURL(rawURL string) string { return "" } - publicBase := config.Integrations.OnlyOffice.Url + publicBase := settings.Config.Integrations.OnlyOffice.Url if publicBase == "" { logger.Warningf("OnlyOffice callback: integrations.office.url is not configured") return "" @@ -389,7 +364,7 @@ func resolveOnlyOfficeDownloadURL(rawURL string) string { return "" } - internalBase := config.Integrations.OnlyOffice.InternalUrl + internalBase := settings.Config.Integrations.OnlyOffice.InternalUrl if internalBase == "" { return rawURL } @@ -448,26 +423,26 @@ func onlyOfficeURLHostsMatch(callback, configured *url.URL) bool { } // processOnlyOfficeCallback handles the common callback processing logic for both GET and POST requests -func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *requestContext, data *OnlyOfficeCallback) (int, error) { +func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *Context, data *OnlyOfficeCallback) (int, error) { // Extract clean parameters from query string source := r.URL.Query().Get("source") path := r.URL.Query().Get("path") - user := d.user + user := d.User - if d.share != nil { - source = d.share.GetSourceName() + if d.Share.Hash != "" { + source = d.Share.GetSourceName() path = d.IndexPath - user = d.shareUser + user = d.ShareUser } // Validate required parameters - if (path == "" || source == "") && d.fileInfo.Hash == "" { + if (path == "" || source == "") && d.FileInfo.Hash == "" { logger.Errorf("OnlyOffice callback missing required parameters: source=%s, path=%s", source, path) return returnOnlyOfficeError(w, r, 400, "missing required parameters: path + source/hash are required") } // Rule 1: Validate user-provided path to prevent path traversal - cleanPath, err := utils.SanitizeUserPath(path) + cleanPath, err := utils.SanitizePath(path) if err != nil { return returnOnlyOfficeError(w, r, 400, err.Error()) } @@ -485,13 +460,13 @@ func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *reques deleteOfficeId(source, path, user) // Send log event for document closure and clean up log context - if logContext := getOnlyOfficeLogContext(data.Key); logContext != nil { + if logContext := GetOnlyOfficeLogContext(data.Key); logContext != nil { statusMsg := "Document closed with changes" if data.Status == onlyOfficeStatusDocumentClosedWithNoChanges { statusMsg = "Document closed with no changes" } - sendOnlyOfficeLogEvent(logContext, "INFO", "callback", statusMsg) - removeOnlyOfficeLogContext(data.Key) + SendOnlyOfficeLogEvent(logContext, "INFO", "callback", statusMsg) + RemoveOnlyOfficeLogContext(data.Key) } } @@ -500,8 +475,8 @@ func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *reques logger.Debugf("OnlyOffice callback: document being edited, key=%s, users=%v", data.Key, data.Users) // Send log event for document being edited - if logContext := getOnlyOfficeLogContext(data.Key); logContext != nil { - sendOnlyOfficeLogEvent(logContext, "DEBUG", "callback", fmt.Sprintf("Document being edited, users: %v", data.Users)) + if logContext := GetOnlyOfficeLogContext(data.Key); logContext != nil { + SendOnlyOfficeLogEvent(logContext, "DEBUG", "callback", fmt.Sprintf("Document being edited, users: %v", data.Users)) } // Handle actions if present @@ -523,8 +498,8 @@ func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *reques } // Send log event for action - if logContext := getOnlyOfficeLogContext(data.Key); logContext != nil { - sendOnlyOfficeLogEvent(logContext, "DEBUG", "callback", actionMsg) + if logContext := GetOnlyOfficeLogContext(data.Key); logContext != nil { + SendOnlyOfficeLogEvent(logContext, "DEBUG", "callback", actionMsg) } } } @@ -552,21 +527,21 @@ func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *reques statusDesc, data.Key, data.URL, data.ForceSaveType) // Send log event for save operation - if logContext := getOnlyOfficeLogContext(data.Key); logContext != nil { - sendOnlyOfficeLogEvent(logContext, "INFO", "callback", fmt.Sprintf("Processing save operation: %s", statusDesc)) + if logContext := GetOnlyOfficeLogContext(data.Key); logContext != nil { + SendOnlyOfficeLogEvent(logContext, "INFO", "callback", fmt.Sprintf("Processing save operation: %s", statusDesc)) } // Handle history and changes URL if present if data.History != nil { logger.Debugf("OnlyOffice callback: received history data with serverVersion=%s", data.History.ServerVersion) - if logContext := getOnlyOfficeLogContext(data.Key); logContext != nil { - sendOnlyOfficeLogEvent(logContext, "DEBUG", "callback", fmt.Sprintf("Received history data with serverVersion=%s", data.History.ServerVersion)) + if logContext := GetOnlyOfficeLogContext(data.Key); logContext != nil { + SendOnlyOfficeLogEvent(logContext, "DEBUG", "callback", fmt.Sprintf("Received history data with serverVersion=%s", data.History.ServerVersion)) } } if data.ChangesURL != "" { logger.Debugf("OnlyOffice callback: received changes URL: %s", data.ChangesURL) - if logContext := getOnlyOfficeLogContext(data.Key); logContext != nil { - sendOnlyOfficeLogEvent(logContext, "DEBUG", "callback", "Received changes URL for document history") + if logContext := GetOnlyOfficeLogContext(data.Key); logContext != nil { + SendOnlyOfficeLogEvent(logContext, "DEBUG", "callback", "Received changes URL for document history") } } @@ -576,27 +551,20 @@ func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *reques return returnOnlyOfficeSuccess(w, r) } - // Check share permissions first if this is a share request - if d.share != nil { - if !d.share.AllowModify { - logger.Errorf("OnlyOffice callback: edit permission not allowed for this share") - return returnOnlyOfficeError(w, r, 403, "edit permission not allowed for this share") - } - } else { - // Verify user has modify permissions - if !user.Permissions.Modify { - logger.Errorf("OnlyOffice callback: user %s lacks modify permissions for path=%s", - d.user.Username, path) - return returnOnlyOfficeError(w, r, 403, "user lacks modify permissions") - } + // Check modify permission for save operations + filePerms, permErr := effectiveFilePerms(d, source) + if permErr != nil || !filePerms.Modify { + logger.Errorf("OnlyOffice callback: user %s lacks modify permissions for source=%s path=%s", + user.Username, source, path) + return returnOnlyOfficeError(w, r, 403, "user lacks modify permissions") } - // Download the updated document from OnlyOffice server downloadURL := resolveOnlyOfficeDownloadURL(data.URL) if downloadURL == "" { logger.Errorf("OnlyOffice callback: missing or untrusted document URL in callback payload") - return returnOnlyOfficeError(w, r, 500, "missing or untrusted document URL in callback payload") + return returnOnlyOfficeError(w, r, 400, "missing or untrusted document URL") } + doc, err := onlyOfficeDownloadClient.Get(downloadURL) if err != nil { logger.Errorf("OnlyOffice callback: failed to download updated document: %v", err) @@ -614,8 +582,8 @@ func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *reques path) // Send detailed log event for file saving with path information - if logContext := getOnlyOfficeLogContext(data.Key); logContext != nil { - sendOnlyOfficeLogEvent(logContext, "INFO", "callback", fmt.Sprintf("Saving document to path: %s", path)) + if logContext := GetOnlyOfficeLogContext(data.Key); logContext != nil { + SendOnlyOfficeLogEvent(logContext, "INFO", "callback", fmt.Sprintf("Saving document to path: %s", path)) } // CRITICAL: Validate that the original file still exists before saving @@ -623,14 +591,14 @@ func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *reques _, err = files.FileInfoFaster(utils.FileOptions{ Source: source, Path: path, - }, store.Access, user, store.Share) + }, user) if err != nil { logger.Errorf("OnlyOffice callback: original file no longer exists at path=%s: %v", path, err) // Send error log event with path information - if logContext := getOnlyOfficeLogContext(data.Key); logContext != nil { - sendOnlyOfficeLogEvent(logContext, "ERROR", "callback", + if logContext := GetOnlyOfficeLogContext(data.Key); logContext != nil { + SendOnlyOfficeLogEvent(logContext, "ERROR", "callback", fmt.Sprintf("Original file no longer exists at path: %s - %v -- was it renamed or moved?", path, err)) } @@ -650,8 +618,8 @@ func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *reques path, writeErr) // Send error log event with path information - if logContext := getOnlyOfficeLogContext(data.Key); logContext != nil { - sendOnlyOfficeLogEvent(logContext, "ERROR", "callback", fmt.Sprintf("Failed to save document to path: %s - %v", path, writeErr)) + if logContext := GetOnlyOfficeLogContext(data.Key); logContext != nil { + SendOnlyOfficeLogEvent(logContext, "ERROR", "callback", fmt.Sprintf("Failed to save document to path: %s - %v", path, writeErr)) } return returnOnlyOfficeError(w, r, 500, "failed to save document") @@ -661,8 +629,8 @@ func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *reques path) // Send success log event with detailed path information - if logContext := getOnlyOfficeLogContext(data.Key); logContext != nil { - sendOnlyOfficeLogEvent(logContext, "INFO", "callback", fmt.Sprintf("Document saved successfully to path: %s", path)) + if logContext := GetOnlyOfficeLogContext(data.Key); logContext != nil { + SendOnlyOfficeLogEvent(logContext, "INFO", "callback", fmt.Sprintf("Document saved successfully to path: %s", path)) } } @@ -686,7 +654,7 @@ func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *reques // @Router /api/office/callback [post] // @Router /api/office/callback [get] // @Security ApiKeyAuth -func onlyofficeCallbackHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func onlyofficeCallbackHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { // Parse callback data based on request method var callbackData *OnlyOfficeCallback var err error @@ -745,7 +713,7 @@ func parseOnlyOfficeCallbackFromJSON(r *http.Request) (*OnlyOfficeCallback, erro return &data, nil } -func getOnlyOfficeId(realpath string) (string, error) { +func GetOnlyOfficeId(realpath string) (string, error) { // error is intentionally ignored in order treat errors // the same as a cache-miss cachedDocumentKey, ok := utils.OnlyOfficeCache.Get(realpath) @@ -761,7 +729,7 @@ func deleteOfficeId(source, path string, user *users.User) { Source: source, Expand: false, FollowSymlinks: true, - }, store.Access, user, store.Share) + }, user) key := path if fi != nil && fi.RealPath != "" { key = fi.RealPath @@ -845,7 +813,7 @@ func returnOnlyOfficeSuccess(w http.ResponseWriter, r *http.Request) (int, error resp := map[string]int{ "error": 0, } - return renderJSON(w, r, resp) + return RenderJSON(w, r, resp) } // returnOnlyOfficeError returns an error response to OnlyOffice server with proper status code @@ -874,5 +842,5 @@ func returnOnlyOfficeError(w http.ResponseWriter, r *http.Request, statusCode in // Set the appropriate HTTP status code w.WriteHeader(statusCode) - return renderJSON(w, r, resp) + return RenderJSON(w, r, resp) } diff --git a/backend/internal/web/onlyOffice_test.go b/backend/internal/web/onlyOffice_test.go new file mode 100644 index 0000000000..4ea210e357 --- /dev/null +++ b/backend/internal/web/onlyOffice_test.go @@ -0,0 +1,377 @@ +package web + +import ( + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func TestOnlyOfficeClientConfigDeniedWithoutView(t *testing.T) { + initStreamTestSources(t) + + origOnlyOffice := settings.Config.Integrations.OnlyOffice + origNameToSource := settings.Config.Server.NameToSource + t.Cleanup(func() { + settings.Config.Integrations.OnlyOffice = origOnlyOffice + settings.Config.Server.NameToSource = origNameToSource + }) + + settings.Config.Integrations.OnlyOffice.Url = "http://onlyoffice.example" + settings.Config.Server.NameToSource = map[string]*settings.Source{ + "default": {Name: "default", Path: "/default"}, + } + + originalFileInfoFaster := files.FileInfoFasterFunc + t.Cleanup(func() { files.FileInfoFasterFunc = originalFileInfoFaster }) + files.FileInfoFasterFunc = func(opts utils.FileOptions, user *users.User) (*iteminfo.ExtendedFileInfo, error) { + return &iteminfo.ExtendedFileInfo{ + FileInfo: iteminfo.FileInfo{ + ItemInfo: iteminfo.ItemInfo{Name: "doc.docx", Type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, + Path: opts.Path, + }, + RealPath: "/tmp/doc.docx", + }, nil + } + + user := testUserWithSourcePerms("/default", users.SourceFilePermissions{ + View: false, Download: true, Modify: true, + }) + d := &requestContext{User: user} + + req := httptest.NewRequest(http.MethodGet, "/api/office/config?source=default&path=/doc.docx", nil) + status, err := onlyofficeClientConfigGetHandler(httptest.NewRecorder(), req, d) + if status != http.StatusForbidden { + t.Fatalf("status = %d, want %d (err: %v)", status, http.StatusForbidden, err) + } +} + +func TestBuildOnlyOfficeViewURL(t *testing.T) { + origHTTP := settings.Config.Http + t.Cleanup(func() { settings.Config.Http = origHTTP }) + settings.Config.Http.InternalUrl = "http://filebrowser:8080" + settings.Config.Http.BaseURL = "/testing/" + + req := httptest.NewRequest(http.MethodGet, "/", nil) + got := buildOnlyOfficeViewURL(req, "Downloads", "/doc.docx", "", "view-token", "session.jwt.token") + want := "http://filebrowser:8080/testing/api/resources/view?auth=session.jwt.token&file=%2Fdoc.docx&source=Downloads&viewToken=view-token" + if got != want { + t.Fatalf("buildOnlyOfficeViewURL() = %q, want %q", got, want) + } + + shareGot := buildOnlyOfficeViewURL(req, "Downloads", "/doc.docx", "share-hash", "view-token", "session.jwt.token") + shareWant := "http://filebrowser:8080/testing/public/api/resources/view?file=%2Fdoc.docx&hash=share-hash&viewToken=view-token" + if shareGot != shareWant { + t.Fatalf("buildOnlyOfficeViewURL(share) = %q, want %q", shareGot, shareWant) + } +} + +func TestJoinOnlyOfficeAPIURL(t *testing.T) { + tests := []struct { + base string + path string + want string + }{ + {"http://host/testing/", "api/resources/view", "http://host/testing/api/resources/view"}, + {"http://host/testing", "api/resources/view", "http://host/testing/api/resources/view"}, + {"http://host/", "public/api/resources/view", "http://host/public/api/resources/view"}, + {"http://host//", "/api/office/callback", "http://host/api/office/callback"}, + } + for _, tt := range tests { + got := joinOnlyOfficeAPIURL(tt.base, tt.path) + if got != tt.want { + t.Fatalf("joinOnlyOfficeAPIURL(%q, %q) = %q, want %q", tt.base, tt.path, got, tt.want) + } + } +} + +func TestOnlyOfficeUsesIndexedViewGrant(t *testing.T) { + initStreamTestSources(t) + + user := testUserWithView(42, "default") + d := &requestContext{User: user} + + token1, err := mintViewGrant(d, "default") + if err != nil { + t.Fatalf("mintViewGrant: %v", err) + } + token2, err := mintViewGrant(d, "default") + if err != nil { + t.Fatalf("mintViewGrant second: %v", err) + } + if token1 != token2 { + t.Fatalf("expected same indexed token, got %q and %q", token1, token2) + } + grant, ok := utils.ViewGrantsCache.Get(token1) + if !ok { + t.Fatal("grant not in cache") + } + if grant.Source != "default" { + t.Fatalf("grant.Source = %q, want default", grant.Source) + } +} + +func TestResolveOnlyOfficeDownloadURL(t *testing.T) { + orig := settings.Config.Integrations.OnlyOffice + t.Cleanup(func() { + settings.Config.Integrations.OnlyOffice = orig + }) + + settings.Config.Integrations.OnlyOffice.Url = "http://192.168.88.100:8282" + settings.Config.Integrations.OnlyOffice.InternalUrl = "http://onlyoffice" + + cachePath := "/cache/files/data/doc_1/output.ods/output.ods?md5=abc&expires=1" + publicURL := "http://192.168.88.100:8282" + cachePath + internalURL := "http://onlyoffice" + cachePath + + tests := []struct { + name string + input string + want string + }{ + { + name: "rewrites public cache URL to internal host", + input: publicURL, + want: internalURL, + }, + { + name: "empty URL", + input: "", + want: "", + }, + { + name: "untrusted host rejected", + input: "http://other-host:8282" + cachePath, + want: "", + }, + { + name: "non-http scheme rejected", + input: "ftp://192.168.88.100:8282" + cachePath, + want: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := resolveOnlyOfficeDownloadURL(tt.input) + if got != tt.want { + t.Errorf("resolveOnlyOfficeDownloadURL() = %q, want %q", got, tt.want) + } + }) + } + + t.Run("pass through public URL when internalUrl unset", func(t *testing.T) { + settings.Config.Integrations.OnlyOffice.InternalUrl = "" + got := resolveOnlyOfficeDownloadURL(publicURL) + if got != publicURL { + t.Errorf("resolveOnlyOfficeDownloadURL() = %q, want %q", got, publicURL) + } + }) + + t.Run("hostname match with default http port", func(t *testing.T) { + settings.Config.Integrations.OnlyOffice.Url = "http://office.local" + settings.Config.Integrations.OnlyOffice.InternalUrl = "http://onlyoffice" + input := "http://office.local:80" + cachePath + want := "http://onlyoffice" + cachePath + got := resolveOnlyOfficeDownloadURL(input) + if got != want { + t.Errorf("resolveOnlyOfficeDownloadURL() = %q, want %q", got, want) + } + }) + + t.Run("reject when public url not configured", func(t *testing.T) { + settings.Config.Integrations.OnlyOffice.Url = "" + settings.Config.Integrations.OnlyOffice.InternalUrl = "http://onlyoffice" + got := resolveOnlyOfficeDownloadURL(publicURL) + if got != "" { + t.Errorf("resolveOnlyOfficeDownloadURL() = %q, want empty", got) + } + }) +} + +func TestDeleteOfficeId(t *testing.T) { + const rawPath = "/docs/document.docx" + + tests := []struct { + name string + resolve func(utils.FileOptions) (*iteminfo.ExtendedFileInfo, error) + deleteKey string + remainKey string + }{ + { + name: "deletes resolved realpath", + resolve: func(utils.FileOptions) (*iteminfo.ExtendedFileInfo, error) { + return &iteminfo.ExtendedFileInfo{RealPath: "/some/path/document.docx"}, nil + }, + deleteKey: "/some/path/document.docx", + remainKey: rawPath, + }, + { + name: "fallback to raw path on error", + resolve: func(utils.FileOptions) (*iteminfo.ExtendedFileInfo, error) { + return nil, fmt.Errorf("could not resolve path") + }, + deleteKey: rawPath, + remainKey: "/some/path/document.docx", + }, + { + name: "also deletes realpath when partially resolved before erroring", + resolve: func(utils.FileOptions) (*iteminfo.ExtendedFileInfo, error) { + return &iteminfo.ExtendedFileInfo{RealPath: "/some/path/document.docx"}, fmt.Errorf("access check failed") + }, + deleteKey: "/some/path/document.docx", + remainKey: rawPath, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + origFunc := files.FileInfoFasterFunc + t.Cleanup(func() { files.FileInfoFasterFunc = origFunc }) + files.FileInfoFasterFunc = func(opts utils.FileOptions, user *users.User) (*iteminfo.ExtendedFileInfo, error) { + if opts.Path != rawPath { + t.Errorf("expected opts.Path=%q, got %q", rawPath, opts.Path) + } + if opts.Source != "source" { + t.Errorf("expected opts.Source=%q, got %q", "source", opts.Source) + } + if !opts.FollowSymlinks { + t.Error("expected FollowSymlinks=true") + } + return tt.resolve(opts) + } + utils.OnlyOfficeCache.Set(tt.deleteKey, "document-key") + utils.OnlyOfficeCache.Set(tt.remainKey, "other-key") + t.Cleanup(func() { + utils.OnlyOfficeCache.Delete(tt.deleteKey) + utils.OnlyOfficeCache.Delete(tt.remainKey) + }) + deleteOfficeId("source", rawPath, &users.User{}) + if _, err := GetOnlyOfficeId(tt.deleteKey); err == nil { + t.Errorf("expected cache entry %q to be deleted", tt.deleteKey) + } + if _, err := GetOnlyOfficeId(tt.remainKey); err != nil { + t.Errorf("expected cache entry %q to remain, but it was deleted", tt.remainKey) + } + }) + } +} + +func TestOnlyOfficeFileBrowserBaseURL(t *testing.T) { + origHTTP := settings.Config.Http + t.Cleanup(func() { settings.Config.Http = origHTTP }) + + settings.Config.Http.BaseURL = "/files/" + + tests := []struct { + name string + internalURL string + externalURL string + reqHost string + forwardedHost string + reqProto string + trustProxy bool + want string + }{ + { + name: "internalUrl wins", + internalURL: "http://filebrowser:80", + externalURL: "https://files.example.com", + want: "http://filebrowser:80/files/", + }, + { + name: "externalUrl when internal unset", + externalURL: "https://files.example.com", + want: "https://files.example.com/files/", + }, + { + name: "request fallback with trustProxyHeaders", + reqHost: "proxy.local", + reqProto: "https", + trustProxy: true, + want: "https://proxy.local/files/", + }, + { + name: "ignores untrusted forwarded host", + reqHost: "internal.local:8080", + forwardedHost: "evil.example.com", + want: "http://internal.local:8080/files/", + }, + { + name: "trusted host without proto defaults to https", + reqHost: "internal.local:8080", + forwardedHost: "public.example.com", + trustProxy: true, + want: "https://public.example.com/files/", + }, + { + name: "trusted host with proto honors proto", + reqHost: "internal.local:8080", + forwardedHost: "public.example.com", + reqProto: "http", + trustProxy: true, + want: "http://public.example.com/files/", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + settings.Config.Http.InternalUrl = tt.internalURL + settings.Config.Http.ExternalUrl = tt.externalURL + settings.Config.Http.TrustProxyHeaders = tt.trustProxy + + req := httptest.NewRequest(http.MethodGet, "/files/", nil) + req.Host = tt.reqHost + if tt.reqProto != "" { + req.Header.Set("X-Forwarded-Proto", tt.reqProto) + } + if fh := tt.forwardedHost; fh != "" { + req.Header.Set("X-Forwarded-Host", fh) + } else if tt.reqHost != "" && tt.trustProxy { + req.Header.Set("X-Forwarded-Host", tt.reqHost) + } + + got := onlyOfficeFileBrowserBaseURL(req) + if got != tt.want { + t.Errorf("onlyOfficeFileBrowserBaseURL() = %q, want %q", got, tt.want) + } + }) + } +} + +func TestOnlyOfficeURLHostsMatch(t *testing.T) { + mustParse := func(raw string) *url.URL { + t.Helper() + u, err := url.Parse(raw) + if err != nil { + t.Fatalf("url.Parse(%q): %v", raw, err) + } + return u + } + + if !onlyOfficeURLHostsMatch(mustParse("http://office.local:80/x"), mustParse("http://office.local/x")) { + t.Fatal("expected office.local:80 to match office.local with default port") + } + if onlyOfficeURLHostsMatch(mustParse("http://evil.example/x"), mustParse("http://office.local/x")) { + t.Fatal("expected different hostnames not to match") + } +} + +func testUserWithSourcePerms(sourcePath string, perms users.SourceFilePermissions) *users.User { + return &users.User{ + FrontendUser: users.FrontendUser{Username: "alice"}, + BackendScopes: []users.BackendScope{ + {Path: sourcePath, Scope: "/", Permissions: perms}, + }, + BackendSourcePermissions: map[string]users.SourceFilePermissions{ + sourcePath: perms, + }, + Version: users.SourcePermissionsMigrationVersion, + } +} diff --git a/backend/http/pinnedItems.go b/backend/internal/web/pinnedItems.go similarity index 70% rename from backend/http/pinnedItems.go rename to backend/internal/web/pinnedItems.go index 524d821846..3c1a42a7dc 100644 --- a/backend/http/pinnedItems.go +++ b/backend/internal/web/pinnedItems.go @@ -1,4 +1,4 @@ -package http +package web import ( "encoding/json" @@ -6,24 +6,19 @@ import ( "net/http" "strings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/filebrowser/backend/indexing" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" ) -// pinnedItemPatchRequest is the JSON body for PATCH /api/users/pinnedItems. +// pinnedItemPatchRequest is the JSON body for PATCH /api/users/pinned-items. type pinnedItemPatchRequest struct { Source string `json:"source" validate:"required"` Path string `json:"path" validate:"required"` // scope-relative parent directory Name string `json:"name" validate:"required"` // item basename within path } -// sharePinnedItemPatchRequest is the JSON body for PATCH /public/api/share/pinnedItems. -type sharePinnedItemPatchRequest struct { - Path string `json:"path" validate:"required"` // share-relative parent directory - Name string `json:"name" validate:"required"` // item basename within path -} - // scopeRelativeDirToIndexPath maps a scope-relative directory to source and index paths. func scopeRelativeDirToIndexPath(sourceName, userScope, directoryPath string) (sourcePath, indexDirPath string, err error) { userScope = strings.TrimRight(userScope, "/") @@ -36,25 +31,13 @@ func scopeRelativeDirToIndexPath(sourceName, userScope, directoryPath string) (s return "", "", fmt.Errorf("index not found for source %s", source.Name) } - cleanDir, err := utils.SanitizeUserPath(directoryPath) + cleanDir, err := utils.SanitizePath(directoryPath) if err != nil { return "", "", fmt.Errorf("invalid path: %w", err) } fullDirPath := utils.JoinPathAsUnix(userScope, cleanDir) - return source.Path, idx.MakeIndexPath(fullDirPath, true), nil -} - -// normalizeShareRelativeDir returns a normalized share-relative directory path key. -func normalizeShareRelativeDir(shareRelDir string) (string, error) { - if shareRelDir == "" || shareRelDir == "/" { - return "/", nil - } - cleanDir, err := utils.SanitizeUserPath(shareRelDir) - if err != nil { - return "", fmt.Errorf("invalid path: %w", err) - } - return utils.AddTrailingSlashIfNotExists(cleanDir), nil + return source.Path, idx.MakeIndexPath(fullDirPath, true).String(), nil } // pinnedItemAction returns the patch action query param, defaulting to "add". @@ -78,8 +61,8 @@ func pinnedItemAction(r *http.Request) string { // @Failure 400 {object} map[string]string "Bad Request" // @Failure 403 {object} map[string]string "Forbidden" // @Failure 500 {object} map[string]string "Internal Server Error" -// @Router /api/users/pinnedItems [patch] -func userPatchPinnedItemsHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +// @Router /api/users/pinned-items [patch] +func userPatchPinnedItemsHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { var body pinnedItemPatchRequest if err := json.NewDecoder(r.Body).Decode(&body); err != nil { return http.StatusBadRequest, fmt.Errorf("failed to decode body: %w", err) @@ -94,13 +77,13 @@ func userPatchPinnedItemsHandler(w http.ResponseWriter, r *http.Request, d *requ if body.Source == "" || body.Path == "" || body.Name == "" { return http.StatusBadRequest, fmt.Errorf("source, path, and name are required") } - cleanPath, err := utils.SanitizeUserPath(body.Path) + cleanPath, err := utils.SanitizePath(body.Path) if err != nil { return http.StatusBadRequest, err } body.Path = cleanPath - cleanName, err := utils.SanitizeUserPath(body.Name) + cleanName, err := utils.SanitizePath(body.Name) if err != nil { return http.StatusBadRequest, err } @@ -110,11 +93,11 @@ func userPatchPinnedItemsHandler(w http.ResponseWriter, r *http.Request, d *requ if !ok { return http.StatusBadRequest, fmt.Errorf("source not found: %s", body.Source) } - if !d.user.HasSourceByPath(source.Path) { + if !d.User.HasSourceByPath(source.Path) { return http.StatusForbidden, fmt.Errorf("access denied to source %s", body.Source) } - userScope, err := d.user.GetScopeForSourcePath(source.Path) + userScope, err := d.User.GetScopeForSourcePath(source.Path) if err != nil { return http.StatusForbidden, err } @@ -124,7 +107,7 @@ func userPatchPinnedItemsHandler(w http.ResponseWriter, r *http.Request, d *requ return http.StatusBadRequest, err } - u, err := store.Users.Get(d.user.ID) + u, err := state.GetUserByID(d.User.ID) if err != nil { return http.StatusInternalServerError, err } @@ -137,7 +120,7 @@ func userPatchPinnedItemsHandler(w http.ResponseWriter, r *http.Request, d *requ pinned.Remove(sourcePath, indexDirPath, body.Name) } - if err := store.Users.Update(u, d.user.Permissions.Admin, "PinnedItems"); err != nil { + if err := state.UpdateUser(&u, "", "PinnedItems"); err != nil { return http.StatusInternalServerError, err } diff --git a/backend/http/preview.go b/backend/internal/web/preview.go similarity index 61% rename from backend/http/preview.go rename to backend/internal/web/preview.go index 65ce18b878..cfdca8ffca 100644 --- a/backend/http/preview.go +++ b/backend/internal/web/preview.go @@ -1,4 +1,4 @@ -package http +package web import ( "bytes" @@ -13,10 +13,11 @@ import ( "strings" "time" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" - "github.com/gtsteffaniak/filebrowser/backend/preview" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/internal/preview" + "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" ) @@ -44,7 +45,7 @@ func isClientCancellation(ctx context.Context, err error) bool { // @Accept json // @Produce json // @Param path query string true "File path of the image to preview" -// @Param size query string false "Preview size ('small' or 'large'). Default is based on server config." +// @Param size query string false "Preview size ('small' or 'large'). Default is based on server settings.Config." // @Success 200 {file} file "Preview image content" // @Failure 202 {object} map[string]string "Download permissions required" // @Failure 400 {object} map[string]string "Invalid request path" @@ -53,8 +54,8 @@ func isClientCancellation(ctx context.Context, err error) bool { // @Failure 500 {object} map[string]string "Internal server error" // @Failure 501 {object} map[string]string "Preview generation not implemented" // @Router /api/resources/preview [get] -func previewHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if config.Server.DisablePreviews { +func previewHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if settings.Config.Server.DisablePreviews { return http.StatusNotImplemented, fmt.Errorf("preview is disabled") } path := r.URL.Query().Get("path") @@ -65,25 +66,62 @@ func previewHandler(w http.ResponseWriter, r *http.Request, d *requestContext) ( if source == "" { return http.StatusBadRequest, fmt.Errorf("source is required") } + filePerms, err := effectiveFilePerms(d, source) + 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") + } fileInfo, err := files.FileInfoFaster(utils.FileOptions{ Path: path, Source: source, AlbumArt: true, // Extract album art for audio previews Expand: true, - }, store.Access, d.user, store.Share) + }, d.User) if err != nil { logger.Errorf("error getting file info: %v", err) - return errToStatus(err), err + return ErrToStatus(err), err } - d.fileInfo = *fileInfo - status, err := previewHelperFunc(w, r, d) + d.FileInfo = *fileInfo + status, err := PreviewHelperFunc(w, r, d) if err != nil { - // Error already logged in previewHelperFunc or its callees - return errToStatus(err), err + // Error already logged in PreviewHelperFunc or its callees + return ErrToStatus(err), err } return status, nil } +// publicPreviewHandler handles the preview request for images from public shares. +// @Summary Get image/video preview from a public share +// @Description Returns a preview (thumbnail) for images or videos accessible via a public share. Preview generation can be disabled globally or per-share. Not available for upload-only shares. +// @Tags Resources +// @Accept json +// @Produce image/jpeg +// @Param hash query string true "Share hash for authentication" +// @Param path query string true "File path within the share to preview" +// @Param size query string false "Preview size: 'small' or 'large'. Default is based on server settings.Config." +// @Success 200 {file} file "Preview image content (JPEG)" +// @Failure 403 {object} map[string]string "Share unavailable or access denied" +// @Failure 404 {object} map[string]string "File not found or preview not available" +// @Failure 500 {object} map[string]string "Internal server error" +// @Failure 501 {object} map[string]string "Previews disabled globally, for this share, or for upload shares" +// @Router /public/api/resources/preview [get] +func publicPreviewHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if settings.Config.Server.DisablePreviews || d.Share.DisableThumbnails { + return http.StatusNotImplemented, fmt.Errorf("preview is disabled") + } + if d.Share.ShareType == "upload" { + return http.StatusNotImplemented, fmt.Errorf("preview is disabled for upload shares") + } + status, err := PreviewHelperFunc(w, r, d) + if err != nil { + logger.Errorf("public preview handler: error getting preview with error %v", err) + return http.StatusNotFound, fmt.Errorf("preview not available for this item") + } + return status, err +} + func shouldServeOriginalPreview(ext string, resizable bool, realPath, previewSize string, fileSize int64) bool { if !resizable { return false @@ -94,7 +132,7 @@ func shouldServeOriginalPreview(ext string, resizable bool, realPath, previewSiz return false } const maxSizeForOriginal = 256 * 1024 // 256KB - if config.Server.DisableResize || fileSize < maxSizeForOriginal { + if settings.Config.Server.DisableResize || fileSize < maxSizeForOriginal { return true } return preview.ShouldServeOriginalImage(realPath, previewSize) @@ -107,7 +145,7 @@ func rawFileHandler(w http.ResponseWriter, r *http.Request, file iteminfo.Extend } defer fd.Close() - setContentDisposition(w, r, file.Name) + SetContentDisposition(w, r, file.Name, false) w.Header().Set("Cache-Control", "private") http.ServeContent(w, r, file.Name, file.ModTime, fd) @@ -116,10 +154,10 @@ func rawFileHandler(w http.ResponseWriter, r *http.Request, file iteminfo.Extend // getDirectoryPreview returns the previewable file at the given frame index (0–3) for motion preview. // atPercentage maps to frame: 0→0, 1–25→1, 26–50→2, 51–100→3. The returned file is frameIndex % n where n is the number of previewable items. -func getDirectoryPreview(r *http.Request, d *requestContext, frameIndex int) (*iteminfo.ExtendedFileInfo, error) { - // Build list of previewable item names in stable order (same as d.fileInfo.Files) +func getDirectoryPreview(ctx context.Context, r *http.Request, d *Context, frameIndex int) (*iteminfo.ExtendedFileInfo, error) { + // Build list of previewable item names in stable order (same as d.FileInfo.Files) var previewableNames []string - for _, item := range d.fileInfo.Files { + for _, item := range d.FileInfo.Files { if !iteminfo.ShouldBubbleUpToFolderPreview(item.ItemInfo) { continue } @@ -132,17 +170,17 @@ func getDirectoryPreview(r *http.Request, d *requestContext, frameIndex int) (*i index := frameIndex % len(previewableNames) name := previewableNames[index] - source := d.fileInfo.Source - path := utils.JoinPathAsUnix(d.fileInfo.Path, name) - user := d.user - if d.share != nil { - sourceInfo, ok := config.Server.SourceMap[d.share.Source] + source := d.FileInfo.Source + path := utils.JoinPathAsUnix(d.FileInfo.Path, name) + user := d.User + if d.Share.Hash != "" { + sourceInfo, ok := settings.Config.Server.SourceMap[d.Share.SourcePath] if !ok { return nil, fmt.Errorf("source not found for share") } source = sourceInfo.Name path = d.IndexPath + name - user = d.shareUser + user = d.ShareUser } fileInfo, err := files.FileInfoFaster( utils.FileOptions{ @@ -150,19 +188,19 @@ func getDirectoryPreview(r *http.Request, d *requestContext, frameIndex int) (*i Source: source, AlbumArt: true, Metadata: true, - }, store.Access, user, store.Share) + }, user) if err != nil { return nil, err } - tempCtx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + tempCtx, cancel := context.WithTimeout(ctx, 5*time.Second) _, previewErr := preview.GetPreviewForFile(tempCtx, *fileInfo, "small", "", 0) cancel() if previewErr != nil { if !errors.Is(previewErr, context.Canceled) && !errors.Is(previewErr, context.DeadlineExceeded) { - logger.Debugf("Skipping preview file in directory '%s': %s (error: %v)", d.fileInfo.Name, name, previewErr) + logger.Debugf("Skipping preview file in directory '%s': %s (error: %v)", d.FileInfo.Name, name, previewErr) // Fallback: try first item (frame 0) once so atPercentage=0 still works when another frame fails if index != 0 { - return getDirectoryPreview(r, d, 0) + return getDirectoryPreview(ctx, r, d, 0) } } return nil, previewErr @@ -170,17 +208,17 @@ func getDirectoryPreview(r *http.Request, d *requestContext, frameIndex int) (*i return fileInfo, nil } -func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func PreviewHelperFunc(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { ctx := r.Context() - if d.ctx != nil { - ctx = d.ctx + if d.Ctx != nil { + ctx = d.Ctx } previewSize := r.URL.Query().Get("size") if !(previewSize == "large" || previewSize == "original" || previewSize == "xlarge") { previewSize = "small" } - if !d.fileInfo.HasPreview { + if !d.FileInfo.HasPreview { return http.StatusBadRequest, fmt.Errorf("this item does not have a preview") } @@ -199,7 +237,7 @@ func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext // For directories: map atPercentage to frame index 0–3 for motion preview (cycle over previewable items) var dirFrameIndex int - if d.fileInfo.Type == "directory" { + if d.FileInfo.Type == "directory" { switch { case seekPercentage <= 0: dirFrameIndex = 0 @@ -210,7 +248,7 @@ func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext default: dirFrameIndex = 3 } - fileInfo, err := getDirectoryPreview(r, d, dirFrameIndex) + fileInfo, err := getDirectoryPreview(ctx, r, d, dirFrameIndex) if err != nil { if isClientCancellation(ctx, err) { return http.StatusOK, nil @@ -221,27 +259,27 @@ func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext logger.Errorf("error getting directory preview: %v", err) return http.StatusInternalServerError, err } - d.fileInfo = *fileInfo + d.FileInfo = *fileInfo seekPercentage = 0 } - setContentDisposition(w, r, d.fileInfo.Name) - isImage := strings.HasPrefix(d.fileInfo.Type, "image") - ext := strings.ToLower(filepath.Ext(d.fileInfo.Name)) + SetContentDisposition(w, r, d.FileInfo.Name, false) + isImage := strings.HasPrefix(d.FileInfo.Type, "image") + ext := strings.ToLower(filepath.Ext(d.FileInfo.Name)) resizable := iteminfo.ResizableImageTypes[ext] // For small displayable images (jpg, png, etc.) serve the original to avoid processing. // Also serve the original when dimensions already fit the requested preview size. - if isImage && shouldServeOriginalPreview(ext, resizable, d.fileInfo.RealPath, previewSize, d.fileInfo.Size) { - return rawFileHandler(w, r, d.fileInfo) + if isImage && shouldServeOriginalPreview(ext, resizable, d.FileInfo.RealPath, previewSize, d.FileInfo.Size) { + return rawFileHandler(w, r, d.FileInfo) } officeUrl := "" - if d.fileInfo.OnlyOfficeId != "" { - pathUrl := fmt.Sprintf("/api/resources/download?file=%s&source=%s", url.QueryEscape(d.fileInfo.Path), url.QueryEscape(d.fileInfo.Source)) - pathUrl = pathUrl + "&auth=" + d.token - if config.Server.InternalUrl != "" { - officeUrl = config.Server.InternalUrl + pathUrl + if d.FileInfo.OnlyOfficeId != "" { + pathUrl := fmt.Sprintf("/api/resources/download?file=%s&source=%s", url.QueryEscape(d.FileInfo.Path), url.QueryEscape(d.FileInfo.Source)) + pathUrl = pathUrl + "&auth=" + d.Token + if settings.Config.Http.InternalUrl != "" { + officeUrl = settings.Config.Http.InternalUrl + pathUrl } else { scheme := "http" if r.TLS != nil { @@ -250,7 +288,7 @@ func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext officeUrl = scheme + "://" + r.Host + pathUrl } } - previewImg, err := preview.GetPreviewForFile(ctx, d.fileInfo, previewSize, officeUrl, seekPercentage) + previewImg, err := preview.GetPreviewForFile(ctx, d.FileInfo, previewSize, officeUrl, seekPercentage) if err != nil { // Check if it was a context cancellation (client navigated away) if isClientCancellation(ctx, err) { @@ -260,18 +298,18 @@ func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext // Check if it was a context timeout (server-side timeout) if ctx.Err() == context.DeadlineExceeded || errors.Is(err, context.DeadlineExceeded) { - logger.Errorf("Preview timeout for file '%s' after 15 seconds", d.fileInfo.Name) + logger.Errorf("Preview timeout for file '%s' after 15 seconds", d.FileInfo.Name) return http.StatusRequestTimeout, fmt.Errorf("preview generation timed out after 15 seconds") } // Log detailed error information for actual server errors logger.Errorf("Preview generation failed for file '%s' (type: %s, size: %s, seek: %d%%): %v", - d.fileInfo.Name, d.fileInfo.Type, previewSize, seekPercentage, err) + d.FileInfo.Name, d.FileInfo.Type, previewSize, seekPercentage, err) return http.StatusInternalServerError, err } w.Header().Set("Cache-Control", "private") w.Header().Set("Content-Type", "image/jpeg") - http.ServeContent(w, r, d.fileInfo.Name+"-preview.jpg", d.fileInfo.ModTime, bytes.NewReader(previewImg)) + http.ServeContent(w, r, d.FileInfo.Name+"-preview.jpg", d.FileInfo.ModTime, bytes.NewReader(previewImg)) return 0, nil } diff --git a/backend/internal/web/proxy.go b/backend/internal/web/proxy.go new file mode 100644 index 0000000000..db04731ae4 --- /dev/null +++ b/backend/internal/web/proxy.go @@ -0,0 +1,89 @@ +package web + +import ( + "fmt" + "net/http" + "strings" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func normalizeHTTPScheme(proto string) string { + p := strings.ToLower(strings.TrimSpace(proto)) + switch p { + case "http", "https": + return p + default: + return "" + } +} + +func firstForwardedValue(v string) string { + v = strings.TrimSpace(v) + if i := strings.Index(v, ","); i >= 0 { + v = strings.TrimSpace(v[:i]) + } + return v +} + +// requestScheme returns http or https from TLS and optionally trusted X-Forwarded-Proto. +func requestScheme(r *http.Request) string { + cfg := &settings.Config + if cfg.Http.TrustProxyHeaders { + if proto := normalizeHTTPScheme(r.Header.Get("X-Forwarded-Proto")); proto != "" { + return proto + } + } + if r.TLS != nil { + return "https" + } + return "http" +} + +// requestHost returns the client-facing host, honoring trusted X-Forwarded-Host. +func requestHost(r *http.Request) string { + cfg := &settings.Config + if cfg.Http.TrustProxyHeaders { + if h := firstForwardedValue(r.Header.Get("X-Forwarded-Host")); h != "" { + return h + } + } + return r.Host +} + +// requestSchemeForPublicURL picks scheme for absolute share URLs (HTTPS default when forwarded host is trusted). +func requestSchemeForPublicURL(r *http.Request) string { + cfg := &settings.Config + if cfg.Http.TrustProxyHeaders { + if firstForwardedValue(r.Header.Get("X-Forwarded-Host")) != "" { + if proto := normalizeHTTPScheme(r.Header.Get("X-Forwarded-Proto")); proto != "" { + return proto + } + return "https" + } + } + return requestScheme(r) +} + +func shareURLParams(r *http.Request) (host, scheme string) { + if r == nil { + return "", "" + } + return requestHost(r), requestSchemeForPublicURL(r) +} + +// requestPageFullURL builds the canonical page URL from the request (or http.externalUrl when set). +func requestPageFullURL(r *http.Request) string { + if settings.Config.Http.ExternalUrl != "" { + return strings.TrimSuffix(settings.Config.Http.ExternalUrl, "/") + r.URL.Path + } + host, scheme := shareURLParams(r) + return fmt.Sprintf("%s://%s%s", scheme, host, r.URL.Path) +} + +// ShareURLFromRequest builds a public share or direct-download URL from the request and server config. +func ShareURLFromRequest(r *http.Request, hash string, isDirectDownload bool, token string) string { + host, scheme := shareURLParams(r) + return share.PublicShareURL(host, scheme, hash, isDirectDownload, token) +} diff --git a/backend/internal/web/proxy_test.go b/backend/internal/web/proxy_test.go new file mode 100644 index 0000000000..9d2e7536a7 --- /dev/null +++ b/backend/internal/web/proxy_test.go @@ -0,0 +1,168 @@ +package web + +import ( + "crypto/tls" + "net/http/httptest" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func TestGetScheme(t *testing.T) { + t.Run("trusted proto", func(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.Header.Set("X-Forwarded-Proto", "https") + if got := GetScheme(req); got != "https" { + t.Fatalf("GetScheme = %q, want https", got) + } + }) + + t.Run("ignores spoofed proto when untrusted", func(t *testing.T) { + settings.Config.Http.TrustProxyHeaders = false + + req := httptest.NewRequest("GET", "http://example.com/", nil) + req.Header.Set("X-Forwarded-Proto", "https") + if got := GetScheme(req); got != "http" { + t.Fatalf("GetScheme = %q, want http", got) + } + }) +} + +func TestRequestSchemeTLSFallback(t *testing.T) { + settings.Config.Http.TrustProxyHeaders = false + + req := httptest.NewRequest("GET", "https://example.com/", nil) + req.TLS = &tls.ConnectionState{} + if got := requestScheme(req); got != "https" { + t.Fatalf("requestScheme = %q, want https", got) + } +} + +func TestRequestSchemeIgnoresInvalidProto(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.Header.Set("X-Forwarded-Proto", "javascript") + if got := requestScheme(req); got != "http" { + t.Fatalf("requestScheme = %q, want http", got) + } +} + +func TestRequestHostTrustProxyHeaders(t *testing.T) { + settings.Config.Http.TrustProxyHeaders = true + t.Cleanup(func() { settings.Config.Http.TrustProxyHeaders = false }) + + req := httptest.NewRequest("GET", "http://127.0.0.1:8080/", nil) + req.Host = "127.0.0.1:8080" + req.Header.Set("X-Forwarded-Host", "public.example.com, internal.example.com") + + if got := requestHost(req); got != "public.example.com" { + t.Fatalf("requestHost = %q, want public.example.com", got) + } +} + +func TestRequestSchemeForPublicURL(t *testing.T) { + orig := settings.Config.Http.TrustProxyHeaders + t.Cleanup(func() { settings.Config.Http.TrustProxyHeaders = orig }) + + t.Run("trusted host without proto defaults to https", func(t *testing.T) { + settings.Config.Http.TrustProxyHeaders = true + req := httptest.NewRequest("GET", "http://127.0.0.1:8080/", nil) + req.Header.Set("X-Forwarded-Host", "public.example.com") + if got := requestSchemeForPublicURL(req); got != "https" { + t.Fatalf("requestSchemeForPublicURL = %q, want https", got) + } + }) + + t.Run("trusted host with proto honors proto", func(t *testing.T) { + settings.Config.Http.TrustProxyHeaders = true + req := httptest.NewRequest("GET", "http://127.0.0.1:8080/", nil) + req.Header.Set("X-Forwarded-Host", "public.example.com") + req.Header.Set("X-Forwarded-Proto", "http") + if got := requestSchemeForPublicURL(req); got != "http" { + t.Fatalf("requestSchemeForPublicURL = %q, want http", got) + } + }) + + t.Run("ignores forwarded proto when untrusted", func(t *testing.T) { + settings.Config.Http.TrustProxyHeaders = false + req := httptest.NewRequest("GET", "http://127.0.0.1:8080/", nil) + req.Header.Set("X-Forwarded-Proto", "https") + if got := requestSchemeForPublicURL(req); got != "http" { + t.Fatalf("requestSchemeForPublicURL = %q, want http", got) + } + }) +} + +func TestRequestPageFullURL(t *testing.T) { + orig := settings.Config.Http + t.Cleanup(func() { settings.Config.Http = orig }) + settings.Config.Http.ExternalUrl = "" + + tests := []struct { + name string + directHost string + forwardedHost string + forwardedProto string + trustProxy bool + path string + want string + }{ + { + name: "trusted forwarded host and proto", + directHost: "127.0.0.1:8080", + forwardedHost: "files.example.com", + forwardedProto: "https", + trustProxy: true, + path: "/files/", + want: "https://files.example.com/files/", + }, + { + name: "trusted host without proto defaults to https", + directHost: "127.0.0.1:8080", + forwardedHost: "files.example.com", + trustProxy: true, + path: "/files/", + want: "https://files.example.com/files/", + }, + { + name: "trusted host with proto honors proto", + directHost: "127.0.0.1:8080", + forwardedHost: "files.example.com", + forwardedProto: "http", + trustProxy: true, + path: "/files/", + want: "http://files.example.com/files/", + }, + { + name: "ignores spoofed host when untrusted", + directHost: "127.0.0.1:8080", + forwardedHost: "evil.example.com", + forwardedProto: "https", + trustProxy: false, + path: "/files/", + want: "http://127.0.0.1:8080/files/", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + settings.Config.Http.TrustProxyHeaders = tt.trustProxy + req := httptest.NewRequest("GET", "http://example.com"+tt.path, nil) + req.Host = tt.directHost + if tt.forwardedHost != "" { + req.Header.Set("X-Forwarded-Host", tt.forwardedHost) + } + if tt.forwardedProto != "" { + req.Header.Set("X-Forwarded-Proto", tt.forwardedProto) + } + if got := requestPageFullURL(req); got != tt.want { + t.Fatalf("requestPageFullURL() = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/backend/http/resource.go b/backend/internal/web/resource.go similarity index 61% rename from backend/http/resource.go rename to backend/internal/web/resource.go index ef92190b9f..93b32f352f 100644 --- a/backend/http/resource.go +++ b/backend/internal/web/resource.go @@ -1,4 +1,4 @@ -package http +package web import ( "context" @@ -15,15 +15,20 @@ import ( "strings" "time" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/indexing" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" - "github.com/gtsteffaniak/filebrowser/backend/preview" + "github.com/gtsteffaniak/filebrowser/backend/internal/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/preview" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" "github.com/gtsteffaniak/go-cache/cache" "github.com/gtsteffaniak/go-logger/logger" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + ) var pauseCache = cache.NewCache[string](1 * time.Minute) @@ -40,6 +45,57 @@ func publicPauseUploadCacheKey(shareHash, source, indexPath string) string { return shareHash + pauseCacheKeySep + source + pauseCacheKeySep + indexPath } +// resourcePostPermCheck validates create vs overwrite permissions for ResourcePostHandler. +func resourcePostPermCheck(exists bool, override bool, perms users.SourceFilePermissions) (int, error) { + if exists { + if override && !perms.Modify { + return http.StatusForbidden, fmt.Errorf("user is not allowed to modify") + } + return 0, nil + } + if !perms.Create { + return http.StatusForbidden, fmt.Errorf("user is not allowed to create") + } + return 0, nil +} + +// resourcePatchPermCheck validates move/copy/rename permissions. Returns a failure message when denied. +func resourcePatchPermCheck(action, fromSource, toSource string, fromPerms, toPerms users.SourceFilePermissions) string { + switch action { + case "copy": + if !fromPerms.Download || !toPerms.Create { + return "user is not allowed to copy" + } + case "move", "rename": + if !fromPerms.Modify { + return "user is not allowed to modify" + } + if toSource != fromSource && !toPerms.Modify { + return "user is not allowed to modify destination source" + } + } + return "" +} + +// reconcileSharesAfterMove updates authoritative share rows in state after a filesystem move. +func reconcileSharesAfterMove(isSrcDir bool, sourceIndex, destIndex, realsrc, realdst string) { + srcIdx := indexing.GetIndex(sourceIndex) + dstIdx := indexing.GetIndex(destIndex) + if srcIdx == nil || dstIdx == nil { + logger.Errorf("reconcile shares after move: missing index src=%s dst=%s", sourceIndex, destIndex) + return + } + _, err := state.UpdateSharesForMovedResource( + srcIdx.Path, + srcIdx.MakeIndexPath(realsrc, isSrcDir).String(), + dstIdx.Path, + dstIdx.MakeIndexPath(realdst, isSrcDir).String(), + ) + if err != nil { + logger.Errorf("reconcile shares after move: %v", err) + } +} + // validateMoveOperation checks if a move/rename operation is valid at the HTTP level // It prevents moving a directory into itself or its subdirectories func validateMoveOperation(src, dst string, isSrcDir bool) error { @@ -85,9 +141,16 @@ func validateMoveOperation(src, dst string, isSrcDir bool) error { // @Failure 404 {object} map[string]string "Resource not found" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/resources [get] -func resourceGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func resourceGetHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { path := r.URL.Query().Get("path") source := r.URL.Query().Get("source") + filePerms, err := effectiveFilePerms(d, source) + 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") + } getContent := r.URL.Query().Get("content") == "true" getMetadata := r.URL.Query().Get("metadata") == "true" skipExtendedAttrs := r.URL.Query().Get("skipExtendedAttrs") == "true" @@ -98,21 +161,22 @@ func resourceGetHandler(w http.ResponseWriter, r *http.Request, d *requestContex Expand: true, Content: getContent, Metadata: getMetadata, - ExtractEmbeddedSubtitles: config.Integrations.Media.ExtractEmbeddedSubtitles, - ShowHidden: d.user.ShowHidden, - HideFileExt: d.user.HideFileExt, + ExtractEmbeddedSubtitles: settings.Config.Integrations.Media.ExtractEmbeddedSubtitles, + ShowHidden: d.User.ShowHidden, + HideFileExt: d.User.HideFileExt, SkipExtendedAttrs: skipExtendedAttrs, ShowSharedAttr: true, ShowPinnedItems: true, - }, store.Access, d.user, store.Share) + }, d.User) if err != nil { - return errToStatus(err), err + return ErrToStatus(err), err } - if !d.user.Permissions.Download && fileInfo.Content != "" { + if !filePerms.Download && fileInfo.Content != "" { return http.StatusForbidden, fmt.Errorf("user is not allowed to get content, requires download permission") } if fileInfo.Type == "directory" { - return renderJSON(w, r, fileInfo) + AttachViewTokensForDirectory(d, source, fileInfo) + return RenderJSON(w, r, fileInfo) } if algo := r.URL.Query().Get("checksum"); algo != "" { checksum, err := utils.GetChecksum(fileInfo.RealPath, algo) @@ -124,8 +188,31 @@ func resourceGetHandler(w http.ResponseWriter, r *http.Request, d *requestContex fileInfo.Checksums = make(map[string]string) fileInfo.Checksums[algo] = checksum } - return renderJSON(w, r, fileInfo) + AttachViewToken(d, source, fileInfo) + return RenderJSON(w, r, fileInfo) +} +// publicGetResourceHandler returns file or directory information from a public share. +// @Summary Get file/directory information from a public share +// @Description Returns metadata for files or directories accessible via a public share link. Browsing is disabled for upload-only shares. +// @Tags Resources +// @Accept json +// @Produce json +// @Param hash query string true "Share hash for authentication" +// @Param path query string false "Path within the share to retrieve information for. Defaults to share root." +// @Param content query string false "Include file content if true" +// @Param metadata query string false "Extract audio/video metadata if true" +// @Success 200 {object} iteminfo.FileInfo "File or directory metadata" +// @Failure 403 {object} map[string]string "Share unavailable or access denied" +// @Failure 404 {object} map[string]string "Share not found or file not found" +// @Failure 500 {object} map[string]string "Internal server error" +// @Failure 501 {object} map[string]string "Browsing disabled for upload shares" +// @Router /public/api/resources [get] +func publicGetResourceHandler(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") + } + return RenderJSON(w, r, d.FileInfo) } // resourceDeleteHandler deletes a resource at a specified path. @@ -141,13 +228,16 @@ func resourceGetHandler(w http.ResponseWriter, r *http.Request, d *requestContex // @Failure 404 {object} map[string]string "Resource not found" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/resources [delete] -func resourceDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - - if !d.user.Permissions.Delete { - return http.StatusForbidden, fmt.Errorf("user is not allowed to delete") - } +func resourceDeleteHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { path := r.URL.Query().Get("path") source := r.URL.Query().Get("source") + filePerms, err := effectiveFilePerms(d, source) + if err != nil { + return http.StatusForbidden, err + } + if d.Share.Hash == "" && !filePerms.Delete { + return http.StatusForbidden, fmt.Errorf("user is not allowed to delete") + } if path == "/" { return http.StatusForbidden, fmt.Errorf("cannot delete your user's root directory") @@ -166,11 +256,11 @@ func resourceDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestCon Path: path, Source: source, Expand: false, - ShowHidden: d.user.ShowHidden, - HideFileExt: d.user.HideFileExt, - }, store.Access, d.user, store.Share) + ShowHidden: d.User.ShowHidden, + HideFileExt: d.User.HideFileExt, + }, d.User) if err != nil { - return errToStatus(err), err + return ErrToStatus(err), err } // delete thumbnails @@ -178,12 +268,35 @@ func resourceDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestCon err = files.DeleteFiles(source, fileInfo.RealPath, fileInfo.Type == "directory") if err != nil { - return errToStatus(err), err + return ErrToStatus(err), err } + activity.RecordDelete(r, toActor(d), source, path) return http.StatusOK, nil } +// deprecated -- see publicBulkDeleteHandler +func publicDeleteHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if !d.Share.AllowDelete { + return http.StatusForbidden, fmt.Errorf("delete is not allowed for this share") + } + fileInfo, err := files.FileInfoFaster(utils.FileOptions{ + FollowSymlinks: true, + Path: d.IndexPath, + Source: d.Share.SourcePath, + }, d.ShareUser) + if err != nil { + return http.StatusNotFound, fmt.Errorf("resource not available") + } + err = files.DeleteFiles(d.Share.SourcePath, fileInfo.RealPath, fileInfo.Type == "directory") + if err != nil { + logger.Errorf("public delete handler: error deleting resource with error %v", err) + return http.StatusInternalServerError, fmt.Errorf("an error occured while deleting the resource") + } + preview.DelThumbs(r.Context(), *fileInfo) + return http.StatusOK, nil +} + // BulkDeleteItem represents a single item in a bulk delete request type BulkDeleteItem struct { Source string `json:"source"` @@ -233,16 +346,10 @@ type MoveCopyResponse struct { // @Failure 403 {object} map[string]string "Forbidden" // @Failure 500 {object} map[string]string "Internal server error - all deletions failed" // @Router /api/resources/bulk [delete] -func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - filePermUser := d.user - if d.share != nil { - filePermUser = d.shareUser - } - // Check permissions - either user delete permission or share delete permission - if d.share == nil { - if !d.user.Permissions.Delete { - return http.StatusForbidden, fmt.Errorf("user is not allowed to delete") - } +func ResourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + filePermUser := d.User + if d.Share.Hash != "" { + filePermUser = d.ShareUser } // Parse request body @@ -282,7 +389,7 @@ func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *reques }) continue } - sanitizedPath, err := utils.SanitizeUserPath(rawPath) + sanitizedPath, err := utils.SanitizePath(rawPath) if err != nil { response.Failed = append(response.Failed, BulkDeleteItem{ Source: item.Source, @@ -292,8 +399,8 @@ func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *reques continue } - if d.share != nil { - sourceName := d.share.GetSourceName() + if d.Share.Hash != "" { + sourceName := d.Share.GetSourceName() if sourceName == "" { response.Failed = append(response.Failed, BulkDeleteItem{ Source: item.Source, @@ -323,7 +430,7 @@ func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *reques } // get user scope path from share - userScope, err := d.shareUser.GetScopeForSourceName(sourceName) + userScope, err := d.ShareUser.GetScopeForSourceName(sourceName) if err != nil { response.Failed = append(response.Failed, BulkDeleteItem{ Source: item.Source, @@ -332,7 +439,7 @@ func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *reques }) continue } - withoutUserScope := strings.TrimPrefix(d.share.Path, userScope) + withoutUserScope := strings.TrimPrefix(d.Share.Path, userScope) indexPath := utils.JoinPathAsUnix(withoutUserScope, sanitizedPath) fileInfo, err := files.FileInfoFaster(utils.FileOptions{ @@ -340,7 +447,7 @@ func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *reques Path: indexPath, Source: sourceName, ShowHidden: true, - }, store.Access, filePermUser, store.Share) + }, filePermUser) if err != nil { return http.StatusNotFound, fmt.Errorf("resource not available") } @@ -379,6 +486,15 @@ func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *reques }) continue } + filePerms, permErr := effectiveFilePerms(d, item.Source) + if permErr != nil || !filePerms.Delete { + response.Failed = append(response.Failed, BulkDeleteItem{ + Source: item.Source, + Path: sanitizedPath, + Message: "user is not allowed to delete", + }) + continue + } idx := indexing.GetIndex(item.Source) if idx == nil { @@ -405,7 +521,7 @@ func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *reques Path: sanitizedPath, Source: item.Source, ShowHidden: true, - }, store.Access, filePermUser, store.Share) + }, filePermUser) if err != nil { response.Failed = append(response.Failed, BulkDeleteItem{ Source: item.Source, @@ -425,8 +541,13 @@ func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *reques } preview.DelThumbs(r.Context(), *fileInfo) } - // Success - response.Succeeded = append(response.Succeeded, item) + // Success (log canonical path/source used for deletion) + loggedItem := item + loggedItem.Path = sanitizedPath + if d.Share.Hash != "" { + loggedItem.Source = d.Share.GetSourceName() + } + response.Succeeded = append(response.Succeeded, loggedItem) } // Determine status code based on results @@ -435,7 +556,37 @@ func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *reques statusCode = http.StatusMultiStatus } - return renderJSON(w, r, response, statusCode) + if len(response.Succeeded) > 0 { + activity.RecordBulkDelete(r, toActor(d), bulkDeleteActivityItems(response.Succeeded)) + } + + return RenderJSON(w, r, response, statusCode) +} + +// publicBulkDeleteHandler deletes multiple resources from a public share in a single request. +// @Summary Bulk delete resources from public share +// @Description Deletes multiple resources specified in the request body. Returns a list of succeeded and failed deletions. +// @Tags Resources +// @Accept json +// @Produce json +// @Param hash query string true "Share hash for authentication" +// @Param items body []BulkDeleteItem true "Array of items to delete, each with source and path" +// @Success 200 {object} BulkDeleteResponse "All resources deleted successfully" +// @Success 207 {object} BulkDeleteResponse "Partial success - some resources deleted, some failed" +// @Failure 400 {object} map[string]string "Bad request - invalid JSON or empty items array" +// @Failure 403 {object} map[string]string "Forbidden - delete not allowed for this share" +// @Failure 500 {object} map[string]string "Internal server error - all deletions failed" +// @Router /public/api/resources/bulk [delete] +func publicBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if !d.Share.AllowDelete { + return http.StatusForbidden, fmt.Errorf("delete is not allowed for this share") + } + status, err := ResourceBulkDeleteHandler(w, r, d) + if err != nil { + logger.Errorf("public bulk delete handler: error deleting resources with error %v", err) + return http.StatusInternalServerError, fmt.Errorf("an error occurred while processing the request") + } + return status, nil } // resourcePauseHandler registers a graceful pause for an in-flight chunked upload. @@ -452,39 +603,44 @@ func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *reques // @Failure 403 {object} map[string]string "Forbidden" // @Failure 404 {object} map[string]string "Source not found" // @Router /api/resources/pause [post] -func resourcePauseHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if d.share != nil { +func resourcePauseHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if d.Share.Hash != "" { return http.StatusBadRequest, fmt.Errorf("use public pause endpoint for share uploads") } - if !d.user.Permissions.Create { + source := r.URL.Query().Get("source") + filePerms, err := effectiveFilePerms(d, source) + if err != nil { + return http.StatusForbidden, err + } + if !filePerms.Create { return http.StatusForbidden, fmt.Errorf("user is not allowed to pause uploads") } path := r.URL.Query().Get("path") - source := r.URL.Query().Get("source") - cleanPath, err := utils.SanitizeUserPath(path) + cleanPath, err := utils.SanitizePath(path) if err != nil { return http.StatusBadRequest, err } - path = cleanPath idx := indexing.GetIndex(source) if idx == nil { logger.Debugf("source %s not found", source) return http.StatusNotFound, fmt.Errorf("source %s not found", source) } - if _, err := d.user.GetScopeForSourceName(source); err != nil { + userscope, err := d.User.GetScopeForSourceName(source) + if err != nil { return http.StatusForbidden, err } - if !store.Access.Permitted(idx.Path, path, d.user.Username) { - return http.StatusForbidden, fmt.Errorf("access denied to path %s", path) + fullIndexPath := utils.JoinPathAsUnix(userscope, cleanPath) + if !state.AccessPermitted(idx.Path, utils.IndexPathFromNormalized(fullIndexPath, true), d.User.Username) { + return http.StatusForbidden, fmt.Errorf("access denied to path %s", fullIndexPath) } - pauseCache.Set(pauseUploadCacheKey(source, path), "1") + pauseCache.Set(pauseUploadCacheKey(source, fullIndexPath), "1") return http.StatusOK, nil } // publicPauseHandler registers a graceful pause for a public share chunked upload. // @Summary Register graceful chunked upload pause (public share) // @Description Same as authenticated pause, for upload shares. Uses hash and path query parameters like other public resource APIs. -// @Tags Shares +// @Tags Resources // @Accept json // @Produce json // @Param hash query string true "Share hash" @@ -493,16 +649,16 @@ func resourcePauseHandler(w http.ResponseWriter, r *http.Request, d *requestCont // @Failure 403 {object} map[string]string "Forbidden" // @Failure 404 {object} map[string]string "Source not found" // @Router /public/api/resources/pause [post] -func publicPauseHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if d.share.ShareType != "upload" && !d.share.AllowCreate { +func PublicPauseHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if d.Share.ShareType != "upload" && !d.Share.AllowCreate { return http.StatusForbidden, fmt.Errorf("pausing uploads is not allowed for this share") } - src, ok := config.Server.SourceMap[d.share.Source] + src, ok := settings.Config.Server.SourceMap[d.Share.SourcePath] if !ok { return http.StatusNotFound, fmt.Errorf("source not found") } sourceName := src.Name - publicPauseCache.Set(publicPauseUploadCacheKey(d.share.Hash, sourceName, d.IndexPath), "1") + publicPauseCache.Set(publicPauseUploadCacheKey(d.Share.Hash, sourceName, d.IndexPath), "1") return http.StatusOK, nil } @@ -522,21 +678,17 @@ func publicPauseHandler(w http.ResponseWriter, r *http.Request, d *requestContex // @Failure 409 {object} map[string]string "Conflict - Resource already exists" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/resources [post] -func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func ResourcePostHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { path := r.URL.Query().Get("path") source := r.URL.Query().Get("source") // Rule 1: Validate user-provided path to prevent path traversal - cleanPath, err := utils.SanitizeUserPath(path) + cleanPath, err := utils.SanitizePath(path) if err != nil { return http.StatusBadRequest, err } path = cleanPath - if d.share == nil && !d.user.Permissions.Create { - return http.StatusForbidden, fmt.Errorf("user is not allowed to create or modify") - } - idx := indexing.GetIndex(source) if idx == nil { logger.Debugf("source %s not found", source) @@ -547,9 +699,9 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte return http.StatusForbidden, fmt.Errorf("source is read-only") } - filePermUser := d.user - if d.share != nil { - filePermUser = d.shareUser + filePermUser := d.User + if d.Share.Hash != "" { + filePermUser = d.ShareUser } isDir := r.URL.Query().Get("isDir") == "true" fileOpts := utils.FileOptions{ @@ -571,8 +723,18 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte // get scoped path realPath, _, _ := idx.GetRealPath(fullIndexPath) - // Check access control for the target path - if !store.Access.Permitted(idx.Path, path, filePermUser.Username) { + if d.Share.Hash == "" { + filePerms, permErr := effectiveFilePerms(d, source) + if permErr != nil { + return http.StatusForbidden, permErr + } + _, statErr := os.Stat(realPath) + if status, gateErr := resourcePostPermCheck(statErr == nil, r.URL.Query().Get("override") == "true", filePerms); gateErr != nil { + return status, gateErr + } + } + + if !state.AccessPermitted(idx.Path, utils.IndexPathFromNormalized(fullIndexPath, true), filePermUser.Username) { return http.StatusForbidden, fmt.Errorf("access denied to path %s", path) } @@ -602,9 +764,10 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte err = files.WriteDirectory(dirOpts) if err != nil { logger.Debugf("error writing directory: %v", err) - return errToStatus(err), err + return ErrToStatus(err), err } + activity.RecordUpload(r, toActor(d), source, path, true) return http.StatusOK, nil } @@ -640,7 +803,7 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte } var fileInfo *iteminfo.ExtendedFileInfo - fileInfo, err = files.FileInfoFaster(fileOpts, store.Access, filePermUser, store.Share) + fileInfo, err = files.FileInfoFaster(fileOpts, filePermUser) if err == nil { // File exists if r.URL.Query().Get("override") != "true" { logger.Debugf("resource already exists: %v", fileInfo.RealPath) @@ -683,8 +846,8 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte _ = outFile.Sync() gracefulPause := false - if d.share != nil { - k := publicPauseUploadCacheKey(d.share.Hash, source, path) + if d.Share.Hash != "" { + k := publicPauseUploadCacheKey(d.Share.Hash, source, path) if _, ok := publicPauseCache.Get(k); ok { gracefulPause = true publicPauseCache.Delete(k) @@ -709,16 +872,18 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte // close file before moving outFile.Close() // Move the completed file from the temp location to the final destination - err = files.MoveResource(false, source, source, tempFilePath, realPath, store.Share, store.Access) + err = files.MoveResource(false, source, source, tempFilePath, realPath) if err != nil { logger.Debugf("could not move file from %v to %v: %v", tempFilePath, realPath, err) return http.StatusInternalServerError, fmt.Errorf("could not move file from chunked folder to destination: %v", err) } + reconcileSharesAfterMove(false, source, source, tempFilePath, realPath) + activity.RecordUpload(r, toActor(d), source, path, false) } return http.StatusOK, nil } - fileInfo, err := files.FileInfoFaster(fileOpts, store.Access, filePermUser, store.Share) + fileInfo, err := files.FileInfoFaster(fileOpts, filePermUser) if err == nil { // File exists if r.URL.Query().Get("override") != "true" { logger.Debugf("resource already exists: %v", fileInfo.RealPath) @@ -731,11 +896,58 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte err = files.WriteFile(fileOpts.Source, fullIndexPath, r.Body) if err != nil { logger.Debugf("error writing file: %v", err) - return errToStatus(err), err + return ErrToStatus(err), err } + activity.RecordUpload(r, toActor(d), source, path, false) return http.StatusOK, nil } +// publicUploadHandler processes file uploads to a public upload share. +// @Summary Upload files to a public upload share +// @Description Handles file and directory uploads to an upload-only public share. Supports chunked uploads, conflict resolution (override), and directory creation. +// @Tags Resources +// @Accept multipart/form-data +// @Produce json +// @Param hash query string true "Share hash for authentication" +// @Param path query string true "path within the share to upload to. Must be relative to share root." +// @Param override query bool false "If true, overwrite existing files/folders. Defaults to false." +// @Param action query string false "Upload action: 'override' to replace files, 'rename' to auto-rename" +// @Param file formData file true "File to upload" +// @Success 200 {object} map[string]string "Upload successful" +// @Failure 400 {object} map[string]string "Invalid request or parameters" +// @Failure 403 {object} map[string]string "Share unavailable or upload not allowed" +// @Failure 404 {object} map[string]string "Share not found" +// @Failure 409 {object} map[string]string "File or directory already exists (conflict)" +// @Failure 500 {object} map[string]string "Internal server error during upload" +// @Failure 501 {object} map[string]string "Uploading disabled for non-upload shares" +// @Router /public/api/resources [post] +func publicUploadHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if d.Share.ShareType != "upload" && !d.Share.AllowCreate { + return http.StatusForbidden, fmt.Errorf("uploading is disabled for this share") + } + if !d.Share.AllowReplacements && r.URL.Query().Get("action") == "override" { + return http.StatusForbidden, fmt.Errorf("cannot overwrite files for this share") + } + sourceInfo, ok := settings.Config.Server.SourceMap[d.Share.SourcePath] + if !ok { + return http.StatusNotFound, fmt.Errorf("source not found") + } + source := sourceInfo.Name + q := r.URL.Query() + q.Set("source", source) + q.Set("path", d.IndexPath) + r.URL.RawQuery = q.Encode() + status, err := ResourcePostHandler(w, r, d) + if err != nil { + logger.Errorf("public upload handler: error uploading with error %v", err) + if status == 0 { + status = http.StatusInternalServerError + } + return status, err + } + return status, nil +} + // resourcePutHandler updates an existing file resource. // @Summary Update a file resource // @Description Updates an existing file at the specified path. @@ -750,18 +962,25 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte // @Failure 405 {object} map[string]string "Method not allowed" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/resources [put] -func resourcePutHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func resourcePutHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { source := r.URL.Query().Get("source") path := r.URL.Query().Get("path") // Rule 1: Validate user-provided path to prevent path traversal - cleanPath, err := utils.SanitizeUserPath(path) + cleanPath, err := utils.SanitizePath(path) if err != nil { return http.StatusBadRequest, err } path = cleanPath + filePerms, err := effectiveFilePerms(d, source) + if err != nil { + return http.StatusForbidden, err + } + if d.Share.Hash == "" && !filePerms.Modify { + return http.StatusForbidden, fmt.Errorf("user is not allowed to modify files in this source") + } // Get user scope to resolve full index path for write operation - userScope, err := d.user.GetScopeForSourceName(source) + userScope, err := d.User.GetScopeForSourceName(source) if err != nil { return http.StatusForbidden, err } @@ -774,20 +993,58 @@ func resourcePutHandler(w http.ResponseWriter, r *http.Request, d *requestContex if idx.Config.ReadOnly { return http.StatusForbidden, fmt.Errorf("source is read-only") } - if store.Access != nil && !store.Access.Permitted(idx.Path, fullIndexPath, d.user.Username) { - logger.Debugf("user %s denied access to path %s", d.user.Username, fullIndexPath) + if !state.AccessPermitted(idx.Path, utils.IndexPathFromNormalized(fullIndexPath, true), d.User.Username) { + logger.Debugf("user %s denied access to path %s", d.User.Username, fullIndexPath) return http.StatusForbidden, fmt.Errorf("access denied to path %s", path) } // check if destination is a directory stat, err := os.Stat(filepath.Join(idx.Path + fullIndexPath)) if err == nil && stat.IsDir() { - // if directory return StatusMethodNotAllowed return http.StatusMethodNotAllowed, fmt.Errorf("path is a directory") } err = files.WriteFile(source, fullIndexPath, r.Body) - return errToStatus(err), err + return ErrToStatus(err), err +} + +// publicPutHandler handles the PUT request for a public share. +// @Summary Update a file in a public share +// @Description Updates the content of a file in a public share. +// @Tags Resources +// @Accept json +// @Produce json +// @Param hash query string true "Share hash for authentication" +// @Param path query string true "Path to the file to update" +// @Param content body string true "New content for the file" +// @Success 200 {object} map[string]string "File updated successfully" +// @Failure 400 {object} map[string]string "Invalid request or parameters" +// @Failure 403 {object} map[string]string "Share unavailable or update not allowed" +// @Failure 404 {object} map[string]string "Share not found or file not found" +// @Failure 500 {object} map[string]string "Internal server error" +// @Router /public/api/resources [put] +func publicPutHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if !d.Share.AllowModify { + return http.StatusForbidden, fmt.Errorf("edit permission not allowed for this share") + } + sourceName := d.Share.GetSourceName() + if sourceName == "" { + return http.StatusNotFound, fmt.Errorf("source not available") + } + path := r.URL.Query().Get("path") + + cleanPath, err := utils.SanitizePath(path) + if err != nil { + return http.StatusBadRequest, err + } + + resolvedPath := utils.JoinPathAsUnix(d.Share.Path, cleanPath) + err = files.WriteFile(sourceName, resolvedPath, r.Body) + if err != nil { + logger.Errorf("public put handler: error updating resource with error %v", err) + return http.StatusInternalServerError, fmt.Errorf("an error occurred while updating the resource") + } + return http.StatusOK, nil } // resourcePatchHandler performs a patch operation (e.g., move, copy, rename) on resources. @@ -804,11 +1061,7 @@ func resourcePutHandler(w http.ResponseWriter, r *http.Request, d *requestContex // @Failure 404 {object} map[string]string "Resource not found" // @Failure 500 {object} MoveCopyResponse "All operations failed" // @Router /api/resources [patch] -func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !d.user.Permissions.Modify && d.share == nil { - return http.StatusForbidden, fmt.Errorf("user is not allowed to create or modify") - } - +func ResourcePatchHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { req, ok := d.Data.(MoveCopyRequest) if req.Action == "" || !ok { // Parse request body @@ -824,6 +1077,11 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont if req.Action == "" { return http.StatusBadRequest, fmt.Errorf("action is required (copy, move, or rename)") } + switch req.Action { + case "copy", "move", "rename": + default: + return http.StatusBadRequest, fmt.Errorf("invalid action: %s (must be copy, move, or rename)", req.Action) + } response := MoveCopyResponse{ Succeeded: make([]MoveCopyItem, 0), @@ -836,7 +1094,7 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont // Validate all fields are provided if item.FromSource == "" || item.FromPath == "" || item.ToSource == "" || item.ToPath == "" { item.Message = "fromSource, fromPath, toSource, and toPath are required" - if d.share != nil { + if d.Share.Hash != "" { response.Failed = append(response.Failed, MoveCopyItem{ Message: item.Message, }) @@ -845,13 +1103,13 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont response.Failed = append(response.Failed, item) continue } - cleanFromPath, err := utils.SanitizeUserPath(item.FromPath) + cleanFromPath, err := utils.SanitizePath(item.FromPath) if err != nil { item.Message = fmt.Sprintf("invalid fromPath: %v", err) response.Failed = append(response.Failed, item) continue } - cleanToPath, err := utils.SanitizeUserPath(item.ToPath) + cleanToPath, err := utils.SanitizePath(item.ToPath) if err != nil { item.Message = fmt.Sprintf("invalid toPath: %v", err) response.Failed = append(response.Failed, item) @@ -864,26 +1122,47 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont // For shares, paths are already absolute, so use empty scope userscopeSrc := "" userscopeDst := "" - if d.share == nil { - userscopeSrc, err = d.user.GetScopeForSourceName(item.FromSource) + if d.Share.Hash == "" { + userscopeSrc, err = d.User.GetScopeForSourceName(item.FromSource) if err != nil { item.Message = "source not available" response.Failed = append(response.Failed, item) continue } - userscopeDst, err = d.user.GetScopeForSourceName(item.ToSource) + userscopeDst, err = d.User.GetScopeForSourceName(item.ToSource) if err != nil { item.Message = "destination source not available" response.Failed = append(response.Failed, item) continue } + fromPerms, permErr := effectiveFilePerms(d, item.FromSource) + if permErr != nil { + item.Message = "permission denied" + response.Failed = append(response.Failed, item) + continue + } + toPerms := fromPerms + if item.ToSource != item.FromSource { + var toErr error + toPerms, toErr = effectiveFilePerms(d, item.ToSource) + if toErr != nil { + item.Message = "permission denied" + response.Failed = append(response.Failed, item) + continue + } + } + if msg := resourcePatchPermCheck(req.Action, item.FromSource, item.ToSource, fromPerms, toPerms); msg != "" { + item.Message = msg + response.Failed = append(response.Failed, item) + continue + } } // Get source index srcIdx := indexing.GetIndex(item.FromSource) if srcIdx == nil { item.Message = "source not found" - if d.share != nil { + if d.Share.Hash != "" { response.Failed = append(response.Failed, MoveCopyItem{ Message: item.Message, }) @@ -897,7 +1176,7 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont dstIdx := indexing.GetIndex(item.ToSource) if dstIdx == nil { item.Message = "destination source not found" - if d.share != nil { + if d.Share.Hash != "" { response.Failed = append(response.Failed, MoveCopyItem{ Message: item.Message, }) @@ -909,17 +1188,19 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont if srcIdx.Config.ReadOnly && req.Action == "move" { item.Message = "From source is read-only and cannot be moved" - if d.share != nil { + if d.Share.Hash != "" { response.Failed = append(response.Failed, MoveCopyItem{ Message: item.Message, }) continue } + response.Failed = append(response.Failed, item) + continue } if dstIdx.Config.ReadOnly { item.Message = "destination source is read-only" - if d.share != nil { + if d.Share.Hash != "" { response.Failed = append(response.Failed, MoveCopyItem{ Message: item.Message, }) @@ -939,9 +1220,9 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont } // Check access control for both source and destination paths - if !store.Access.Permitted(srcIdx.Path, fullSrcIndexPath, d.user.Username) { + if !state.AccessPermitted(srcIdx.Path, utils.IndexPathFromNormalized(fullSrcIndexPath, true), d.User.Username) { item.Message = "access denied to source path" - if d.share != nil { + if d.Share.Hash != "" { response.Failed = append(response.Failed, MoveCopyItem{ Message: item.Message, }) @@ -950,9 +1231,9 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont response.Failed = append(response.Failed, item) continue } - if !store.Access.Permitted(dstIdx.Path, fullDstIndexPath, d.user.Username) { + if !state.AccessPermitted(dstIdx.Path, utils.IndexPathFromNormalized(fullDstIndexPath, true), d.User.Username) { item.Message = "access denied to destination path" - if d.share != nil { + if d.Share.Hash != "" { response.Failed = append(response.Failed, MoveCopyItem{ Message: item.Message, }) @@ -969,7 +1250,7 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont if err != nil { logger.Errorf("could not resolve source path: %v, item.FromPath: %v", err, item.FromPath) item.Message = "could not resolve source path" - if d.share != nil { + if d.Share.Hash != "" { response.Failed = append(response.Failed, MoveCopyItem{ Message: item.Message, }) @@ -985,7 +1266,7 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont parentDir, _, err := dstIdx.GetRealPath(fullDstParentPath) if err != nil { item.Message = "destination directory does not exist" - if d.share != nil { + if d.Share.Hash != "" { response.Failed = append(response.Failed, MoveCopyItem{ Message: item.Message, }) @@ -1005,7 +1286,7 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont if req.Action == "rename" || req.Action == "move" { if err = validateMoveOperation(realSrc, realDest, isSrcDir); err != nil { item.Message = "invalid move operation, circular reference" - if d.share != nil { + if d.Share.Hash != "" { response.Failed = append(response.Failed, MoveCopyItem{ Message: item.Message, }) @@ -1028,7 +1309,7 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont }) if err != nil { logger.Errorf("Could not run patch action. src=%v dst=%v err=%v", realSrc, realDest, err) - if d.share != nil { + if d.Share.Hash != "" { item.Message = "could not run patch action" response.Failed = append(response.Failed, MoveCopyItem{ Message: item.Message, @@ -1042,6 +1323,7 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont // Success response.Succeeded = append(response.Succeeded, item) + activity.RecordPatchItem(r, toActor(d), req.Action, activity.MoveCopyItem{FromSource: item.FromSource, FromPath: item.FromPath, ToPath: item.ToPath}) } if len(response.Failed) == 0 && len(response.Succeeded) == 0 { @@ -1051,7 +1333,7 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont } // For shares, sanitize the response to only include messages (hide paths) - if d.share != nil { + if d.Share.Hash != "" { sanitizedFailed := make([]MoveCopyItem, len(response.Failed)) for i, item := range response.Failed { sanitizedFailed[i] = MoveCopyItem{ @@ -1075,7 +1357,77 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont statusCode = http.StatusMultiStatus } // If all succeeded, statusCode remains 200 OK - return renderJSON(w, r, response, statusCode) + return RenderJSON(w, r, response, statusCode) +} + +// publicPatchHandler performs a patch operation (e.g., move, copy, rename) on resources in a public share. +// @Summary Move, copy, or rename resources in a public share +// @Description Performs move, copy, or rename operations on multiple resources within a public share. All operations are performed atomically. +// @Tags Resources +// @Accept json +// @Produce json +// @Param hash query string true "Share hash for authentication" +// @Param request body MoveCopyRequest true "Move/copy request with items and action" +// @Success 200 {object} MoveCopyResponse "All operations completed successfully" +// @Success 207 {object} MoveCopyResponse "Partial success - some operations succeeded, some failed" +// @Failure 400 {object} map[string]string "Bad request - invalid JSON or parameters" +// @Failure 403 {object} map[string]string "Forbidden - modify not allowed for this share" +// @Failure 404 {object} map[string]string "Share or resource not found" +// @Failure 500 {object} MoveCopyResponse "Internal server error" +// @Router /public/api/resources [patch] +func publicPatchHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if !d.Share.AllowModify { + return http.StatusForbidden, fmt.Errorf("edit permission not allowed for this share") + } + + sourceName := d.Share.GetSourceName() + if sourceName == "" { + return http.StatusNotFound, fmt.Errorf("source not available") + } + + var shareCreatedByUser *users.User + userValue, err := state.UserForShareOwner(d.Share) + if err == nil { + shareCreatedByUser = &userValue + } + if err != nil { + return http.StatusNotFound, fmt.Errorf("user for share no longer exists") + } + d.User = shareCreatedByUser + + var req MoveCopyRequest + if err = json.NewDecoder(r.Body).Decode(&req); err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid JSON body: %v", err) + } + + if req.Action == "" { + return http.StatusBadRequest, fmt.Errorf("action is required (copy, move, or rename)") + } + + for i := range req.Items { + var sanitizedPath string + sanitizedPath, err = utils.SanitizePath(req.Items[i].FromPath) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid from path: %w", err) + } + req.Items[i].FromSource = sourceName + req.Items[i].FromPath = utils.JoinPathAsUnix(d.Share.Path, sanitizedPath) + sanitizedPath, err = utils.SanitizePath(req.Items[i].ToPath) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid to path: %w", err) + } + req.Items[i].ToSource = sourceName + req.Items[i].ToPath = utils.JoinPathAsUnix(d.Share.Path, sanitizedPath) + } + d.Data = req + + status, err := ResourcePatchHandler(w, r, d) + if err != nil { + logger.Errorf("public patch handler: error processing patch with error %v", err) + return http.StatusInternalServerError, fmt.Errorf("an error occurred while processing the request") + } + + return status, err } func addVersionSuffix(source string) string { @@ -1100,7 +1452,7 @@ type patchActionParams struct { dstIndex string src string dst string - d *requestContext + d *Context isSrcDir bool } @@ -1111,9 +1463,9 @@ func patchAction(ctx context.Context, params patchActionParams) error { return err case "rename", "move": idx := indexing.GetIndex(params.srcIndex) - srcPath := idx.MakeIndexPath(params.src, params.isSrcDir) + srcPath := idx.MakeIndexPath(params.src, params.isSrcDir).String() userScope := "" - userScope, _ = params.d.user.GetScopeForSourceName(params.srcIndex) + userScope, _ = params.d.User.GetScopeForSourceName(params.srcIndex) if userScope != "" && userScope != "/" { // Strip the user scope from srcPath so FileInfoFaster doesn't double it srcPath = strings.TrimPrefix(srcPath, userScope) @@ -1124,9 +1476,9 @@ func patchAction(ctx context.Context, params patchActionParams) error { Path: srcPath, Source: params.srcIndex, IsDir: params.isSrcDir, - ShowHidden: params.d.user.ShowHidden, - HideFileExt: params.d.user.HideFileExt, - }, store.Access, params.d.user, store.Share) + ShowHidden: params.d.User.ShowHidden, + HideFileExt: params.d.User.HideFileExt, + }, params.d.User) if err != nil { return err @@ -1134,7 +1486,12 @@ func patchAction(ctx context.Context, params patchActionParams) error { // delete thumbnails preview.DelThumbs(ctx, *fileInfo) - return files.MoveResource(params.isSrcDir, params.srcIndex, params.dstIndex, params.src, params.dst, store.Share, store.Access) + err = files.MoveResource(params.isSrcDir, params.srcIndex, params.dstIndex, params.src, params.dst) + if err != nil { + return err + } + reconcileSharesAfterMove(params.isSrcDir, params.srcIndex, params.dstIndex, params.src, params.dst) + return nil default: return fmt.Errorf("unsupported action %s: %w", params.action, errors.ErrInvalidRequestParams) } @@ -1150,7 +1507,7 @@ func inspectIndex(w http.ResponseWriter, r *http.Request) { return } info, _ := index.GetReducedMetadata(path, !isNotDir) - renderJSON(w, r, info) // nolint:errcheck + RenderJSON(w, r, info) // nolint:errcheck } func mockData(w http.ResponseWriter, r *http.Request) { @@ -1162,7 +1519,7 @@ func mockData(w http.ResponseWriter, r *http.Request) { return } mockDir := indexing.CreateMockData(NumDirs, numFiles) - renderJSON(w, r, mockDir) // nolint:errcheck + RenderJSON(w, r, mockDir) // nolint:errcheck } // itemsGetHandler efficiently returns a basic list of items for a directory. @@ -1178,19 +1535,70 @@ func mockData(w http.ResponseWriter, r *http.Request) { // @Failure 403 {object} map[string]string "Forbidden (access denied)" // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/resources/items [get] -func itemsGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func itemsGetHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + source := r.URL.Query().Get("source") + filePerms, err := effectiveFilePerms(d, source) + 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") + } items, err := files.GetDirItems(utils.FileOptions{ FollowSymlinks: true, Path: r.URL.Query().Get("path"), Source: r.URL.Query().Get("source"), - ShowHidden: d.user.ShowHidden, + ShowHidden: d.User.ShowHidden, Only: r.URL.Query().Get("only"), - }, store.Access, d.user) + }, d.User) if err != nil { if err == errors.ErrAccessDenied { return http.StatusForbidden, err } return http.StatusInternalServerError, err } - return renderJSON(w, r, items) + return RenderJSON(w, r, items) +} + +// publicItemsGetHandler efficiently returns a basic list of items for a directory in a public share. +// @Summary Get directory items (public share) +// @Description Efficiently returns a basic list of items for the specified path in a public share. Use hash for authentication instead of source. Use 'only' parameter to filter by only files or folders. +// @Tags Resources +// @Accept json +// @Produce json +// @Param hash query string true "Share hash for authentication" +// @Param path query string false "Path within the share to list child items. Defaults to share root." +// @Param only query string false "Filter: 'files', 'folders', or omit for both" +// @Success 200 {object} files.Items "lists files and folders" +// @Failure 403 {object} map[string]string "Forbidden (access denied)" +// @Failure 404 {object} map[string]string "Share not found or source not found" +// @Failure 500 {object} map[string]string "Internal server error" +// @Router /public/api/resources/items [get] +func publicItemsGetHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + sourceInfo, ok := settings.Config.Server.SourceMap[d.Share.SourcePath] + if !ok { + return http.StatusNotFound, fmt.Errorf("source not found") + } + items, err := files.GetDirItems(utils.FileOptions{ + FollowSymlinks: true, + Path: d.IndexPath, + Source: sourceInfo.Name, + ShowHidden: d.ShareUser.ShowHidden, + Only: r.URL.Query().Get("only"), + }, d.ShareUser) + if err != nil { + if err == errors.ErrAccessDenied { + return http.StatusForbidden, err + } + return http.StatusInternalServerError, err + } + return RenderJSON(w, r, items) +} + +func bulkDeleteActivityItems(items []BulkDeleteItem) []activity.BulkDeleteItem { + out := make([]activity.BulkDeleteItem, len(items)) + for i, it := range items { + out[i] = activity.BulkDeleteItem{Source: it.Source, Path: it.Path} + } + return out } diff --git a/backend/internal/web/resource_permissions_test.go b/backend/internal/web/resource_permissions_test.go new file mode 100644 index 0000000000..3653dd34c8 --- /dev/null +++ b/backend/internal/web/resource_permissions_test.go @@ -0,0 +1,163 @@ +package web + +import ( + "net/http" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func TestResourcePostPermCheck(t *testing.T) { + t.Parallel() + + full := users.SourceFilePermissions{View: true, Download: true, Modify: true, Create: true, Delete: true} + createOnly := users.SourceFilePermissions{View: true, Download: true, Create: true} + modifyOnly := users.SourceFilePermissions{View: true, Download: true, Modify: true} + + tests := []struct { + name string + exists bool + override bool + perms users.SourceFilePermissions + wantErr bool + }{ + {name: "new target requires create", exists: false, perms: createOnly}, + {name: "new target denied without create", exists: false, perms: modifyOnly, wantErr: true}, + {name: "override existing requires modify", exists: true, override: true, perms: full}, + {name: "override existing denied without modify", exists: true, override: true, perms: createOnly, wantErr: true}, + {name: "existing without override skips modify gate", exists: true, override: false, perms: createOnly}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + status, err := resourcePostPermCheck(tt.exists, tt.override, tt.perms) + if tt.wantErr { + if err == nil || status != http.StatusForbidden { + t.Fatalf("status=%d err=%v, want forbidden", status, err) + } + return + } + if err != nil || status != 0 { + t.Fatalf("status=%d err=%v, want allow", status, err) + } + }) + } +} + +func TestResourcePatchPermCheck(t *testing.T) { + t.Parallel() + + full := users.SourceFilePermissions{View: true, Download: true, Modify: true, Create: true, Delete: true} + downloadOnly := users.SourceFilePermissions{View: true, Download: true} + createOnly := users.SourceFilePermissions{View: true, Create: true} + modifyOnly := users.SourceFilePermissions{View: true, Modify: true} + + tests := []struct { + name string + action string + fromSource string + toSource string + fromPerms users.SourceFilePermissions + toPerms users.SourceFilePermissions + wantMsg string + }{ + { + name: "copy requires download and create", + action: "copy", fromSource: "a", toSource: "b", + fromPerms: full, toPerms: full, + }, + { + name: "copy denied without source download", + action: "copy", fromSource: "a", toSource: "b", + fromPerms: createOnly, toPerms: full, + wantMsg: "user is not allowed to copy", + }, + { + name: "copy denied without destination create", + action: "copy", fromSource: "a", toSource: "b", + fromPerms: downloadOnly, toPerms: modifyOnly, + wantMsg: "user is not allowed to copy", + }, + { + name: "same-source move requires modify", + action: "move", fromSource: "a", toSource: "a", + fromPerms: modifyOnly, toPerms: modifyOnly, + }, + { + name: "same-source rename requires modify", + action: "rename", fromSource: "a", toSource: "a", + fromPerms: modifyOnly, toPerms: modifyOnly, + }, + { + name: "move denied without source modify", + action: "move", fromSource: "a", toSource: "a", + fromPerms: downloadOnly, toPerms: downloadOnly, + wantMsg: "user is not allowed to modify", + }, + { + name: "cross-source move requires destination modify", + action: "move", fromSource: "a", toSource: "b", + fromPerms: full, toPerms: downloadOnly, + wantMsg: "user is not allowed to modify destination source", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := resourcePatchPermCheck(tt.action, tt.fromSource, tt.toSource, tt.fromPerms, tt.toPerms) + if got != tt.wantMsg { + t.Fatalf("resourcePatchPermCheck() = %q, want %q", got, tt.wantMsg) + } + }) + } +} + +func TestWebDAVMethodPermissionMatrix(t *testing.T) { + t.Parallel() + + type check struct { + method string + perms users.SourceFilePermissions + allow bool + } + + tests := []check{ + {method: "PROPFIND", perms: users.SourceFilePermissions{View: true}, allow: true}, + {method: http.MethodOptions, perms: users.SourceFilePermissions{View: true}, allow: true}, + {method: http.MethodGet, perms: users.SourceFilePermissions{View: true}, allow: false}, + {method: http.MethodHead, perms: users.SourceFilePermissions{Download: true}, allow: true}, + {method: "PROPFIND", perms: users.SourceFilePermissions{Download: true}, allow: false}, + {method: "MKCOL", perms: users.SourceFilePermissions{Create: true}, allow: true}, + {method: "MKCOL", perms: users.SourceFilePermissions{Modify: true}, allow: false}, + {method: http.MethodPut, perms: users.SourceFilePermissions{Modify: true}, allow: true}, + {method: http.MethodPut, perms: users.SourceFilePermissions{Create: true}, allow: false}, + {method: http.MethodDelete, perms: users.SourceFilePermissions{Delete: true}, allow: true}, + {method: http.MethodDelete, perms: users.SourceFilePermissions{Modify: true}, allow: false}, + {method: "COPY", perms: users.SourceFilePermissions{Download: true, Create: true}, allow: true}, + {method: "COPY", perms: users.SourceFilePermissions{Download: true, Modify: true}, allow: false}, + {method: "COPY", perms: users.SourceFilePermissions{Create: true, Modify: true}, allow: false}, + {method: "MOVE", perms: users.SourceFilePermissions{Modify: true}, allow: true}, + {method: "MOVE", perms: users.SourceFilePermissions{Create: true, Download: true}, allow: false}, + {method: "PROPPATCH", perms: users.SourceFilePermissions{View: true, Download: true, Modify: true, Create: true, Delete: true}, allow: false}, + {method: "LOCK", perms: users.SourceFilePermissions{View: true, Download: true, Modify: true, Create: true, Delete: true}, allow: false}, + } + + for _, tt := range tests { + name := tt.method + if !tt.allow { + name += "_denied" + } + t.Run(name, func(t *testing.T) { + status, err := webDAVMethodPermission(tt.method, tt.perms) + if tt.allow { + if err != nil || status != 0 { + t.Fatalf("status=%d err=%v, want allow", status, err) + } + return + } + if err == nil || status != http.StatusForbidden { + t.Fatalf("status=%d err=%v, want forbidden", status, err) + } + }) + } +} diff --git a/backend/http/search.go b/backend/internal/web/search.go similarity index 58% rename from backend/http/search.go rename to backend/internal/web/search.go index a3ecec7a5e..5fe673f63f 100644 --- a/backend/http/search.go +++ b/backend/internal/web/search.go @@ -1,4 +1,4 @@ -package http +package web import ( "fmt" @@ -8,9 +8,12 @@ import ( "strconv" "strings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/indexing" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + ) type searchOptions struct { @@ -35,85 +38,43 @@ type scopedSourcePath struct { // searchHandler handles search requests for files based on the provided query. // -// This endpoint processes a search query, retrieves relevant file paths, and -// returns a JSON response with the search results. The search is performed -// against the file index, which is built from the root directory specified in -// the server's configuration. The results are filtered based on the user's scope. -// -// Per-source search scope (preferred for multi-source): +// Per-source search scope: // // Repeated query parameter "scope" with the value "sourceName:relativePath", -// split on the first colon. The path is user-relative (same as the legacy single-scope -// path). Encode the whole value with the normal query string rules (e.g. %3A for ':' if needed). +// split on the first colon. Encode the whole value with normal query string rules (e.g. %3A for ':'). // Examples: // ?scope=mydisk:/&scope=backup:/Photos // Duplicate source names: the last repeated scope for that source wins. // -// Legacy (still supported): +// When scope is omitted, each listed source is searched from the root of the user's scope. // -// - source / sources: which catalogues to search -// - scope: a single path (no 'source:' prefix) applied only when exactly one source is specified. -// When multiple sources are listed and no "source:path" scopes are used, each source is searched -// from the root of the user's scope (same as before). -// -// The handler expects the following headers in the request: -// - SessionId: A unique identifier for the user's session. -// -// The request URL should include query parameters: -// - query: Structured filter prefix only, or full legacy search string when "terms" parameters are not used +// Query parameters: +// - query: Structured filter prefix, or full search string when "terms" parameters are not used // - terms: Repeated query parameter; each value is one literal search term. OR-combined by default; use termJoin=and for AND. // - termJoin: Optional; "and" requires every term to match; any other value keeps OR semantics (default). -// - source: Source name (deprecated, use 'sources' instead) -// - sources: Comma-separated list of source names (e.g., "source1,source2") when not using scoped scope=source:path params -// - scope: Either (1) repeated "sourceName:relativePath" as above, or (2) legacy single path within user scope for a single-source search +// - sources: Comma-separated list of source names when not using repeated scope=source:path params +// - scope: Repeated "sourceName:relativePath" per source // - olderThan: Optional Unix time in seconds; only items modified strictly before this instant // - newerThan: Optional Unix time in seconds; only items modified on or after this instant -// - useWildcard: Optional; when true, file names are matched with SQLite GLOB (wildcards) instead of substring search. Legacy query params glob and useGlob are accepted as aliases. -// -// Example request (single source): -// -// GET api/tools/search?query=myfile&source=mysource -// -// Example request (multiple sources with per-source folders): -// -// GET api/tools/search?query=myfile&scope=source1:/&scope=source2:/documents -// -// Example response: -// [ -// -// { -// "path": "/path/to/myfile.txt", -// "type": "text", -// "source": "mysource" -// }, -// { -// "path": "/path/to/mydir/", -// "type": "directory", -// "source": "mysource" -// } -// -// ] +// - useWildcard: Optional; when true, file names are matched with SQLite GLOB (wildcards) instead of substring search // // @Summary Search Files // @Description Searches for files matching the provided query. Returns file paths and metadata based on the user's session and scope. Supports searching across multiple sources when using the 'sources' parameter. // @Tags Tools // @Accept json // @Produce json -// @Param query query string false "Filter prefix or full legacy search text (required when no terms are supplied)" +// @Param query query string false "Filter prefix or full search text (required when no terms are supplied)" // @Param terms query []string false "Repeated: one literal search term per parameter; combined with OR unless termJoin=and" -// @Param source query string false "Source name for the desired source (deprecated, use 'sources' instead)" // @Param sources query string false "Comma-separated source names when not using repeated scope=source:path" -// @Param scope query []string false "Repeated: either 'sourceName:relativePath' per source, or legacy single path when one source" +// @Param scope query []string false "Repeated: 'sourceName:relativePath' per source" // @Param olderThan query int false "Unix seconds; only results modified strictly before this time" // @Param newerThan query int false "Unix seconds; only results modified on or after this time" // @Param useWildcard query bool false "When true, match indexed file names with SQLite GLOB (wildcard patterns)" -// @Param glob query bool false "Deprecated: alias for useWildcard" -// @Param useGlob query bool false "Deprecated: alias for useWildcard" // @Param termJoin query string false "Optional: 'and' to require all repeated 'terms' match; default is OR" // @Success 200 {array} indexing.SearchResult "List of search results with source field populated" // @Failure 400 {object} map[string]string "Bad Request" // @Router /api/tools/search [get] -func searchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func searchHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { searchOptions, err := prepSearchOptions(r, d) if err != nil { return http.StatusBadRequest, err @@ -126,7 +87,6 @@ func searchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i var response []*indexing.SearchResult if len(searchOptions.sources) == 1 { - // Single source - use the existing Search method for backward compatibility index := indexing.GetIndex(searchOptions.sources[0]) if index == nil { return http.StatusBadRequest, fmt.Errorf("index not found for source %s", searchOptions.sources[0]) @@ -134,7 +94,6 @@ func searchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i combinedPath := searchOptions.combinedPath[searchOptions.sources[0]] response = index.SearchParsed(searchOptions.parsed, combinedPath, searchOptions.sessionId, searchOptions.largest, searchSize, searchOptions.olderThanUnix, searchOptions.newerThanUnix, searchOptions.useWildcard) } else { - // Multiple sources - use the new SearchMultiSources function response = indexing.SearchMultiSourcesParsed(searchOptions.parsed, searchOptions.sources, searchOptions.combinedPath, searchOptions.sessionId, searchOptions.largest, searchSize, searchOptions.olderThanUnix, searchOptions.newerThanUnix, searchOptions.useWildcard) } @@ -144,7 +103,7 @@ func searchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i index := indexing.GetIndex(result.Source) combinedPath := searchOptions.combinedPath[result.Source] indexPath := utils.JoinPathAsUnix(combinedPath, result.Path) - if store.Access != nil && !store.Access.Permitted(index.Path, indexPath, d.user.Username) { + if !state.AccessPermitted(index.Path, utils.IndexPathFromNormalized(indexPath, true), d.User.Username) { continue // Silently skip this file/folder } // Remove the user scope from the path (modifying in place is safe - these are fresh allocations) @@ -154,7 +113,7 @@ func searchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i } filteredResponse = append(filteredResponse, result) // This is to filter the ext-hidden files from search results, like the ones with the hidden property - if d.user.HideFileExt != "" { + if d.User.HideFileExt != "" { filtered := filteredResponse[:0] for _, res := range filteredResponse { if res.Type == "directory" { @@ -162,75 +121,54 @@ func searchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i continue } baseName := filepath.Base(res.Path) - if !utils.HideFileByExt(baseName, d.user.HideFileExt) { + if !utils.HideFileByExt(baseName, d.User.HideFileExt) { filtered = append(filtered, res) } } filteredResponse = filtered } } - return renderJSON(w, r, filteredResponse) + return RenderJSON(w, r, filteredResponse) } -// parseRepeatedScopeParams interprets repeated "scope" query values. -// If a value contains ':', it is "sourceName:relativePath" (first ':' separates source and path). -// Otherwise it is a legacy single path (at most one such value across all scope params). -func parseRepeatedScopeParams(scopeQueryValues []string) ([]scopedSourcePath, string, error) { +// parseRepeatedScopeParams interprets repeated "scope" query values as "sourceName:relativePath". +func parseRepeatedScopeParams(scopeQueryValues []string) ([]scopedSourcePath, error) { var clauses []scopedSourcePath - legacyPath := "" for _, raw := range scopeQueryValues { raw = strings.TrimSpace(raw) if raw == "" { continue } idx := strings.IndexByte(raw, ':') - if idx > 0 { - src := strings.TrimSpace(raw[:idx]) - if src == "" { - return nil, "", fmt.Errorf("invalid scope parameter %q: empty source name before ':'", raw) - } - pathPart := strings.TrimSpace(raw[idx+1:]) - if pathPart == "" { - pathPart = "/" - } - cleanPath, err := utils.SanitizeUserPath(pathPart) - if err != nil { - return nil, "", fmt.Errorf("invalid path in scope parameter %q: %v", raw, err) - } - clauses = append(clauses, scopedSourcePath{source: src, relPath: cleanPath}) - continue + if idx <= 0 { + return nil, fmt.Errorf("invalid scope parameter %q: use scope=sourceName:relativePath", raw) } - if idx == 0 { - return nil, "", fmt.Errorf("invalid scope parameter %q: source name must precede ':'", raw) + src := strings.TrimSpace(raw[:idx]) + if src == "" { + return nil, fmt.Errorf("invalid scope parameter %q: empty source name before ':'", raw) } - if legacyPath != "" { - return nil, "", fmt.Errorf("multiple legacy scope paths without a source prefix are not allowed; use scope=sourceName:path for each source") + pathPart := strings.TrimSpace(raw[idx+1:]) + if pathPart == "" { + pathPart = "/" } - clean, err := utils.SanitizeUserPath(raw) + cleanPath, err := utils.SanitizePath(pathPart) if err != nil { - return nil, "", fmt.Errorf("invalid scope: %v", err) + return nil, fmt.Errorf("invalid path in scope parameter %q: %v", raw, err) } - legacyPath = clean + clauses = append(clauses, scopedSourcePath{source: src, relPath: cleanPath}) } - return clauses, legacyPath, nil + return clauses, nil } -func prepSearchOptions(r *http.Request, d *requestContext) (*searchOptions, error) { +func prepSearchOptions(r *http.Request, d *Context) (*searchOptions, error) { query := r.URL.Query().Get("query") rawTerms := r.URL.Query()["terms"] termJoin := strings.TrimSpace(strings.ToLower(r.URL.Query().Get("termJoin"))) matchAllTerms := termJoin == "and" sourcesParam := r.URL.Query().Get("sources") - sourceParam := r.URL.Query().Get("source") // deprecated, but still supported - scopeValues := r.URL.Query()["scope"] // repeated; use slice, not Get (first only) + scopeValues := r.URL.Query()["scope"] largest := r.URL.Query().Get("largest") == "true" wildRaw := strings.TrimSpace(r.URL.Query().Get("useWildcard")) - if wildRaw == "" { - wildRaw = strings.TrimSpace(r.URL.Query().Get("glob")) - } - if wildRaw == "" { - wildRaw = strings.TrimSpace(r.URL.Query().Get("useGlob")) - } useWildcard := strings.EqualFold(wildRaw, "true") || wildRaw == "1" olderThanUnix, err := parseOptionalUnixQueryParam("olderThan", r.URL.Query().Get("olderThan")) if err != nil { @@ -241,7 +179,7 @@ func prepSearchOptions(r *http.Request, d *requestContext) (*searchOptions, erro return nil, err } - scopedClauses, legacyScopeOnly, err := parseRepeatedScopeParams(scopeValues) + scopedClauses, err := parseRepeatedScopeParams(scopeValues) if err != nil { return nil, err } @@ -256,7 +194,7 @@ func prepSearchOptions(r *http.Request, d *requestContext) (*searchOptions, erro parsed := iteminfo.BuildSearchOptionsFromQuery(query, normalizedTerms, matchAllTerms) - minLen := config.Server.MinSearchLength + minLen := settings.Config.Server.MinSearchLength if !largest { if len(normalizedTerms) > 0 { for _, t := range normalizedTerms { @@ -276,9 +214,6 @@ func prepSearchOptions(r *http.Request, d *requestContext) (*searchOptions, erro var searchScopeOut string if len(scopedClauses) > 0 { - if legacyScopeOnly != "" { - return nil, fmt.Errorf("cannot mix legacy scope path with scope=sourceName:path parameters") - } pathBySource := make(map[string]string) for _, c := range scopedClauses { if _, ok := pathBySource[c.source]; !ok { @@ -291,21 +226,18 @@ func prepSearchOptions(r *http.Request, d *requestContext) (*searchOptions, erro if index == nil { return nil, fmt.Errorf("index not found for source %s", source) } - userscope, err := d.user.GetScopeForSourceName(source) + userscope, err := d.User.GetScopeForSourceName(source) if err != nil { return nil, err } rel := strings.TrimPrefix(pathBySource[source], ".") - combinedPathMap[source] = index.MakeIndexPath(filepath.Join(userscope, rel), true) + combinedPathMap[source] = index.MakeIndexPath(filepath.Join(userscope, rel), true).String() } } else { - if sourcesParam != "" { - sources = strings.Split(sourcesParam, ",") - } else if sourceParam != "" { - sources = []string{sourceParam} - } else { - return nil, fmt.Errorf("either 'source', 'sources', or repeated scope=sourceName:path query parameters are required") + if sourcesParam == "" { + return nil, fmt.Errorf("'sources' or repeated scope=sourceName:path query parameters are required") } + sources = strings.Split(sourcesParam, ",") for i := range sources { sources[i] = strings.TrimSpace(sources[i]) } @@ -317,15 +249,7 @@ func prepSearchOptions(r *http.Request, d *requestContext) (*searchOptions, erro } } - scope := legacyScopeOnly - if scope == "" { - scope = "/" - } - cleanScope, err := utils.SanitizeUserPath(scope) - if err != nil { - return nil, fmt.Errorf("invalid scope: %v", err) - } - searchScopeOut = strings.TrimPrefix(cleanScope, ".") + searchScopeOut = "/" if len(sources) > 1 { searchScopeOut = "" @@ -333,12 +257,11 @@ func prepSearchOptions(r *http.Request, d *requestContext) (*searchOptions, erro for _, source := range sources { index := indexing.GetIndex(source) - userscope, err := d.user.GetScopeForSourceName(source) + userscope, err := d.User.GetScopeForSourceName(source) if err != nil { return nil, err } - combinedPath := index.MakeIndexPath(filepath.Join(userscope, searchScopeOut), true) - combinedPathMap[source] = combinedPath + combinedPathMap[source] = index.MakeIndexPath(filepath.Join(userscope, searchScopeOut), true).String() } } diff --git a/backend/internal/web/server.go b/backend/internal/web/server.go new file mode 100644 index 0000000000..2d1ab09ed1 --- /dev/null +++ b/backend/internal/web/server.go @@ -0,0 +1,197 @@ +package web + +import ( + "context" + "crypto/tls" + "embed" + "encoding/json" + "fmt" + "html/template" + "io/fs" + "net" + "net/http" + "os" + "time" + + _ "net/http/pprof" + + "github.com/coreos/go-systemd/v22/activation" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/internal/auth" + "github.com/gtsteffaniak/filebrowser/backend/internal/events" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/go-logger/logger" +) + +// Deps holds injected dependencies for HTTP handlers and middleware. +type Deps struct { + Store *state.Store + Files *files.Service + Auth *auth.Service +} + +var ( + runtimeDeps Deps + assetFs fs.FS +) + +func initRuntime(deps Deps, assets fs.FS) { + runtimeDeps = deps + assetFs = assets +} + +// Embed the files in the frontend/dist directory +// +//go:embed embed/* +var assets embed.FS + +// GetEmbeddedAssets returns the embedded assets filesystem +func GetEmbeddedAssets() embed.FS { + return assets +} + +// StartHttp starts the HTTP server and blocks until ctx is cancelled. +func StartHttp(ctx context.Context, deps Deps, shutdownComplete chan struct{}) { + if settings.Env.IsDevMode { + go func() { + if err := http.ListenAndServe("localhost:6060", nil); err != nil { + logger.Fatalf("pprof server error: %v", err) + } + }() + } + + fs := fileutils.GetAssetFS() + if fs == nil { + logger.Fatal("Asset filesystem not initialized. Call fileutils.InitAssetFS first.") + } + + templates := template.New("").Funcs(template.FuncMap{ + "marshal": func(v interface{}) (string, error) { + a, err := json.Marshal(v) + return string(a), err + }, + }) + if !settings.Env.IsDevMode { + templates = template.Must(templates.ParseFS(fs, "public/index.html")) + } + templateRenderer = &TemplateRenderer{ + templates: templates, + devMode: settings.Env.IsDevMode, + } + + initRuntime(deps, fs) + + router := http.NewServeMux() + api := http.NewServeMux() + publicRoutes := http.NewServeMux() + publicApi := http.NewServeMux() + + configureHTTPRouter(router, api, publicRoutes, publicApi) + + srv := &http.Server{ + Addr: settings.HTTPListenAddr(settings.Config.Http.ListenAddress, settings.Config.Http.Port), + Handler: muxWithMiddleware(router), + } + listenAddress := settings.Config.Http.ListenAddress + go func() { + var listener net.Listener + var err error + + if settings.Config.Http.Socket != "" { + if err = os.Remove(settings.Config.Http.Socket); err != nil && !os.IsNotExist(err) { + logger.Fatalf("Could not remove existing socket: %v", err) + } + listener, err = net.Listen("unix", settings.Config.Http.Socket) + if err != nil { + logger.Fatalf("Could not listen on unix socket: %v", err) + } + logger.Infof("Running at : unix://%s%s", settings.Config.Http.Socket, settings.Config.Http.BaseURL) + } else if settings.Config.Http.TLSCert != "" && settings.Config.Http.TLSKey != "" { + cer, err := tls.LoadX509KeyPair(settings.Config.Http.TLSCert, settings.Config.Http.TLSKey) + if err != nil { + logger.Fatalf("Could not load certificate: %v", err) + } + tlsConfig := &tls.Config{ + MinVersion: tls.VersionTLS12, + Certificates: []tls.Certificate{cer}, + } + scheme := "https" + port := "" + if settings.Config.Http.Port != 443 { + port = fmt.Sprintf(":%d", settings.Config.Http.Port) + } + fullURL := fmt.Sprintf("%s://%s%s%s", scheme, listenAddress, port, settings.Config.Http.BaseURL) + logger.Infof("Running at : %s", fullURL) + + socketActivationListeners, err := activation.TLSListeners(tlsConfig) + if err == nil && len(socketActivationListeners) > 0 { + listener = socketActivationListeners[0] + logger.Debug("Socket activation detected. Listening address is being controlled by systemd.") + } else if err != nil { + logger.Debugf("Socket activation failed: %v", err) + } + if listener == nil { + listener, err = tls.Listen("tcp", srv.Addr, tlsConfig) + if err != nil { + logger.Fatalf("Could not start TLS server: %v", err) + } + } + } else { + scheme := "http" + port := "" + if settings.Config.Http.Port != 80 { + port = fmt.Sprintf(":%d", settings.Config.Http.Port) + } + fullURL := fmt.Sprintf("%s://%s%s%s", scheme, listenAddress, port, settings.Config.Http.BaseURL) + logger.Infof("Running at : %s", fullURL) + + socketActivationListeners, err := activation.Listeners() + if err == nil && len(socketActivationListeners) > 0 { + listener = socketActivationListeners[0] + logger.Debug("Socket activation detected. Listening address is being controlled by systemd.") + } else if err != nil { + logger.Debugf("Socket activation failed: %v", err) + } + if listener == nil { + addr := srv.Addr + if addr == "" { + addr = ":http" + } + listener, err = net.Listen("tcp", addr) + if err != nil { + logger.Fatalf("Server error: %v", err) + } + } + } + + if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed { + logger.Fatalf("Server error: %v", err) + } + }() + + <-ctx.Done() + logger.Info("Shutting down HTTP server...") + events.Shutdown() + + if err := state.Close(); err != nil { + logger.Errorf("Failed to close state management: %v", err) + } + + shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + if err := srv.Shutdown(shutdownCtx); err != nil { + logger.Errorf("HTTP server forced to shut down: %v", err) + } else { + logger.Info("HTTP server shut down gracefully.") + } + + if settings.Config.Http.Socket != "" { + if err := os.Remove(settings.Config.Http.Socket); err != nil && !os.IsNotExist(err) { + logger.Debugf("Could not remove unix socket: %v", err) + } + } + + close(shutdownComplete) +} diff --git a/backend/internal/web/settings.go b/backend/internal/web/settings.go new file mode 100644 index 0000000000..c70e3af471 --- /dev/null +++ b/backend/internal/web/settings.go @@ -0,0 +1,273 @@ +package web + +import ( + "encoding/json" + "fmt" + "io" + "io/fs" + "net/http" + "os" + + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/go-logger/logger" +) + +// settingsGetHandler retrieves the current system settings. +// @Summary Get system settings +// @Description Returns the current configuration settings for signup, user directories, rules, frontend. +// @Tags Settings +// @Accept json +// @Produce json +// @Param property query string false "Property to retrieve: `userDefaults`, `frontend`, `auth`, `server`, `sources`" +// @Success 200 {object} settings.Settings "System settings data" +// @Router /api/settings [get] +func settingsGetHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + property := r.URL.Query().Get("property") + if property != "" { + // get property by name + switch property { + case "userDefaults": + return RenderJSON(w, r, state.GetDefaultUserDefaults()) + case "frontend": + return RenderJSON(w, r, settings.Config.Frontend) + case "auth": + return RenderJSON(w, r, settings.Config.Auth) + case "server": + return RenderJSON(w, r, settings.Config.Server) + case "sources": + return RenderJSON(w, r, settings.Config.Server.Sources) + default: + return http.StatusNotFound, nil + } + } + return RenderJSON(w, r, &settings.Config) +} + +// settingsConfigHandler returns the current system settings as YAML. +// @Summary Get system settings as YAML +// @Description Returns the current running configuration settings as YAML format with optional comments and filtering. +// @Tags Settings +// @Accept json +// @Produce text/plain +// @Param full query boolean false "Show all values (true) or only non-default values (false, default)" +// @Param comments query boolean false "Include comments in YAML (true) or plain YAML (false, default)" +// @Success 200 {string} string "System settings in YAML format" +// @Router /api/settings/config [get] +func settingsConfigHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + // Parse query parameters + fullParam := r.URL.Query().Get("full") + commentsParam := r.URL.Query().Get("comments") + + showFull := fullParam == "true" + showComments := commentsParam == "true" + + var err error + var yamlConfig string + + // Try to read the generated YAML file for comments (should always exist) + var embeddedYaml []byte + var readErr error + + if settings.Env.EmbeddedFs { + embeddedYaml, readErr = fs.ReadFile(assetFs, "embed/config.generated.yaml") + } else { + embeddedYaml, readErr = os.ReadFile("internal/web/dist/config.generated.yaml") + if readErr != nil { + return http.StatusInternalServerError, fmt.Errorf("error reading generated YAML: %v", readErr) + } + } + + // If we successfully read the generated YAML, use it as the comment source + if readErr == nil && len(embeddedYaml) > 0 { + yamlConfig, err = settings.GenerateConfigYamlWithEmbedded(&settings.Config, showComments, showFull, false, string(embeddedYaml)) + if err != nil { + return http.StatusInternalServerError, fmt.Errorf("error generating YAML: %v", err) + } + } else { + // Fallback to Go source parsing if generated YAML doesn't exist + yamlConfig, err = settings.GenerateConfigYaml(&settings.Config, showComments, showFull, false) + if err != nil { + return http.StatusInternalServerError, fmt.Errorf("error generating YAML: %v", err) + } + } + + // Set content type and write response + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + if _, err := w.Write([]byte(yamlConfig)); err != nil { + return http.StatusInternalServerError, err + } + + return http.StatusOK, nil +} + +func getSourceInfoHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + sources := d.User.GetSourceNames() + reducedIndexes := map[string]indexing.ReducedIndex{} + for _, source := range sources { + reducedIndex, err := indexing.GetIndexInfo(source, false) + if err != nil { + logger.Debugf("error getting index info: %v", err) + continue + } + showScannerInfo := r.URL.Query().Get("scanners") == "true" + if !showScannerInfo { + reducedIndex.Scanners = nil + } + reducedIndexes[source] = reducedIndex + } + return RenderJSON(w, r, reducedIndexes) +} + +type userDefaultsResponse struct { + Values *settings.UserDefaults `json:"values,omitempty"` + Enforced settings.UserDefaultsEnforcement `json:"enforced"` + LockedFromConfigPaths []string `json:"lockedFromConfigPaths,omitempty"` + LockMessage string `json:"lockMessage,omitempty"` +} + +func userDefaultsLockMeta() (paths []string, message string) { + paths = settings.ConfigSpecifiedUserDefaultPaths() + if len(paths) == 0 { + return nil, "" + } + return paths, settings.UserDefaultsConfigLockMessage +} + +func settingsUserDefaultsGetHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if scope := r.URL.Query().Get("scope"); scope != "" && scope != "default" { + return http.StatusBadRequest, fmt.Errorf("per-login user defaults scopes are no longer supported") + } + lockedPaths, lockMessage := userDefaultsLockMeta() + enforced := state.GetEnforcedUserDefaults() + if !d.User.Permissions.Admin { + return RenderJSON(w, r, userDefaultsResponse{ + Enforced: enforced, + LockedFromConfigPaths: lockedPaths, + LockMessage: lockMessage, + }) + } + values := state.GetUserDefaults() + return RenderJSON(w, r, userDefaultsResponse{ + Values: &values, + Enforced: enforced, + LockedFromConfigPaths: lockedPaths, + LockMessage: lockMessage, + }) +} + +func settingsUserDefaultsPatchHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if scope := r.URL.Query().Get("scope"); scope != "" && scope != "default" { + return http.StatusBadRequest, fmt.Errorf("per-login user defaults scopes are no longer supported") + } + patchJSON, err := io.ReadAll(r.Body) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("read user defaults patch: %w", err) + } + if len(patchJSON) == 0 { + return http.StatusBadRequest, fmt.Errorf("empty user defaults patch body") + } + + var top map[string]json.RawMessage + if err = json.Unmarshal(patchJSON, &top); err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid user defaults patch JSON: %w", err) + } + var enforcedPatch []byte + if raw, ok := top["enforced"]; ok { + enforcedPatch = raw + delete(top, "enforced") + } + valuesPatch, err := json.Marshal(top) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("marshal user defaults values patch: %w", err) + } + + hasValues := len(valuesPatch) > 2 + hasEnforced := len(enforcedPatch) > 0 + if hasValues && hasEnforced { + return http.StatusBadRequest, fmt.Errorf("patch values and enforced in a single request is not supported") + } + if !hasValues && !hasEnforced { + return http.StatusBadRequest, fmt.Errorf("empty user defaults patch body") + } + + if hasValues { + if err := settings.ValidateSinglePropertyUserDefaultsPatch(valuesPatch); err != nil { + return http.StatusBadRequest, err + } + if err := state.PatchUserDefaults(valuesPatch); err != nil { + logger.Errorf("failed to patch user defaults: %v", err) + return http.StatusInternalServerError, fmt.Errorf("failed to update user defaults") + } + } + if hasEnforced { + if err := settings.ValidateSinglePropertyUserDefaultsPatch(enforcedPatch); err != nil { + return http.StatusBadRequest, err + } + if err := state.PatchUserDefaultsEnforced(enforcedPatch); err != nil { + logger.Errorf("failed to patch enforced user defaults: %v", err) + return http.StatusInternalServerError, fmt.Errorf("failed to update enforced user defaults") + } + } + return http.StatusNoContent, nil +} + +func settingsSourceGetHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + // Read-only global source file permission defaults (used by user edit/create UI). + return RenderJSON(w, r, state.GetSourceSettings()) +} + +func settingsSourcePatchHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + patchJSON, err := io.ReadAll(r.Body) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("read source settings patch: %w", err) + } + defer r.Body.Close() + if len(patchJSON) == 0 { + return http.StatusBadRequest, fmt.Errorf("empty source settings patch body") + } + + var top map[string]json.RawMessage + if err = json.Unmarshal(patchJSON, &top); err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid source settings patch JSON: %w", err) + } + var enforcedPatch []byte + if raw, ok := top["enforcedPermissions"]; ok { + enforcedPatch = raw + delete(top, "enforcedPermissions") + } + valuesPatch, err := json.Marshal(top) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("marshal source settings values patch: %w", err) + } + + hasValues := len(valuesPatch) > 2 + hasEnforced := len(enforcedPatch) > 0 + if hasValues && hasEnforced { + return http.StatusBadRequest, fmt.Errorf("patch defaultPermissions and enforcedPermissions in a single request is not supported") + } + if !hasValues && !hasEnforced { + return http.StatusBadRequest, fmt.Errorf("empty source settings patch body") + } + + if hasValues { + if err := settings.ValidateSinglePropertyUserDefaultsPatch(valuesPatch); err != nil { + return http.StatusBadRequest, err + } + if err := settings.ValidateSourceDefaultsPatchNotConfigLocked(valuesPatch); err != nil { + return http.StatusBadRequest, err + } + if err := state.PatchSourceAccessDefaults(valuesPatch); err != nil { + logger.Errorf("failed to update source settings: %v", err) + return http.StatusInternalServerError, fmt.Errorf("failed to update source settings") + } + } + if hasEnforced { + if err := state.PatchSourceAccessEnforced(enforcedPatch); err != nil { + logger.Errorf("failed to patch enforced source permissions: %v", err) + return http.StatusInternalServerError, fmt.Errorf("failed to update enforced source permissions") + } + } + return RenderJSON(w, r, state.GetSourceSettings()) +} diff --git a/backend/internal/web/share.go b/backend/internal/web/share.go new file mode 100644 index 0000000000..da7fb4c73a --- /dev/null +++ b/backend/internal/web/share.go @@ -0,0 +1,850 @@ +package web + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "strconv" + "strings" + "time" + + "golang.org/x/crypto/bcrypt" + + "github.com/gtsteffaniak/filebrowser/backend/internal/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/go-logger/logger" +) + +// shareListHandler returns a list of all share links. +// @Summary List share links +// @Description Returns a list of share links for the current user, or all links if the user is an admin. +// @Tags Shares +// @Accept json +// @Produce json +// @Success 200 {array} share.ShareFrontend "List of share links" +// @Failure 500 {object} map[string]string "Internal server error" +// @Router /api/share/list [get] +func shareListHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + var ( + shares []share.Share + err error + ) + if d.User.Permissions.Admin { + shares, err = state.GetAllShares() + } else { + shares, err = state.GetSharesByUserID(d.User.ID) + } + if err != nil { + return http.StatusInternalServerError, err + } + host, scheme := shareURLParams(r) + return RenderJSON(w, r, state.PrepShareValuesForFrontend(d.User, r, host, scheme, shares)) +} + +// shareGetsHandler retrieves share links for a specific resource path. +// @Summary Get share links by path +// @Description Retrieves all share links associated with a specific resource path for the current user. +// @Tags Shares +// @Accept json +// @Produce json +// @Param path query string true "Resource path for which to retrieve share links" +// @Param source query string true "Source name for share links" +// @Success 200 {array} share.ShareFrontend "List of share links for the specified path" +// @Failure 500 {object} map[string]string "Internal server error" +// @Router /api/share [get] +func shareGetHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + path := r.URL.Query().Get("path") + sourceName := r.URL.Query().Get("source") + if path == "" { + return http.StatusBadRequest, fmt.Errorf("path is required") + } + cleanPath, err := utils.SanitizePath(path) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid path: %w", err) + } + path = cleanPath + sourceInfo, ok := settings.Config.Server.NameToSource[sourceName] // backend source is path + if !ok { + return http.StatusBadRequest, fmt.Errorf("invalid source name: %s", sourceName) + } + userscope, err := d.User.GetScopeForSourceName(sourceName) + if err != nil { + return http.StatusForbidden, err + } + scopePath := utils.JoinPathAsUnix(userscope, path) + idx := indexing.GetIndex(sourceInfo.Name) + if idx == nil { + return http.StatusBadRequest, fmt.Errorf("index not found for source: %s", sourceName) + } + + s, err := state.GetSharesInScope(scopePath, sourceInfo.Path, d.User.ID) + if err != nil { + return http.StatusInternalServerError, fmt.Errorf("error getting share info from server") + } + host, scheme := shareURLParams(r) + return RenderJSON(w, r, state.PrepSharesForFrontend(d.User, r, host, scheme, s...)) +} + +// shareDeleteHandler deletes a specific share link by its hash. +// @Summary Delete a share link +// @Description Deletes a share link specified by its hash. +// @Tags Shares +// @Accept json +// @Produce json +// @Param hash query string true "Hash of the share link to delete" +// @Success 200 "Share link deleted successfully" +// @Failure 400 {object} map[string]string "Bad request - missing or invalid hash" +// @Failure 500 {object} map[string]string "Internal server error" +// @Router /api/share [delete] +func shareDeleteHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + hash := r.URL.Query().Get("hash") + + if hash == "" { + return http.StatusBadRequest, nil + } + + thisShare, err := state.GetShare(hash) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("share not found") + } + if !thisShare.UserCanEdit(d.User) { + return http.StatusForbidden, fmt.Errorf("you are not allowed to delete this share") + } + + err = state.DeleteShare(hash) + if err != nil { + return ErrToStatus(err), err + } + + activity.RecordShareMutation(r, toActor(d), activitydb.EventShareDelete, hash, thisShare.SourceName, thisShare.Path, nil) + return ErrToStatus(err), err +} + +// sharePatchHandler updates a share link's path. +// @Summary Update share link path +// @Description Updates the path for a specific share link identified by hash +// @Tags Shares +// @Accept json +// @Produce json +// @Param body body object{hash=string,path=string} true "Hash and new path" +// @Success 200 {object} share.ShareFrontend "Updated share link" +// @Failure 400 {object} map[string]string "Bad request - missing or invalid parameters" +// @Failure 500 {object} map[string]string "Internal server error" +// @Router /api/share [patch] +func sharePatchHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + var body struct { + Hash string `json:"hash"` + Path string `json:"path"` + } + + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + return http.StatusBadRequest, fmt.Errorf("failed to decode body: %w", err) + } + defer r.Body.Close() + + if body.Hash == "" || body.Path == "" { + return http.StatusBadRequest, fmt.Errorf("hash and path are required") + } + + sanitizedPath, err := utils.SanitizePath(body.Path) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid path: %w", err) + } + body.Path = sanitizedPath + + // only allow users to update their own shares + thisShare, err := state.GetShare(body.Hash) + if err != nil { + return ErrToStatus(err), fmt.Errorf("failed to load share: %w", err) + } + if !thisShare.UserCanEdit(d.User) { + return http.StatusForbidden, fmt.Errorf("you are not allowed to update this share") + } + sourceName := thisShare.GetSourceName() + if sourceName == "" { + return http.StatusBadRequest, fmt.Errorf("source not available for share") + } + userscope, err := d.User.GetScopeForSourceName(sourceName) + if err != nil { + return http.StatusForbidden, err + } + storedPath := utils.JoinPathAsUnix(userscope, body.Path) + err = state.UpdateSharePath(body.Hash, storedPath) + if err != nil { + return http.StatusInternalServerError, err + } + + updatedShare, err := state.GetShare(body.Hash) + if err != nil { + return http.StatusInternalServerError, err + } + host, scheme := shareURLParams(r) + prepared := state.PrepShareForFrontend(d.User, r, host, scheme, updatedShare) + if prepared == nil { + return http.StatusInternalServerError, fmt.Errorf("could not prepare share response") + } + changes := []activitydb.FieldChange{{ + Field: "path", + From: thisShare.Path, + To: updatedShare.Path, + }} + activity.RecordShareMutation(r, toActor(d), activitydb.EventShareUpdate, body.Hash, updatedShare.SourceName, updatedShare.Path, changes) + return RenderJSON(w, r, prepared) +} + +// sharePostHandler creates a new share link. +// @Summary Create a share link +// @Description Creates a new share link with an optional expiration time and password protection. +// @Tags Shares +// @Accept json +// @Produce json +// @Param body body share.SharePostBody true "Share creation parameters" +// @Success 200 {object} share.ShareFrontend "Created share link" +// @Failure 400 {object} map[string]string "Bad request - failed to decode body" +// @Failure 500 {object} map[string]string "Internal server error" +// @Router /api/share [post] +func sharePostHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + var req share.SharePostBody + var err error + if r.Body != nil { + if err = json.NewDecoder(r.Body).Decode(&req); err != nil { + return http.StatusBadRequest, fmt.Errorf("failed to decode body: %w", err) + } + defer r.Body.Close() + } + + if req.Hash != "" { + _, err = state.GetShare(req.Hash) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid hash provided") + } + } + + var expire int64 + + if req.Expires != "" { + var num int + num, err = strconv.Atoi(req.Expires) + if err != nil { + return http.StatusInternalServerError, err + } + + var add time.Duration + switch req.Unit { + case "seconds": + add = time.Second * time.Duration(num) + case "minutes": + add = time.Minute * time.Duration(num) + case "days": + add = time.Hour * 24 * time.Duration(num) + default: + add = time.Hour * time.Duration(num) + } + + expire = time.Now().Add(add).Unix() + } + + hash, status, err2 := sharePasswordFromRequest(req.Password) + if err2 != nil { + return status, err2 + } + stringHash := "" + var token string + if len(hash) > 0 { + payloadBuffer := make([]byte, 24) + if _, err = rand.Read(payloadBuffer); err != nil { + return http.StatusInternalServerError, err + } + payload := base64.URLEncoding.EncodeToString(payloadBuffer) + + mac := hmac.New(sha256.New, []byte(settings.Config.Auth.Key)) + mac.Write([]byte(payload)) + signature := base64.URLEncoding.EncodeToString(mac.Sum(nil)) + + token = payload + "." + signature + stringHash = string(hash) + } + if req.Hash != "" { + beforeShare, getErr := state.GetShare(req.Hash) + if getErr != nil { + return http.StatusBadRequest, fmt.Errorf("share not found") + } + updateSourceName := beforeShare.GetSourceName() + if updateSourceName != "" { + ownerPerms, permErr := d.User.FilePermsForSourceName(updateSourceName) + if permErr != nil { + return http.StatusForbidden, permErr + } + share.ClampShareEditable(ownerPerms, &req.ShareEditable) + } + err = state.UpdateShare(req.Hash, func(link *share.Share) error { + shouldResetCounts := link.DownloadsLimit != req.DownloadsLimit || + link.PerUserDownloadLimit != req.PerUserDownloadLimit + + if err = applySharePasswordUpdate(link, req.Password, stringHash, token); err != nil { + return err + } + + preservedPath := link.Path + preservedSourcePath := link.SourcePath + preservedPinned := link.PinnedItems + preservedVersion := link.Version + + share.ApplyPostBodyUpdate(link, &req, expire) + + link.Path = preservedPath + link.SourcePath = preservedSourcePath + link.PinnedItems = preservedPinned + link.Version = preservedVersion + link.UserID = d.User.ID + if link.ShareType == "upload" && !req.AllowCreate { + link.AllowCreate = true + } + if shouldResetCounts { + link.ResetDownloadCounts() + } + return nil + }) + if err != nil { + return http.StatusInternalServerError, err + } + + updatedShare, err3 := state.GetShare(req.Hash) + if err3 != nil { + return http.StatusInternalServerError, err3 + } + changes := activity.ShareUpdateChanges(&beforeShare, &updatedShare) + host, scheme := shareURLParams(r) + prepared := state.PrepShareForFrontend(d.User, r, host, scheme, updatedShare) + if prepared == nil { + return http.StatusInternalServerError, fmt.Errorf("could not prepare share response") + } + if len(changes) > 0 { + activity.RecordShareMutation(r, toActor(d), activitydb.EventShareUpdate, req.Hash, updatedShare.SourceName, updatedShare.Path, changes) + } + return RenderJSON(w, r, prepared) + } + + source, ok := settings.Config.Server.NameToSource[req.SourceName] + if !ok { + return http.StatusForbidden, fmt.Errorf("source with name not found: %s", req.SourceName) + } + + if source.Config.Private { + return http.StatusForbidden, fmt.Errorf("the target source is private, sharing is not permitted") + } + + secureHash, err := generateShortUUID() + if err != nil { + return http.StatusInternalServerError, err + } + idx := indexing.GetIndex(source.Name) + if idx == nil { + return http.StatusForbidden, fmt.Errorf("source with name not found: %s", req.SourceName) + } + userscope, err := d.User.GetScopeForSourceName(source.Name) + if err != nil { + return http.StatusForbidden, err + } + providedPath := req.Path + + cleanPath, err := utils.SanitizePath(providedPath) + if err != nil { + return http.StatusBadRequest, err + } + + storedPath := utils.JoinPathAsUnix(userscope, cleanPath) + + if req.ShareType == "upload" && !req.AllowCreate { + req.AllowCreate = true + } + ownerPerms, permErr := d.User.FilePermsForSourceName(source.Name) + if permErr != nil { + return http.StatusForbidden, permErr + } + share.ClampShareEditable(ownerPerms, &req.ShareEditable) + shareLimits := req.ShareLimits + shareLimits.SourceName = source.Name + + s := &share.Share{ + ShareSettings: share.ShareSettings{ + FrontendShareInfo: req.FrontendShareInfo, + ShareLimits: shareLimits, + }, + ShareColumns: share.ShareColumns{ + Hash: secureHash, + Path: storedPath, + Expire: expire, + }, + SourcePath: source.Path, + UserID: d.User.ID, + PasswordHash: stringHash, + Token: token, + Version: 1, + } + s.DownloadURL = "" + s.ShareURL = "" + s.FaviconUrl = "" + s.BannerUrl = "" + s.FrontendShareInfo.SourceURL = "" + s.FrontendShareInfo.HasPassword = stringHash != "" + s.CanEditShare = false + s.SingleFileShare = false + + if err = state.CreateShare(s); err != nil { + return http.StatusInternalServerError, err + } + + created, err := state.GetShare(secureHash) + if err != nil { + return http.StatusInternalServerError, err + } + host, scheme := shareURLParams(r) + prepared := state.PrepShareForFrontend(d.User, r, host, scheme, created) + if prepared == nil { + return http.StatusInternalServerError, fmt.Errorf("could not prepare share response") + } + activity.RecordShareMutation(r, toActor(d), activitydb.EventShareCreate, s.Hash, s.SourceName, s.Path, nil) + return RenderJSON(w, r, prepared) +} + +// DirectDownloadResponse represents the response for direct download endpoint +type DirectDownloadResponse struct { + Status string `json:"status"` + Hash string `json:"hash"` + DownloadURL string `json:"url"` + ShareURL string `json:"shareUrl"` +} + +// shareDirectDownloadHandler creates a direct download link for files only. +// @Summary Create direct download link +// @Description Creates a direct download link for a specific file with configurable duration, download count, and speed limits. If a share already exists with matching parameters, the existing share will be reused. +// @Tags Shares +// @Accept json +// @Produce json +// @Param path query string true "File path to create download link for" +// @Param source query string true "Source name for the file" +// @Param duration query string false "Duration in minutes for link validity (default: 60)" +// @Param count query string false "Maximum number of downloads allowed (default: unlimited)" +// @Param speed query string false "Download speed limit in kbps (default: unlimited)" +// @Success 201 {object} DirectDownloadResponse "Direct download link created" +// @Failure 400 {object} map[string]string "Bad request - invalid parameters or path is not a file" +// @Failure 403 {object} map[string]string "Forbidden - access denied" +// @Failure 500 {object} map[string]string "Internal server error" +// @Router /api/share/direct [get] +func shareDirectDownloadHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + // Extract query parameters + path := r.URL.Query().Get("path") + source := r.URL.Query().Get("source") + duration := r.URL.Query().Get("duration") + downloadCountStr := r.URL.Query().Get("count") + downloadSpeedStr := r.URL.Query().Get("speed") + + // Validate required parameters + if path == "" || source == "" { + return http.StatusBadRequest, fmt.Errorf("path and source are required") + } + + cleanPath, err := utils.SanitizePath(path) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid path: %w", err) + } + path = cleanPath + + // Validate source exists + sourceInfo, ok := settings.Config.Server.NameToSource[source] + if !ok { + return http.StatusBadRequest, fmt.Errorf("invalid source name: %s", source) + } + + // Get user scope for this source + userscope, err := d.User.GetScopeForSourceName(source) + if err != nil { + return http.StatusForbidden, err + } + + // Validate the path exists and is a file (not a folder) + idx := indexing.GetIndex(source) + if idx == nil { + return http.StatusForbidden, fmt.Errorf("source with name not found: %s", source) + } + + metadata, exists := idx.GetReducedMetadata(path, false) + if !exists { + return http.StatusBadRequest, fmt.Errorf("path is either not a file or not found: %s", path) + } + + // Check if it's a file (not a directory) + if metadata.Type == "directory" { + return http.StatusBadRequest, fmt.Errorf("path must be a file, not a directory: %s", path) + } + + // Set default duration to 60 minutes if not provided + if duration == "" { + duration = "60" + } + + // Parse download count + var downloadCount int + if downloadCountStr != "" { + downloadCount, err = strconv.Atoi(downloadCountStr) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid downloadCount: %v", err) + } + } + + // Parse download speed (in bytes per second) + var downloadSpeed int + if downloadSpeedStr != "" { + downloadSpeed, err = strconv.Atoi(downloadSpeedStr) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid downloadSpeed: %v", err) + } + } + + // Calculate expiration time + durationNum, err := strconv.Atoi(duration) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid duration: %v", err) + } + expire := time.Now().Add(time.Minute * time.Duration(durationNum)).Unix() + + // Generate secure hash for the share + secureHash, err := generateShortUUID() + if err != nil { + return http.StatusInternalServerError, err + } + + // Create the scope path (file: no trailing slash; matches share cache normalization) + scopePath := utils.JoinPathAsUnix(userscope, path) + + // Check if an existing share already matches these parameters + existingShares, err := state.GetSharesInScope(scopePath, sourceInfo.Path, d.User.ID) + if err == nil && len(existingShares) > 0 { + for _, existing := range existingShares { + if existing.DownloadsLimit == downloadCount && + existing.MaxBandwidth == downloadSpeed && + existing.QuickDownload && + (existing.Expire == 0 || existing.Expire >= expire) { // Existing expires later or never + + response := DirectDownloadResponse{ + Status: "201", + Hash: existing.Hash, + DownloadURL: ShareURLFromRequest(r, existing.Hash, true, existing.Token), + ShareURL: ShareURLFromRequest(r, existing.Hash, false, existing.Token), + } + return RenderJSON(w, r, response) + } + } + } + + // No matching existing share found, create a new one + shareLink := &share.Share{ + ShareSettings: share.ShareSettings{ + FrontendShareInfo: share.FrontendShareInfo{ + QuickDownload: true, + }, + ShareLimits: share.ShareLimits{ + MaxBandwidth: downloadSpeed, + DownloadsLimit: downloadCount, + SourceName: sourceInfo.Name, + }, + }, + ShareColumns: share.ShareColumns{ + Hash: secureHash, + Path: scopePath, + Expire: expire, + }, + SourcePath: idx.Path, + UserID: d.User.ID, + Version: 1, + } + + if err = state.CreateShare(shareLink); err != nil { + return http.StatusInternalServerError, err + } + + snap, err := state.GetShare(secureHash) + if err != nil { + return http.StatusInternalServerError, err + } + response := DirectDownloadResponse{ + Status: "200", + Hash: secureHash, + DownloadURL: ShareURLFromRequest(r, secureHash, true, snap.Token), + ShareURL: ShareURLFromRequest(r, secureHash, false, snap.Token), + } + + activity.RecordShareMutation(r, toActor(d), activitydb.EventShareCreate, secureHash, snap.SourceName, snap.Path, nil) + return RenderJSON(w, r, response) +} + +// getShareImage serves banner or favicon files for shares as resizable previews +// @Summary Get share image (banner or favicon) as preview +// @Description Returns a resizable preview (large size) for the banner or favicon file of a share +// @Tags Shares +// @Produce image/jpeg +// @Param hash query string true "Share hash" +// @Param banner query bool false "Request banner file" +// @Param favicon query bool false "Request favicon file" +// @Success 200 {file} file "Preview image content (JPEG)" +// @Failure 400 {object} map[string]string "Invalid request" +// @Failure 403 {object} map[string]string "Permission denied" +// @Failure 404 {object} map[string]string "Asset not found" +// @Router /public/api/share/image [get] +func getShareImage(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + isBanner := r.URL.Query().Get("banner") == "true" + isFavicon := r.URL.Query().Get("favicon") == "true" + + if !isBanner && !isFavicon { + return http.StatusBadRequest, fmt.Errorf("either banner or favicon parameter must be true") + } + + userValue, err := state.UserForShareOwner(d.Share) + if err != nil { + return http.StatusNotFound, fmt.Errorf("user for share no longer exists") + } + shareCreatedByUser := &userValue + + sourceName, assetPath, err := d.Share.GetShareImagePartsHelper(isBanner) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid asset configuration: %v", err) + } + + fileInfo, err := files.FileInfoFaster(utils.FileOptions{ + Path: assetPath, + Source: sourceName, + Expand: false, + Content: false, + Metadata: false, + ShowHidden: false, + FollowSymlinks: true, + }, shareCreatedByUser) + if err != nil { + logger.Errorf("error accessing share asset: source=%v path=%v error=%v", sourceName, assetPath, err) + return http.StatusNotFound, fmt.Errorf("asset file not found or not accessible") + } + + if !strings.HasPrefix(fileInfo.Type, "image/") { + return http.StatusBadRequest, fmt.Errorf("invalid file type, must be image") + } + + d.FileInfo = *fileInfo + q := r.URL.Query() + if isBanner { + q.Set("size", "xlarge") + } else { + q.Set("size", "small") + } + r.URL.RawQuery = q.Encode() + + status, err := PreviewHelperFunc(w, r, d) + if err != nil { + logger.Errorf("error generating preview for share asset: source=%v path=%v error=%v", sourceName, assetPath, err) + return http.StatusNotFound, fmt.Errorf("preview not available for this asset") + } + + return status, err +} + +// shareInfoHandler retrieves share information by hash. +// @Summary Get share information by hash +// @Description Returns information about a share link based on its hash. This endpoint is publicly accessible and can be used with or without authentication. +// @Tags Shares +// @Accept json +// @Produce json +// @Param hash query string true "Hash of the share link" +// @Success 200 {object} share.Share "Share information" +// @Failure 404 {object} map[string]string "Share hash not found" +// @Router /public/api/share/info [get] +func shareInfoHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + hash := r.URL.Query().Get("hash") + shareInfo, err := state.GetShare(hash) + if err != nil { + return http.StatusNotFound, fmt.Errorf("share hash not found") + } + frontendShareInfo := shareInfo.FrontendShareInfo + frontendShareInfo.ShareURL = ShareURLFromRequest(r, hash, false, "") + frontendShareInfo.BannerUrl = shareInfo.BannerURL() + frontendShareInfo.FaviconUrl = shareInfo.FaviconURL() + filtered := make([]users.SidebarLink, 0, len(frontendShareInfo.SidebarLinks)) + for _, link := range frontendShareInfo.SidebarLinks { + if link.Category == "download" && frontendShareInfo.ShareType == "upload" { + continue + } + if link.Category == "download" && frontendShareInfo.DisableDownload { + continue + } + filtered = append(filtered, link) + } + frontendShareInfo.SidebarLinks = filtered + frontendShareInfo.SourceURL = shareInfo.SourceURL(d.User) + frontendShareInfo.CanEditShare = shareInfo.UserCanEdit(d.User) + frontendShareInfo.SingleFileShare = shareInfo.IsSingleFileShare() + frontendShareInfo.HasPassword = shareInfo.HasPassword() + if frontendShareInfo.SourceURL != "" { + frontendShareInfo.SidebarLinks = append(frontendShareInfo.SidebarLinks, users.SidebarLink{ + Name: "sourceLocation", + Category: "custom", + Target: frontendShareInfo.SourceURL, + }) + } + return RenderJSON(w, r, frontendShareInfo) +} + +type sharePinnedItemPatchRequest struct { + Path string `json:"path" validate:"required"` + Name string `json:"name" validate:"required"` +} + +func normalizeShareRelativeDir(shareRelDir string) (string, error) { + if shareRelDir == "" || shareRelDir == "/" { + return "/", nil + } + cleanDir, err := utils.SanitizePath(shareRelDir) + if err != nil { + return "", fmt.Errorf("invalid path: %w", err) + } + return utils.AddTrailingSlashIfNotExists(cleanDir), nil +} + +// sharePatchPinnedItemsHandler adds or removes a pinned item on a share. +// @Summary Add or remove a pinned item on a share +// @Description Patches one pinned item at a time on a share. Defaults to add; pass ?action=remove to unpin. +// @Tags Share +// @Accept json +// @Produce json +// @Param hash query string true "Share hash" +// @Param action query string false "add (default) or remove" +// @Param body body sharePinnedItemPatchRequest true "Pinned item" +// @Success 204 "No Content" +// @Failure 400 {object} map[string]string "Bad Request" +// @Failure 403 {object} map[string]string "Forbidden" +// @Failure 404 {object} map[string]string "Not Found" +// @Failure 500 {object} map[string]string "Internal Server Error" +// @Router /public/api/share/pinned-items [patch] +func sharePatchPinnedItemsHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + hash := r.URL.Query().Get("hash") + if hash == "" { + return http.StatusBadRequest, fmt.Errorf("hash is required") + } + + link, err := state.GetShare(hash) + if err != nil { + return http.StatusNotFound, fmt.Errorf("share hash not found") + } + + if d.User.Username == "anonymous" || !link.UserCanEdit(d.User) { + return http.StatusForbidden, fmt.Errorf("share pin editing is not allowed for this user") + } + + if link.ShareType == "upload" { + return http.StatusForbidden, fmt.Errorf("pinning is disabled for upload shares") + } + + var body sharePinnedItemPatchRequest + if err = json.NewDecoder(r.Body).Decode(&body); err != nil { + return http.StatusBadRequest, fmt.Errorf("failed to decode body: %w", err) + } + defer r.Body.Close() + + action := pinnedItemAction(r) + if action != "add" && action != "remove" { + return http.StatusBadRequest, fmt.Errorf("action must be add or remove") + } + + if body.Path == "" || body.Name == "" { + return http.StatusBadRequest, fmt.Errorf("path and name are required") + } + + shareRelDir, err := normalizeShareRelativeDir(body.Path) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid path: %s", body.Path) + } + + cleanName, err := utils.SanitizePath(body.Name) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid name: %s", body.Name) + } + body.Name = cleanName + + pinned := link.EnsurePinnedItems() + switch action { + case "add": + pinned.Add(shareRelDir, body.Name) + case "remove": + pinned.Remove(shareRelDir, body.Name) + } + + if err := state.UpdateShare(hash, func(existing *share.Share) error { + existing.PinnedItems = link.PinnedItems + return nil + }); err != nil { + return http.StatusInternalServerError, fmt.Errorf("failed to save share: %w", err) + } + + return http.StatusNoContent, nil +} + +func getSharePasswordHash(plaintextPassword string) (data []byte, statuscode int, err error) { + if plaintextPassword == "" { + return nil, 0, nil + } + + hash, err := bcrypt.GenerateFromPassword([]byte(plaintextPassword), bcrypt.DefaultCost) + if err != nil { + return nil, http.StatusInternalServerError, fmt.Errorf("failed to hash password") + } + + return hash, 0, nil +} + +// sharePasswordFromRequest hashes a password for new shares. Nil or empty means no password. +func sharePasswordFromRequest(password *string) ([]byte, int, error) { + if password == nil || *password == "" { + return nil, 0, nil + } + return getSharePasswordHash(*password) +} + +// applySharePasswordUpdate sets or preserves password credentials on share update. +// Nil password omits the field (keep existing); empty string clears; non-empty replaces. +func applySharePasswordUpdate(link *share.Share, password *string, hashedPassword, token string) error { + if password == nil { + return nil + } + if *password == "" { + link.PasswordHash = "" + link.Token = "" + return nil + } + link.PasswordHash = hashedPassword + link.Token = token + return nil +} + +func generateShortUUID() (string, error) { + // Generate 16 random bytes (128 bits of entropy) + bytes := make([]byte, 16) + _, err := rand.Read(bytes) + if err != nil { + return "", err + } + + // Encode the bytes to a URL-safe base64 string + uuid := base64.RawURLEncoding.EncodeToString(bytes) + + // Trim the length to 22 characters for a shorter ID + return uuid[:22], nil +} diff --git a/backend/internal/web/share_password_test.go b/backend/internal/web/share_password_test.go new file mode 100644 index 0000000000..756dc0b782 --- /dev/null +++ b/backend/internal/web/share_password_test.go @@ -0,0 +1,51 @@ +package web + +import ( + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/share" +) + +func TestApplySharePasswordUpdatePreservesWhenOmitted(t *testing.T) { + link := &share.Share{ + PasswordHash: "hashed", + Token: "tok", + } + + if err := applySharePasswordUpdate(link, nil, "", ""); err != nil { + t.Fatal(err) + } + if link.PasswordHash != "hashed" || link.Token != "tok" { + t.Fatalf("expected preserved secrets, got hash=%q token=%q", link.PasswordHash, link.Token) + } +} + +func TestApplySharePasswordUpdateClearsWhenEmpty(t *testing.T) { + link := &share.Share{ + PasswordHash: "hashed", + Token: "tok", + } + empty := "" + + if err := applySharePasswordUpdate(link, &empty, "", ""); err != nil { + t.Fatal(err) + } + if link.PasswordHash != "" || link.Token != "" { + t.Fatalf("expected cleared secrets, got hash=%q token=%q", link.PasswordHash, link.Token) + } +} + +func TestApplySharePasswordUpdateReplacesWhenProvided(t *testing.T) { + link := &share.Share{ + PasswordHash: "old", + Token: "oldtok", + } + next := "new-password" + + if err := applySharePasswordUpdate(link, &next, "newhash", "newtok"); err != nil { + t.Fatal(err) + } + if link.PasswordHash != "newhash" || link.Token != "newtok" { + t.Fatalf("expected replaced secrets, got hash=%q token=%q", link.PasswordHash, link.Token) + } +} diff --git a/backend/http/static.go b/backend/internal/web/static.go similarity index 73% rename from backend/http/static.go rename to backend/internal/web/static.go index a73aa88b32..2a1f5c20bb 100644 --- a/backend/http/static.go +++ b/backend/internal/web/static.go @@ -1,4 +1,4 @@ -package http +package web import ( "encoding/json" @@ -11,10 +11,10 @@ import ( "path/filepath" "strings" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/common/version" - "github.com/gtsteffaniak/filebrowser/backend/icons" + "github.com/gtsteffaniak/filebrowser/backend/internal/icons" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/version" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" ) var templateRenderer *TemplateRenderer @@ -56,13 +56,13 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont userSelectedTheme := "" versionString := "" commitSHAString := "" - externalLinks := config.Frontend.ExternalLinks + externalLinks := settings.Config.Frontend.ExternalLinks if settings.Env.IsPlaywright { versionString = version.Version commitSHAString = version.CommitSHA } - if d.user != nil && d.user.Username != "anonymous" { - theme, ok := config.Frontend.Styling.CustomThemeOptions[d.user.CustomTheme] + if d.User != nil && d.User.Username != "anonymous" { + theme, ok := settings.Config.Frontend.Styling.CustomThemeOptions[d.User.CustomTheme] if ok { userSelectedTheme = theme.CssRaw } @@ -81,9 +81,9 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont } defaultThemeColor := "#455a64" - staticURL := config.Server.BaseURL + "public/static" - description := config.Frontend.Description - title := config.Frontend.Name + staticURL := settings.Config.Http.BaseURL + "public/static" + description := settings.Config.Frontend.Description + title := settings.Config.Frontend.Name banner := staticURL + "/icons/pwa-icon-512.png" // largest generated PWA icon disableSidebar := false @@ -96,46 +96,36 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont favicon := staticURL + "/favicon" + faviconExt shareHash := "" data := make(map[string]interface{}) - disableNavButtons := config.Frontend.DisableNavButtons - if d.share != nil { - shareHash = d.share.Hash - } - if shareHash == "" { - shareHash = icons.ShareHashFromHTTPPath(r.URL.Path, config.Server.BaseURL) - } - if shareHash != "" && d.share == nil && store != nil { - if link, err := store.Share.GetByHash(shareHash); err == nil { - d.share = link - } - } - if d.share != nil { - if d.share.Favicon != "" { - if strings.HasPrefix(d.share.Favicon, "http") { - favicon = d.share.Favicon + disableNavButtons := settings.Config.Frontend.DisableNavButtons + if d.ShareValid && d.Share.Hash != "" { + if d.Share.Favicon != "" { + if strings.HasPrefix(d.Share.Favicon, "http") { + favicon = d.Share.Favicon } else { - favicon = staticURL + "/" + d.share.Favicon + favicon = staticURL + "/" + d.Share.Favicon } } - if d.share.Description != "" { - description = d.share.Description + if d.Share.Description != "" { + description = d.Share.Description } - if d.share.Title != "" { - title = d.share.Title + if d.Share.Title != "" { + title = d.Share.Title } - if d.share.ShareTheme != "" { - theme, ok := config.Frontend.Styling.CustomThemeOptions[d.share.ShareTheme] + if d.Share.ShareTheme != "" { + theme, ok := settings.Config.Frontend.Styling.CustomThemeOptions[d.Share.ShareTheme] if ok { userSelectedTheme = theme.CssRaw } } - if d.share.DisableSidebar { + if d.Share.DisableSidebar { disableSidebar = true } - banner = d.share.BannerURL() - shareFavicon := d.share.FaviconURL() + banner = d.Share.BannerURL() + shareFavicon := d.Share.FaviconURL() if shareFavicon != "" { favicon = shareFavicon } + shareHash = d.Share.Hash } // Set login icon URL loginIcon := staticURL + "/loginIcon" @@ -156,18 +146,7 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont } // Construct the full URL for the current request - var fullURL string - if config.Server.ExternalUrl != "" { - // ExternalUrl already includes schema (e.g., http://mydomain.com) - fullURL = strings.TrimSuffix(config.Server.ExternalUrl, "/") + r.URL.Path - } else { - // Build URL from request - scheme := "http" - if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" { - scheme = "https" - } - fullURL = fmt.Sprintf("%s://%s%s", scheme, r.Host, r.URL.Path) - } + fullURL := requestPageFullURL(r) pwaIcon192 := staticURL + "/icons/pwa-icon-192.png" pwaIcon256 := staticURL + "/icons/pwa-icon-256.png" @@ -175,13 +154,13 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont manifestURL := staticURL + "/site.webmanifest" if shareHash != "" { - pwaStartURL := config.Server.BaseURL + "public/share/" + shareHash + "/" + pwaStartURL := settings.Config.Http.BaseURL + "public/share/" + shareHash + "/" query := url.Values{} query.Set("start", pwaStartURL) - if title != config.Frontend.Name { + if title != settings.Config.Frontend.Name { query.Set("name", title) } - if description != config.Frontend.Description { + if description != settings.Config.Frontend.Description { query.Set("description", description) } manifestURL = staticURL + "/site.webmanifest?" + query.Encode() @@ -189,12 +168,12 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont data["htmlVars"] = map[string]interface{}{ "title": title, - "customCSS": template.CSS(config.Frontend.Styling.CustomCSSRaw), + "customCSS": template.CSS(settings.Config.Frontend.Styling.CustomCSSRaw), "userSelectedTheme": template.CSS(userSelectedTheme), - "lightBackground": config.Frontend.Styling.LightBackground, - "darkBackground": config.Frontend.Styling.DarkBackground, + "lightBackground": settings.Config.Frontend.Styling.LightBackground, + "darkBackground": settings.Config.Frontend.Styling.DarkBackground, "staticURL": staticURL, - "baseURL": config.Server.BaseURL, + "baseURL": settings.Config.Http.BaseURL, "favicon": favicon, "loginIcon": loginIcon, "color": defaultThemeColor, @@ -212,39 +191,38 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont } data["globalVars"] = map[string]interface{}{ - "name": config.Frontend.Name, - "minSearchLength": config.Server.MinSearchLength, - "disableExternal": config.Frontend.DisableDefaultLinks, - "darkMode": config.UserDefaults.UI.DarkMode, - "baseURL": config.Server.BaseURL, + "name": settings.Config.Frontend.Name, + "minSearchLength": settings.Config.Server.MinSearchLength, + "disableExternal": settings.Config.Frontend.DisableDefaultLinks, + "darkMode": settings.Config.UserDefaults.UI.DarkMode, + "baseURL": settings.Config.Http.BaseURL, "version": versionString, "commitSHA": commitSHAString, - "signup": config.Auth.Methods.PasswordAuth.Signup, - "noAuth": config.Auth.Methods.NoAuth, - "enableThumbs": !config.Server.DisablePreviews, + "signup": settings.Config.Auth.Methods.PasswordAuth.Signup, + "noAuth": settings.Config.Auth.Methods.NoAuth, + "enableThumbs": !settings.Config.Server.DisablePreviews, "externalLinks": externalLinks, - "externalUrl": strings.TrimSuffix(config.Server.ExternalUrl, "/"), - "onlyOfficeUrl": config.Integrations.OnlyOffice.Url, - "oidcAvailable": config.Auth.Methods.OidcAuth.Enabled, - "jwtAvailable": config.Auth.Methods.JwtAuth.Enabled, - "proxyAvailable": config.Auth.Methods.ProxyAuth.Enabled, - "passwordAvailable": config.Auth.Methods.PasswordAuth.Enabled, - "ldapAvailable": config.Auth.Methods.LdapAuth.Enabled, + "externalUrl": strings.TrimSuffix(settings.Config.Http.ExternalUrl, "/"), + "onlyOfficeUrl": settings.Config.Integrations.OnlyOffice.Url, + "oidcAvailable": settings.Config.Auth.Methods.OidcAuth.Enabled, + "jwtAvailable": settings.Config.Auth.Methods.JwtAuth.Enabled, + "proxyAvailable": settings.Config.Auth.Methods.ProxyAuth.Enabled, + "passwordAvailable": settings.Config.Auth.Methods.PasswordAuth.Enabled, + "ldapAvailable": settings.Config.Auth.Methods.LdapAuth.Enabled, "mediaAvailable": settings.MediaEnabled(), - "exiftoolAvailable": config.Integrations.Media.ExiftoolPath != "", "muPdfAvailable": settings.Env.MuPdfAvailable, "updateAvailable": utils.GetUpdateAvailableUrl(), "disableNavButtons": disableNavButtons, - "userSelectableThemes": config.Frontend.Styling.CustomThemeOptions, + "userSelectableThemes": settings.Config.Frontend.Styling.CustomThemeOptions, "enableHeicConversion": settings.CanConvertImage("heic"), - "eventBasedThemes": !config.Frontend.Styling.DisableEventBasedThemes, + "eventBasedThemes": !settings.Config.Frontend.Styling.DisableEventBasedThemes, "loginIcon": loginIcon, "disableSidebar": disableSidebar, "shareHash": shareHash, - "oidcLoginButtonText": config.Frontend.OIDCLoginButtonText, - "loginButtonText": config.Frontend.LoginButtonText, - "passkeyAvailable": config.Auth.Methods.PasskeyAuth.Enabled, - "passkeyLoginButtonText": config.Auth.Methods.PasskeyAuth.LoginButtonText, + "oidcLoginButtonText": settings.Config.Frontend.OIDCLoginButtonText, + "loginButtonText": settings.Config.Frontend.LoginButtonText, + "passkeyAvailable": settings.Config.Auth.Methods.PasskeyAuth.Enabled, + "passkeyLoginButtonText": settings.Config.Auth.Methods.PasskeyAuth.LoginButtonText, } // Marshal each variable to JSON strings for direct template usage @@ -301,7 +279,7 @@ func manifestHandler(w http.ResponseWriter, r *http.Request) { if startURL := r.URL.Query().Get("start"); startURL != "" { name := r.URL.Query().Get("name") description := r.URL.Query().Get("description") - if shareManifest, ok := icons.ManifestForShare(config.Server.BaseURL, startURL, name, description); ok { + if shareManifest, ok := icons.ManifestForShare(settings.Config.Http.BaseURL, startURL, name, description); ok { manifest = shareManifest } } diff --git a/backend/internal/web/stream.go b/backend/internal/web/stream.go new file mode 100644 index 0000000000..fc12481f5e --- /dev/null +++ b/backend/internal/web/stream.go @@ -0,0 +1,637 @@ +package web + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "mime" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/go-logger/logger" + "golang.org/x/time/rate" +) + +const ( + viewGrantTTL = 15 * time.Minute + maxStreamRangeBytes = 4 << 20 // 4 MiB +) + +var errStreamRangeInvalid = errors.New("invalid byte range") + +type ServeSingleFileOptions struct { + ForceInline bool + RangeOnly bool +} + +func viewGrantScope(d *Context, sourceName string) string { + if d.Share.Hash != "" { + return d.Share.Hash + } + return sourceName +} + +func shareSourceName(d *Context) (string, error) { + if d.Share.Hash == "" { + return "", fmt.Errorf("not a share context") + } + sourceInfo, ok := settings.Config.Server.SourceMap[d.Share.SourcePath] + if !ok { + return "", fmt.Errorf("source not found for share") + } + return sourceInfo.Name, nil +} + +func resolveViewGrantSource(d *Context, r *http.Request) (string, error) { + if d.Share.Hash != "" { + if strings.TrimSpace(r.URL.Query().Get("source")) != "" { + return "", fmt.Errorf("source must not be supplied for share view tokens") + } + return shareSourceName(d) + } + sourceName := strings.TrimSpace(r.URL.Query().Get("source")) + if sourceName == "" { + return "", fmt.Errorf("source is required") + } + return sourceName, nil +} + +func normalizeViewGrantPath(p string) string { + return filepath.ToSlash(strings.TrimSpace(p)) +} + +// shareRelativeDisplayName returns the client-facing filename for a path within a share. +// Single-file shares use file=/ at the share root; the real name comes from the share path. +func shareRelativeDisplayName(d *Context, shareRelativePath string) string { + name := filepath.Base(normalizeViewGrantPath(shareRelativePath)) + if name != "" && name != "." && name != "/" { + return name + } + if d != nil && d.Share.Hash != "" { + if shareName := filepath.Base(d.Share.Path); shareName != "" && shareName != "." && shareName != "/" { + return shareName + } + } + return name +} + +func mintViewGrant(d *Context, sourceName string) (string, error) { + internalSource := sourceName + if d.Share.Hash != "" { + var err error + internalSource, err = shareSourceName(d) + if err != nil { + return "", err + } + } else if internalSource == "" { + return "", fmt.Errorf("source is required") + } + if !canMintViewToken(d, internalSource) { + return "", fmt.Errorf("view permission required") + } + scope := viewGrantScope(d, internalSource) + if existing, ok := utils.ViewGrantIndex.Get(scope); ok { + if grant, ok := utils.ViewGrantsCache.Get(existing); ok { + if grant.Source == scope && time.Now().Unix() <= grant.ExpiresAt { + grant.ExpiresAt = time.Now().Add(viewGrantTTL).Unix() + utils.ViewGrantsCache.Set(existing, grant) + return existing, nil + } + } + } + token, err := utils.RandomHex(16) + if err != nil { + return "", err + } + grant := utils.ViewGrant{ + Source: scope, + ExpiresAt: time.Now().Add(viewGrantTTL).Unix(), + } + utils.ViewGrantsCache.Set(token, grant) + utils.ViewGrantIndex.Set(scope, token) + return token, nil +} + +func refreshViewGrant(d *Context, sourceName, existingToken string) (string, int64, error) { + internalSource := sourceName + if d.Share.Hash != "" { + var err error + internalSource, err = shareSourceName(d) + if err != nil { + return "", 0, err + } + } else if internalSource == "" { + return "", 0, fmt.Errorf("source is required") + } + scope := viewGrantScope(d, internalSource) + if existingToken != "" { + if grant, ok := utils.ViewGrantsCache.Get(existingToken); ok { + if grant.Source == scope && time.Now().Unix() <= grant.ExpiresAt { + grant.ExpiresAt = time.Now().Add(viewGrantTTL).Unix() + utils.ViewGrantsCache.Set(existingToken, grant) + utils.ViewGrantIndex.Set(scope, existingToken) + return existingToken, grant.ExpiresAt, nil + } + } + } + token, err := mintViewGrant(d, internalSource) + if err != nil { + return "", 0, err + } + grant, ok := utils.ViewGrantsCache.Get(token) + if !ok { + return "", 0, fmt.Errorf("view token missing after mint") + } + return token, grant.ExpiresAt, nil +} + +func requireWebSessionForViewToken(d *Context) error { + if d.Share.Hash != "" { + return nil + } + if d.Token == "" { + return fmt.Errorf("view tokens require a web session") + } + if _, ok := state.TokenNameForRawToken(d.User, d.Token); ok { + return fmt.Errorf("view tokens require a web session") + } + return nil +} + +type viewTokenResponse struct { + ViewToken string `json:"viewToken"` + ExpiresAt int64 `json:"expiresAt"` +} + +// viewTokenHandler mints or refreshes a source-scoped view grant. +// @Summary Refresh view token +// @Description Mints or extends a source-scoped view token for inline viewing. Authenticated routes require a web session (not a named API token). Public share routes accept anonymous users when the share allows it. +// @Tags Resources +// @Accept json +// @Produce json +// @Param source query string false "Source name or share hash" +// @Param hash query string false "Share hash (public share routes)" +// @Param viewToken query string false "Existing view token to extend" +// @Success 200 {object} viewTokenResponse +// @Failure 403 {object} map[string]string "Missing permission or API token used" +// @Router /api/resources/view-token [post] +// @Router /public/api/resources/view-token [post] +func viewTokenHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if err := requireWebSessionForViewToken(d); err != nil { + return http.StatusForbidden, err + } + if d.Share.ShareType == "upload" { + return http.StatusNotImplemented, fmt.Errorf("viewing is disabled for upload shares") + } + source, err := resolveViewGrantSource(d, r) + if err != nil { + return http.StatusBadRequest, err + } + existingToken := strings.TrimSpace(r.URL.Query().Get("viewToken")) + if existingToken == "" && r.Body != nil && r.ContentLength != 0 { + var body struct { + ViewToken string `json:"viewToken"` + } + if err = json.NewDecoder(r.Body).Decode(&body); err == nil { + existingToken = strings.TrimSpace(body.ViewToken) + } + } + token, expiresAt, err := refreshViewGrant(d, source, existingToken) + if err != nil { + if strings.Contains(err.Error(), "view permission") { + return http.StatusForbidden, err + } + return http.StatusInternalServerError, err + } + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(viewTokenResponse{ + ViewToken: token, + ExpiresAt: expiresAt, + }); err != nil { + return http.StatusInternalServerError, err + } + return http.StatusOK, nil +} + +func ValidateViewGrant(token string, d *Context, sourceName string) error { + grant, ok := utils.ViewGrantsCache.Get(token) + if !ok { + return fmt.Errorf("invalid or expired view token") + } + if time.Now().Unix() > grant.ExpiresAt { + utils.ViewGrantsCache.Delete(token) + return fmt.Errorf("view token expired") + } + if grant.Source != viewGrantScope(d, sourceName) { + return fmt.Errorf("view token scope mismatch") + } + internalSource := sourceName + if d.Share.Hash != "" { + var err error + internalSource, err = shareSourceName(d) + if err != nil { + return err + } + } + perms, err := effectiveFilePerms(d, internalSource) + if err != nil || !perms.View { + return fmt.Errorf("view permission required") + } + grant.ExpiresAt = time.Now().Add(viewGrantTTL).Unix() + utils.ViewGrantsCache.Set(token, grant) + return nil +} + +func canMintViewToken(d *Context, source string) bool { + if d.Share.Hash != "" && d.Share.ShareType == "upload" { + return false + } + perms, err := effectiveFilePerms(d, source) + return err == nil && perms.View +} + +func AttachViewToken(d *Context, source string, file *iteminfo.ExtendedFileInfo) { + if file == nil || file.Type == "directory" { + return + } + if !canMintViewToken(d, source) { + return + } + token, err := mintViewGrant(d, source) + if err != nil { + return + } + file.ViewToken = token +} + +func AttachViewTokensForDirectory(d *Context, source string, file *iteminfo.ExtendedFileInfo) { + if file == nil || file.Type != "directory" { + return + } + if !canMintViewToken(d, source) { + return + } + token, err := mintViewGrant(d, source) + if err != nil { + return + } + for i := range file.Files { + if file.Files[i].Type == "directory" { + continue + } + file.Files[i].ViewToken = token + } +} + +// streamUseRangeOnly reports whether the stream endpoint must serve capped partial +// content only (never a full-file 200 response). The stream endpoint is media-only. +func streamUseRangeOnly(_ *Context, _ string) bool { + return true +} + +func IsMediaStreamFile(displayFileName string) bool { + contentType := mime.TypeByExtension(strings.ToLower(filepathExt(displayFileName))) + return strings.HasPrefix(contentType, "video/") || strings.HasPrefix(contentType, "audio/") +} + +func filepathExt(name string) string { + if i := strings.LastIndex(name, "."); i >= 0 { + return name[i:] + } + return "" +} + +func parseStreamByteRange(rangeHeader string, size int64) (start, end int64, err error) { + if size <= 0 { + return 0, 0, errStreamRangeInvalid + } + if !strings.HasPrefix(rangeHeader, "bytes=") { + return 0, 0, errStreamRangeInvalid + } + spec := strings.TrimPrefix(rangeHeader, "bytes=") + if spec == "" || strings.Contains(spec, ",") { + return 0, 0, errStreamRangeInvalid + } + + dash := strings.Index(spec, "-") + if dash < 0 { + return 0, 0, errStreamRangeInvalid + } + startStr := strings.TrimSpace(spec[:dash]) + endStr := strings.TrimSpace(spec[dash+1:]) + + if startStr == "" { + // suffix range: bytes=-500 + suffix, parseErr := strconv.ParseInt(endStr, 10, 64) + if parseErr != nil || suffix <= 0 { + return 0, 0, errStreamRangeInvalid + } + if suffix > size { + suffix = size + } + start = size - suffix + end = size - 1 + return start, end, nil + } + + start, err = strconv.ParseInt(startStr, 10, 64) + if err != nil || start < 0 || start >= size { + return 0, 0, errStreamRangeInvalid + } + + if endStr == "" { + end = size - 1 + } else { + end, err = strconv.ParseInt(endStr, 10, 64) + if err != nil || end < start { + return 0, 0, errStreamRangeInvalid + } + if end >= size { + end = size - 1 + } + } + return start, end, nil +} + +func capStreamByteRange(start, end int64) (int64, int64) { + if end-start+1 <= maxStreamRangeBytes { + return start, end + } + return start, start + maxStreamRangeBytes - 1 +} + +func setStreamResponseHeaders(w http.ResponseWriter, r *http.Request, displayFileName string, size int64) { + SetContentDisposition(w, r, displayFileName, true) + w.Header().Set("Accept-Ranges", "bytes") + w.Header().Set("Cache-Control", "private") + w.Header().Set("X-Content-Type-Options", "nosniff") + if contentType := mime.TypeByExtension(strings.ToLower(filepathExt(displayFileName))); contentType != "" { + w.Header().Set("Content-Type", contentType) + } + w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) +} + +func serveStreamByteRange(w http.ResponseWriter, r *http.Request, reader io.ReadSeeker, displayFileName string, size int64) (int, error) { + if r.Method == http.MethodHead { + setStreamResponseHeaders(w, r, displayFileName, size) + return http.StatusOK, nil + } + + rangeHeader := r.Header.Get("Range") + if rangeHeader == "" { + setStreamResponseHeaders(w, r, displayFileName, size) + w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", size)) + return http.StatusRequestedRangeNotSatisfiable, fmt.Errorf("stream requires byte range requests") + } + + start, end, err := parseStreamByteRange(rangeHeader, size) + if err != nil { + setStreamResponseHeaders(w, r, displayFileName, size) + w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", size)) + return http.StatusRequestedRangeNotSatisfiable, fmt.Errorf("invalid byte range") + } + start, end = capStreamByteRange(start, end) + + chunkSize := end - start + 1 + if _, err := reader.Seek(start, io.SeekStart); err != nil { + return http.StatusInternalServerError, err + } + + setStreamResponseHeaders(w, r, displayFileName, chunkSize) + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, size)) + w.WriteHeader(http.StatusPartialContent) + + if _, err := io.CopyN(w, reader, chunkSize); err != nil && !errors.Is(err, io.EOF) { + return http.StatusPartialContent, err + } + return http.StatusPartialContent, nil +} + +// ServeSingleFile opens one file and streams it with Range support via http.ServeContent. +func ServeSingleFile(w http.ResponseWriter, r *http.Request, d *Context, source string, scopedFilePath string, displayFileName string, opts ServeSingleFileOptions) (int, error) { + idx := indexing.GetIndex(source) + if idx == nil { + return http.StatusInternalServerError, fmt.Errorf("source %s is not available", source) + } + permUser := d.User.Username + if d.Share.Hash != "" { + permUser = d.ShareUser.Username + } + + if !state.AccessPermitted(idx.Path, utils.IndexPathFromNormalized(scopedFilePath, true), permUser) { + logger.Debugf("user %s denied access to path %s", permUser, scopedFilePath) + return http.StatusForbidden, fmt.Errorf("access denied to path %s", scopedFilePath) + } + + realPath, _, err := idx.GetRealPath(scopedFilePath) + if err != nil { + return http.StatusInternalServerError, err + } + + isOnlyOffice := IsOnlyOfficeCompatibleFile(displayFileName) && settings.Config.Integrations.OnlyOffice.Url != "" + var documentId string + var logContext *OnlyOfficeLogContext + if isOnlyOffice { + documentId, _ = GetOnlyOfficeId(realPath) + if documentId != "" { + logContext = GetOnlyOfficeLogContext(documentId) + } + } + + fd, err := os.Open(realPath) + if err != nil { + if isOnlyOffice && logContext != nil { + SendOnlyOfficeLogEvent(logContext, "ERROR", "download", + fmt.Sprintf("OnlyOffice download failed - could not open file: %s - %v", scopedFilePath, err)) + } + return http.StatusInternalServerError, err + } + defer fd.Close() + + fileInfo, err := fd.Stat() + if err != nil { + if isOnlyOffice && logContext != nil { + SendOnlyOfficeLogEvent(logContext, "ERROR", "download", + fmt.Sprintf("OnlyOffice download failed - could not get file info: %s - %v", scopedFilePath, err)) + } + return http.StatusInternalServerError, err + } + if fileInfo.IsDir() { + return http.StatusForbidden, fmt.Errorf("cannot stream a directory") + } + + if isOnlyOffice && logContext != nil { + logger.Infof("OnlyOffice Server is downloading file: %s (documentId: %s)", scopedFilePath, documentId) + SendOnlyOfficeLogEvent(logContext, "INFO", "download", + fmt.Sprintf("OnlyOffice Server downloading file: %s", scopedFilePath)) + } + + SetContentDisposition(w, r, displayFileName, opts.ForceInline) + w.Header().Set("Cache-Control", "private") + w.Header().Set("X-Content-Type-Options", "nosniff") + + var reader io.ReadSeeker = fd + if d.Share.Hash != "" && d.Share.MaxBandwidth > 0 { + limit := rate.Limit(d.Share.MaxBandwidth * 1024) + burst := d.Share.MaxBandwidth * 1024 + reader = NewThrottledReadSeeker(fd, limit, burst, r.Context()) + } + + if opts.RangeOnly { + return serveStreamByteRange(w, r, reader, displayFileName, fileInfo.Size()) + } + + srw := &ResponseWriterWrapper{ResponseWriter: w} + http.ServeContent(srw, r, displayFileName, fileInfo.ModTime(), reader) + recordStatus := srw.StatusCode + if recordStatus == 0 { + recordStatus = http.StatusOK + } + return recordStatus, nil +} + +func streamFilesHandler(w http.ResponseWriter, r *http.Request, d *Context, source string, scopedFileList []string) (int, error) { + if len(scopedFileList) != 1 { + return http.StatusForbidden, fmt.Errorf("stream supports single file only") + } + scopedFilePath := scopedFileList[0] + displayName := filepath.Base(scopedFilePath) + return ServeSingleFile(w, r, d, source, scopedFilePath, displayName, ServeSingleFileOptions{ + ForceInline: true, + RangeOnly: streamUseRangeOnly(d, displayName), + }) +} + +// streamHandler serves inline audio/video content with a valid viewToken. +// @Summary Stream content of a single media file for inline viewing +// @Description Returns raw file bytes for inline UI viewing in capped byte ranges. Requires a viewToken minted by GET /resources. Media files must use Range requests; full-file GET responses are rejected. Never counts toward download limits or activity. +// @Tags Resources +// @Accept json +// @Param source query string true "Source name for the file (required)" +// @Param file query string true "File path" +// @Param viewToken query string true "Opaque view grant token from file metadata" +// @Success 200 {file} file "Raw file content (inline)" +// @Failure 403 {object} map[string]string "Missing or invalid view token" +// @Failure 404 {object} map[string]string "File not found" +// @Failure 500 {object} map[string]string "Internal server error" +// @Router /api/media/stream [get] +func streamHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if r.URL.Query().Get("archiveToken") != "" || r.URL.Query().Get("algo") != "" { + return http.StatusForbidden, fmt.Errorf("archives not supported on stream endpoint") + } + source := r.URL.Query().Get("source") + fileList := r.URL.Query()["file"] + if len(fileList) != 1 { + return http.StatusForbidden, fmt.Errorf("stream supports single file only") + } + token := r.URL.Query().Get("viewToken") + if token == "" { + return http.StatusForbidden, fmt.Errorf("view token required") + } + cleanPath, err := utils.SanitizePath(fileList[0]) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid file path: %v", err) + } + if err = ValidateViewGrant(token, d, source); err != nil { + return http.StatusForbidden, err + } + if !IsMediaStreamFile(filepath.Base(cleanPath)) { + return http.StatusForbidden, fmt.Errorf("stream endpoint supports audio and video only") + } + + userscope, err := d.User.GetScopeForSourceName(source) + if err != nil { + return http.StatusForbidden, err + } + scopedPath := utils.JoinPathAsUnix(userscope, cleanPath) + return streamFilesHandler(w, r, d, source, []string{scopedPath}) +} + +// publicStreamHandler serves inline audio/video content from a public share with a valid viewToken. +// @Summary Stream a single media file from a public share for inline viewing +// @Description Returns raw file bytes for inline UI viewing in capped byte ranges on a share link. Requires viewToken from GET /public/api/resources. Media files must use Range requests. Does not count toward download limits. +// @Tags Resources +// @Accept json +// @Produce octet-stream +// @Param hash query string true "Share hash for authentication" +// @Param file query string true "File path within the share" +// @Param viewToken query string true "Opaque view grant token from share file metadata" +// @Success 200 {file} file "Raw file content (inline)" +// @Failure 403 {object} map[string]string "Missing or invalid view token" +// @Failure 404 {object} map[string]string "Share or file not found" +// @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) { + if d.Share.ShareType == "upload" { + return http.StatusNotImplemented, fmt.Errorf("streaming is disabled for upload shares") + } + if r.URL.Query().Get("archiveToken") != "" || r.URL.Query().Get("algo") != "" { + return http.StatusForbidden, fmt.Errorf("archives not supported on stream endpoint") + } + files := r.URL.Query()["file"] + if len(files) != 1 { + return http.StatusForbidden, fmt.Errorf("stream supports single file only") + } + token := r.URL.Query().Get("viewToken") + if token == "" { + return http.StatusForbidden, fmt.Errorf("view token required") + } + cleanFile, err := utils.SanitizePath(files[0]) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid file path: %v", err) + } + sourceInfo, ok := settings.Config.Server.SourceMap[d.Share.SourcePath] + if !ok { + return http.StatusInternalServerError, fmt.Errorf("source not found for share") + } + if err = ValidateViewGrant(token, d, ""); err != nil { + return http.StatusForbidden, err + } + if !IsMediaStreamFile(shareRelativeDisplayName(d, cleanFile)) { + return http.StatusForbidden, fmt.Errorf("stream endpoint supports audio and video only") + } + scopedPath := utils.JoinPathAsUnix(d.Share.Path, cleanFile) + status, err := streamFilesHandler(w, r, d, sourceInfo.Name, []string{scopedPath}) + if err != nil { + if status == http.StatusForbidden { + return http.StatusForbidden, fmt.Errorf("access denied") + } + return status, fmt.Errorf("error streaming file") + } + return status, nil +} + +// ResolveDisplayFileList returns client-facing paths for activity logging. +func ResolveDisplayFileList(d *Context, source string, fileList []string) []string { + if d.Share.Hash != "" { + display := make([]string, 0, len(fileList)) + sharePrefix := strings.TrimSuffix(d.Share.Path, "/") + for _, p := range fileList { + p = strings.TrimPrefix(p, sharePrefix) + p = strings.TrimPrefix(p, "/") + display = append(display, p) + } + return display + } + userscope, err := d.User.GetScopeForSourceName(source) + if err != nil { + return append([]string(nil), fileList...) + } + display := make([]string, 0, len(fileList)) + for _, p := range fileList { + rel := strings.TrimPrefix(p, userscope) + rel = strings.TrimPrefix(rel, "/") + display = append(display, rel) + } + return display +} diff --git a/backend/internal/web/stream_test.go b/backend/internal/web/stream_test.go new file mode 100644 index 0000000000..071c59b430 --- /dev/null +++ b/backend/internal/web/stream_test.go @@ -0,0 +1,803 @@ +package web + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" + "time" + + "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/filebrowser/backend/pkg/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +var streamTestResolverMu sync.Mutex + +func initStreamTestSources(t *testing.T) { + t.Helper() + streamTestResolverMu.Lock() + t.Cleanup(func() { streamTestResolverMu.Unlock() }) + users.SetSourceNameResolver(func(name string) (string, error) { + switch name { + case "default", "Downloads", "srv": + return "/" + name, nil + default: + return "", fmt.Errorf("unknown source %q", name) + } + }) + users.SetSourceConfig(&users.SourceConfigProvider{ + GetSourceByPath: func(path string) (users.SourceInfo, bool) { + switch path { + case "/default", "/Downloads", "/srv": + return users.SourceInfo{Path: path, Name: path[1:]}, true + default: + return users.SourceInfo{}, false + } + }, + GetSourceByName: func(name string) (users.SourceInfo, bool) { + switch name { + case "default", "Downloads", "srv": + return users.SourceInfo{Path: "/" + name, Name: name}, true + default: + return users.SourceInfo{}, false + } + }, + }) +} + +func testUserWithView(id uint64, sources ...string) *users.User { + scopes := make([]users.BackendScope, 0, len(sources)) + perms := map[string]users.SourceFilePermissions{} + for _, s := range sources { + sourcePath := "/" + s + sourcePerms := users.SourceFilePermissions{View: true, Download: true} + perms[sourcePath] = sourcePerms + scopes = append(scopes, users.BackendScope{ + Path: sourcePath, + Scope: "/", + Permissions: sourcePerms, + }) + } + return &users.User{ + ID: id, + FrontendUser: users.FrontendUser{ + Username: "alice", + }, + BackendScopes: scopes, + BackendSourcePermissions: perms, + Version: users.SourcePermissionsMigrationVersion, + } +} + +func TestMintAndValidateViewGrant(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{User: testUserWithView(42, "default")} + token, err := mintViewGrant(d, "default") + if err != nil { + t.Fatalf("mintViewGrant: %v", err) + } + if token == "" { + t.Fatal("expected non-empty token") + } + if err := ValidateViewGrant(token, d, "default"); err != nil { + t.Fatalf("ValidateViewGrant: %v", err) + } +} + +func TestValidateViewGrantWrongScope(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + settings.Config.Server.SourceMap = map[string]*settings.Source{ + "/default": {Path: "/default", Name: "default"}, + } + t.Cleanup(func() { settings.Config.Server.SourceMap = nil }) + d := &requestContext{ + User: testUserWithView(1, "default"), + Share: share.Share{ + ShareColumns: share.ShareColumns{Hash: "abc123"}, + SourcePath: "/default", + }, + } + token, err := mintViewGrant(d, "") + if err != nil { + t.Fatal(err) + } + plain := &requestContext{User: testUserWithView(2, "default")} + if err := ValidateViewGrant(token, plain, "default"); err == nil { + t.Fatal("expected scope mismatch error") + } +} + +func TestValidateViewGrantAnyPathInSource(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{User: testUserWithView(1, "default")} + token, err := mintViewGrant(d, "default") + if err != nil { + t.Fatal(err) + } + if err := ValidateViewGrant(token, d, "default"); err != nil { + t.Fatalf("source-scoped grant should validate regardless of requested file: %v", err) + } +} + +func TestMintViewGrantReusesToken(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{User: testUserWithView(1, "default")} + first, err := mintViewGrant(d, "default") + if err != nil { + t.Fatal(err) + } + second, err := mintViewGrant(d, "default") + if err != nil { + t.Fatal(err) + } + if first != second { + t.Fatalf("expected same view token, got %q and %q", first, second) + } +} + +func TestValidateViewGrantExpired(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + token, err := utils.RandomHex(16) + if err != nil { + t.Fatal(err) + } + utils.ViewGrantsCache.Set(token, utils.ViewGrant{ + Source: "default", + ExpiresAt: time.Now().Add(-time.Minute).Unix(), + }) + d := &requestContext{User: testUserWithView(1, "default")} + if err := ValidateViewGrant(token, d, "default"); err == nil { + t.Fatal("expected expired token error") + } +} + +func TestValidateViewGrantExtendsExpiry(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + token, err := utils.RandomHex(16) + if err != nil { + t.Fatal(err) + } + almostExpired := time.Now().Add(30 * time.Second).Unix() + utils.ViewGrantsCache.Set(token, utils.ViewGrant{ + Source: "default", + ExpiresAt: almostExpired, + }) + d := &requestContext{User: testUserWithView(1, "default")} + if err := ValidateViewGrant(token, d, "default"); err != nil { + t.Fatalf("ValidateViewGrant: %v", err) + } + grant, ok := utils.ViewGrantsCache.Get(token) + if !ok { + t.Fatal("grant missing from cache after validate") + } + if grant.ExpiresAt <= almostExpired { + t.Fatalf("ExpiresAt = %d, want extension beyond %d", grant.ExpiresAt, almostExpired) + } +} + +func TestValidateViewGrantShareBinding(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + settings.Config.Server.SourceMap = map[string]*settings.Source{ + "/srv": {Path: "/srv", Name: "srv"}, + } + t.Cleanup(func() { settings.Config.Server.SourceMap = nil }) + d := &requestContext{ + User: testUserWithView(1, "srv"), + Share: share.Share{ + ShareColumns: share.ShareColumns{Hash: "abc123"}, + SourcePath: "/srv", + }, + } + token, err := mintViewGrant(d, "") + if err != nil { + t.Fatal(err) + } + grant, ok := utils.ViewGrantsCache.Get(token) + if !ok || grant.Source != "abc123" { + t.Fatalf("expected grant scoped to share hash, got %+v ok=%v", grant, ok) + } + if err := ValidateViewGrant(token, d, ""); err != nil { + t.Fatalf("ValidateViewGrant: %v", err) + } + wrongShare := &requestContext{ + User: testUserWithView(1, "srv"), + Share: share.Share{ + ShareColumns: share.ShareColumns{Hash: "other"}, + SourcePath: "/srv", + }, + } + if err := ValidateViewGrant(token, wrongShare, ""); err == nil { + t.Fatal("expected share mismatch error") + } +} + +func TestAttachViewTokenForAllFileTypes(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{User: testUserWithView(7, "default")} + audio := &iteminfo.ExtendedFileInfo{ + FileInfo: iteminfo.FileInfo{ + ItemInfo: iteminfo.ItemInfo{Name: "song.mp3", Type: "audio/mpeg"}, + }, + } + AttachViewToken(d, "default", audio) + if audio.ViewToken == "" { + t.Fatal("expected view token on audio file") + } + doc := &iteminfo.ExtendedFileInfo{ + FileInfo: iteminfo.FileInfo{ + ItemInfo: iteminfo.ItemInfo{Name: "readme.txt", Type: "text/plain"}, + }, + } + AttachViewToken(d, "default", doc) + if doc.ViewToken == "" { + t.Fatal("expected view token on non-media file") + } +} + +func TestAttachViewTokensForDirectory(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{User: testUserWithView(7, "Downloads")} + file := &iteminfo.ExtendedFileInfo{ + FileInfo: iteminfo.FileInfo{ + ItemInfo: iteminfo.ItemInfo{Type: "directory"}, + Files: []iteminfo.ExtendedItemInfo{ + {ItemInfo: iteminfo.ItemInfo{Name: "song.mp3", Type: "audio/mpeg"}}, + {ItemInfo: iteminfo.ItemInfo{Name: "photo.jpg", Type: "image/jpeg"}}, + {ItemInfo: iteminfo.ItemInfo{Name: "nested", Type: "directory"}}, + }, + }, + } + AttachViewTokensForDirectory(d, "Downloads", file) + if file.Files[0].ViewToken == "" { + t.Fatal("expected view token on audio file") + } + if file.Files[1].ViewToken == "" { + t.Fatal("expected view token on image file") + } + if file.Files[0].ViewToken != file.Files[1].ViewToken { + t.Fatal("expected the same universal view token for directory siblings") + } + if file.Files[2].ViewToken != "" { + t.Fatal("did not expect token on directory child folder") + } + if err := ValidateViewGrant(file.Files[0].ViewToken, d, "Downloads"); err != nil { + t.Fatalf("validate audio grant: %v", err) + } + if err := ValidateViewGrant(file.Files[1].ViewToken, d, "Downloads"); err != nil { + t.Fatalf("validate image grant: %v", err) + } +} + +func TestAttachViewTokenDeniedWithoutViewPermission(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{ + User: &users.User{ + ID: 9, + BackendSourcePermissions: map[string]users.SourceFilePermissions{ + "/default": {View: false, Download: true}, + }, + Version: users.SourcePermissionsMigrationVersion, + }, + } + doc := &iteminfo.ExtendedFileInfo{ + FileInfo: iteminfo.FileInfo{ + ItemInfo: iteminfo.ItemInfo{Name: "readme.txt", Type: "text/plain"}, + }, + } + AttachViewToken(d, "default", doc) + if doc.ViewToken != "" { + t.Fatal("expected no view token without view permission") + } +} + +func TestStreamHandlerRejectsMissingToken(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{User: testUserWithView(1, "default")} + req := httptest.NewRequest(http.MethodGet, "/api/media/stream?source=default&file=/a.mp3", nil) + status, err := streamHandler(httptest.NewRecorder(), req, d) + if status != http.StatusForbidden || err == nil { + t.Fatalf("expected 403, got status=%d err=%v", status, err) + } +} + +func TestStreamHandlerRejectsNonMedia(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{User: testUserWithView(1, "default")} + token, err := mintViewGrant(d, "default") + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(http.MethodGet, "/api/media/stream?source=default&file=/doc.pdf&viewToken="+token, nil) + status, err := streamHandler(httptest.NewRecorder(), req, d) + if status != http.StatusForbidden || err == nil { + t.Fatalf("expected 403 for non-media, got status=%d err=%v", status, err) + } +} + +func TestShareRelativeDisplayName(t *testing.T) { + t.Parallel() + d := &requestContext{ + Share: share.Share{ + ShareColumns: share.ShareColumns{Hash: "abc", Path: "/users/alice/media/song.mp3"}, + }, + } + if got := shareRelativeDisplayName(d, "/"); got != "song.mp3" { + t.Fatalf("shareRelativeDisplayName(/) = %q, want song.mp3", got) + } + if got := shareRelativeDisplayName(d, "/nested/other.mp3"); got != "other.mp3" { + t.Fatalf("shareRelativeDisplayName(/nested/other.mp3) = %q, want other.mp3", got) + } +} + +func TestPublicStreamHandlerSingleFileShareRootPath(t *testing.T) { + // SourceMap is process-global; save/restore and avoid t.Parallel (see streamTestResolverMu). + initStreamTestSources(t) + prevSourceMap := settings.Config.Server.SourceMap + settings.Config.Server.SourceMap = map[string]*settings.Source{ + "/srv": {Path: "/srv", Name: "srv"}, + } + t.Cleanup(func() { settings.Config.Server.SourceMap = prevSourceMap }) + d := &requestContext{ + User: testUserWithView(1, "srv"), + Share: share.Share{ + ShareColumns: share.ShareColumns{ + Hash: "abc123", + Path: "/scope/media/song.mp3", + }, + SourcePath: "/srv", + ShareSettings: share.ShareSettings{ + FrontendShareInfo: share.FrontendShareInfo{ + DisableFileViewer: false, + }, + }, + }, + } + token, err := mintViewGrant(d, "") + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(http.MethodGet, "/public/api/media/stream?hash=abc123&file=/&viewToken="+token, nil) + _, err = publicStreamHandler(httptest.NewRecorder(), req, d) + if err != nil && strings.Contains(err.Error(), "stream endpoint supports audio and video only") { + t.Fatalf("single-file share root path rejected as non-media: %v", err) + } +} + +func TestViewHandlerRejectsMedia(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{User: testUserWithView(1, "default")} + token, err := mintViewGrant(d, "default") + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(http.MethodGet, "/api/resources/view?source=default&file=/clip.mp4&viewToken="+token, nil) + status, err := viewHandler(httptest.NewRecorder(), req, d) + if status != http.StatusForbidden || err == nil { + t.Fatalf("expected 403 for media on view endpoint, got status=%d err=%v", status, err) + } +} + +func TestViewHandlerRejectsMissingToken(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{User: testUserWithView(1, "default")} + req := httptest.NewRequest(http.MethodGet, "/api/resources/view?source=default&file=/a.txt", nil) + status, err := viewHandler(httptest.NewRecorder(), req, d) + if status != http.StatusForbidden || err == nil { + t.Fatalf("expected 403, got status=%d err=%v", status, err) + } +} + +func TestStreamHandlerRejectsMultiFile(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{User: testUserWithView(1, "default")} + req := httptest.NewRequest(http.MethodGet, "/api/media/stream?source=default&file=/a.mp3&file=/b.mp3&viewToken=tok", nil) + status, err := streamHandler(httptest.NewRecorder(), req, d) + if status != http.StatusForbidden || err == nil { + t.Fatalf("expected 403 for multi-file, got status=%d err=%v", status, err) + } +} + +func TestStreamHandlerRejectsArchiveParams(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{User: testUserWithView(1, "default")} + req := httptest.NewRequest(http.MethodGet, "/api/media/stream?source=default&file=/a.mp3&viewToken=tok&algo=zip", nil) + status, err := streamHandler(httptest.NewRecorder(), req, d) + if status != http.StatusForbidden || err == nil { + t.Fatalf("expected 403 for algo param, got status=%d err=%v", status, err) + } + req = httptest.NewRequest(http.MethodGet, "/api/media/stream?source=default&file=/a.mp3&viewToken=tok&archiveToken=abc", nil) + status, err = streamHandler(httptest.NewRecorder(), req, d) + if status != http.StatusForbidden || err == nil { + t.Fatalf("expected 403 for archiveToken param, got status=%d err=%v", status, err) + } +} + +func TestViewHandlerRejectsArchiveParams(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{User: testUserWithView(1, "default")} + req := httptest.NewRequest(http.MethodGet, "/api/resources/view?source=default&file=/a.txt&viewToken=tok&algo=zip", nil) + status, err := viewHandler(httptest.NewRecorder(), req, d) + if status != http.StatusForbidden || err == nil { + t.Fatalf("expected 403 for algo param, got status=%d err=%v", status, err) + } +} + +func TestParseStreamByteRange(t *testing.T) { + t.Parallel() + tests := []struct { + name string + header string + size int64 + wantStart int64 + wantEnd int64 + wantErr bool + }{ + {name: "closed range", header: "bytes=0-99", size: 1000, wantStart: 0, wantEnd: 99}, + {name: "open ended", header: "bytes=10-", size: 100, wantStart: 10, wantEnd: 99}, + {name: "suffix", header: "bytes=-50", size: 100, wantStart: 50, wantEnd: 99}, + {name: "missing prefix", header: "0-99", size: 100, wantErr: true}, + {name: "multipart", header: "bytes=0-1,2-3", size: 100, wantErr: true}, + {name: "start past end", header: "bytes=100-", size: 100, wantErr: true}, + } + for _, tc := range tests { + tc := tc + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + start, end, err := parseStreamByteRange(tc.header, tc.size) + if tc.wantErr { + if err == nil { + t.Fatal("expected error") + } + return + } + if err != nil { + t.Fatalf("parseStreamByteRange: %v", err) + } + if start != tc.wantStart || end != tc.wantEnd { + t.Fatalf("got %d-%d, want %d-%d", start, end, tc.wantStart, tc.wantEnd) + } + }) + } +} + +func TestCapStreamByteRange(t *testing.T) { + t.Parallel() + start, end := capStreamByteRange(0, maxStreamRangeBytes) + if end-start+1 != maxStreamRangeBytes { + t.Fatalf("expected capped range of %d bytes, got %d", maxStreamRangeBytes, end-start+1) + } + start, end = capStreamByteRange(100, 150) + if start != 100 || end != 150 { + t.Fatalf("unexpected cap for small range: %d-%d", start, end) + } +} + +func TestStreamUseRangeOnly(t *testing.T) { + t.Parallel() + mediaCtx := &requestContext{User: &users.User{FrontendUser: users.FrontendUser{Permissions: users.Permissions{Download: true}}}} + if !streamUseRangeOnly(mediaCtx, "clip.mp4") { + t.Fatal("expected range-only for stream endpoint") + } + if !streamUseRangeOnly(mediaCtx, "notes.txt") { + t.Fatal("stream endpoint is always range-only") + } +} + +func TestServeStreamByteRangeRejectsFullGET(t *testing.T) { + t.Parallel() + body := strings.Repeat("a", 256) + file, err := os.CreateTemp("", "stream-range-*") + if err != nil { + t.Fatal(err) + } + defer os.Remove(file.Name()) + if _, err = file.WriteString(body); err != nil { + t.Fatal(err) + } + if _, err = file.Seek(0, io.SeekStart); err != nil { + t.Fatal(err) + } + + req := httptest.NewRequest(http.MethodGet, "/stream", nil) + rec := httptest.NewRecorder() + status, err := serveStreamByteRange(rec, req, file, "clip.mp4", int64(len(body))) + if status != http.StatusRequestedRangeNotSatisfiable || err == nil { + t.Fatalf("expected 416, got status=%d err=%v", status, err) + } +} + +func TestServeStreamByteRangeReturnsPartialContent(t *testing.T) { + t.Parallel() + body := strings.Repeat("b", 512) + file, err := os.CreateTemp("", "stream-range-*") + if err != nil { + t.Fatal(err) + } + defer os.Remove(file.Name()) + if _, err = file.WriteString(body); err != nil { + t.Fatal(err) + } + if _, err = file.Seek(0, io.SeekStart); err != nil { + t.Fatal(err) + } + + req := httptest.NewRequest(http.MethodGet, "/stream", nil) + req.Header.Set("Range", "bytes=0-99") + rec := httptest.NewRecorder() + status, err := serveStreamByteRange(rec, req, file, "clip.mp4", int64(len(body))) + if err != nil { + t.Fatalf("serveStreamByteRange: %v", err) + } + if status != http.StatusPartialContent { + t.Fatalf("expected 206, got %d", status) + } + if rec.Code != http.StatusPartialContent { + t.Fatalf("recorder code: %d", rec.Code) + } + if got := rec.Body.Len(); got != 100 { + t.Fatalf("expected 100 bytes body, got %d", got) + } + if !strings.HasPrefix(rec.Header().Get("Content-Range"), "bytes 0-99/512") { + t.Fatalf("unexpected Content-Range: %q", rec.Header().Get("Content-Range")) + } +} + +func TestServeStreamByteRangeCapsOpenEndedRange(t *testing.T) { + t.Parallel() + size := int(maxStreamRangeBytes + 1024) + body := strings.Repeat("c", size) + file, err := os.CreateTemp("", "stream-range-*") + if err != nil { + t.Fatal(err) + } + defer os.Remove(file.Name()) + if _, err = file.WriteString(body); err != nil { + t.Fatal(err) + } + if _, err = file.Seek(0, io.SeekStart); err != nil { + t.Fatal(err) + } + + req := httptest.NewRequest(http.MethodGet, "/stream", nil) + req.Header.Set("Range", "bytes=0-") + rec := httptest.NewRecorder() + status, err := serveStreamByteRange(rec, req, file, "song.mp3", int64(len(body))) + if err != nil { + t.Fatalf("serveStreamByteRange: %v", err) + } + if status != http.StatusPartialContent { + t.Fatalf("expected 206, got %d", status) + } + if rec.Body.Len() != int(maxStreamRangeBytes) { + t.Fatalf("expected capped body %d, got %d", maxStreamRangeBytes, rec.Body.Len()) + } +} + +func TestIsMediaStreamFile(t *testing.T) { + t.Parallel() + if !IsMediaStreamFile("movie.mp4") || !IsMediaStreamFile("track.flac") { + t.Fatal("expected media extensions to match") + } + if IsMediaStreamFile("readme.txt") { + t.Fatal("did not expect text file to match") + } +} + +func TestViewTokenHandlerMintsUniversalGrant(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{ + User: testUserWithView(1, "default"), + Token: "session-jwt-not-in-tokens", + } + req := httptest.NewRequest(http.MethodPost, "/api/resources/view-token?source=default", nil) + rec := httptest.NewRecorder() + status, err := viewTokenHandler(rec, req, d) + if err != nil || status != http.StatusOK { + t.Fatalf("viewTokenHandler: status=%d err=%v", status, err) + } + var resp viewTokenResponse + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if resp.ViewToken == "" || resp.ExpiresAt == 0 { + t.Fatalf("unexpected response: %+v", resp) + } + if err := ValidateViewGrant(resp.ViewToken, d, "default"); err != nil { + t.Fatalf("ValidateViewGrant: %v", err) + } +} + +func TestViewTokenHandlerMintsOnShareWithoutWebSession(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + settings.Config.Server.SourceMap = map[string]*settings.Source{ + "/srv": {Path: "/srv", Name: "srv"}, + } + t.Cleanup(func() { settings.Config.Server.SourceMap = nil }) + d := &requestContext{ + User: &users.User{ + FrontendUser: users.FrontendUser{Username: "anonymous"}, + }, + Share: share.Share{ + ShareColumns: share.ShareColumns{Hash: "abc123"}, + SourcePath: "/srv", + }, + } + req := httptest.NewRequest(http.MethodPost, "/public/api/resources/view-token?hash=abc123", nil) + rec := httptest.NewRecorder() + status, err := viewTokenHandler(rec, req, d) + if err != nil || status != http.StatusOK { + t.Fatalf("viewTokenHandler: status=%d err=%v", status, err) + } + var resp viewTokenResponse + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if resp.ViewToken == "" { + t.Fatal("expected view token on share route") + } + if err := ValidateViewGrant(resp.ViewToken, d, ""); err != nil { + t.Fatalf("ValidateViewGrant: %v", err) + } + grant, ok := utils.ViewGrantsCache.Get(resp.ViewToken) + if !ok || grant.Source != "abc123" { + t.Fatalf("expected share hash scope, got %+v ok=%v", grant, ok) + } +} + +func TestViewTokenHandlerRejectsUploadShare(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + settings.Config.Server.SourceMap = map[string]*settings.Source{ + "/srv": {Path: "/srv", Name: "srv"}, + } + t.Cleanup(func() { settings.Config.Server.SourceMap = nil }) + d := &requestContext{ + User: &users.User{ + FrontendUser: users.FrontendUser{Username: "anonymous"}, + }, + Share: share.Share{ + ShareSettings: share.ShareSettings{ + FrontendShareInfo: share.FrontendShareInfo{ + ShareType: "upload", + }, + }, + ShareColumns: share.ShareColumns{Hash: "upload-share"}, + SourcePath: "/srv", + }, + } + req := httptest.NewRequest(http.MethodPost, "/public/api/resources/view-token?hash=upload-share", nil) + status, err := viewTokenHandler(httptest.NewRecorder(), req, d) + if status != http.StatusNotImplemented || err == nil { + t.Fatalf("expected 501 for upload share, got status=%d err=%v", status, err) + } +} + +func TestCanMintViewTokenRejectsUploadShare(t *testing.T) { + t.Parallel() + d := &requestContext{ + Share: share.Share{ + ShareSettings: share.ShareSettings{ + FrontendShareInfo: share.FrontendShareInfo{ + ShareType: "upload", + }, + }, + ShareColumns: share.ShareColumns{Hash: "upload-share"}, + SourcePath: "/srv", + }, + } + if canMintViewToken(d, "default") { + t.Fatal("expected canMintViewToken to reject upload share") + } + file := &iteminfo.ExtendedFileInfo{ + FileInfo: iteminfo.FileInfo{ + ItemInfo: iteminfo.ItemInfo{Name: "photo.jpg", Type: "image/jpeg"}, + }, + } + AttachViewToken(d, "default", file) + if file.ViewToken != "" { + t.Fatalf("expected no view token on upload share, got %q", file.ViewToken) + } +} + +func TestViewTokenHandlerRejectsSourceOnShare(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + settings.Config.Server.SourceMap = map[string]*settings.Source{ + "/srv": {Path: "/srv", Name: "srv"}, + } + t.Cleanup(func() { settings.Config.Server.SourceMap = nil }) + d := &requestContext{ + User: &users.User{ + FrontendUser: users.FrontendUser{Username: "anonymous"}, + }, + Share: share.Share{ + ShareColumns: share.ShareColumns{Hash: "abc123"}, + SourcePath: "/srv", + }, + } + req := httptest.NewRequest(http.MethodPost, "/public/api/resources/view-token?hash=abc123&source=srv", nil) + status, err := viewTokenHandler(httptest.NewRecorder(), req, d) + if status != http.StatusBadRequest || err == nil { + t.Fatalf("expected 400 when source supplied on share, got status=%d err=%v", status, err) + } +} + +func TestViewTokenHandlerRejectsNamedApiToken(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + user := testUserWithView(1, "default") + user.Tokens = map[string]users.AuthToken{} + users.StoreToken(user.Tokens, users.AuthToken{Name: "my-api-key", Token: "api-jwt-value"}) + d := &requestContext{ + User: user, + Token: "api-jwt-value", + } + req := httptest.NewRequest(http.MethodPost, "/api/resources/view-token?source=default", nil) + status, err := viewTokenHandler(httptest.NewRecorder(), req, d) + if status != http.StatusForbidden || err == nil { + t.Fatalf("expected 403 for API token, got status=%d err=%v", status, err) + } +} + +func TestViewTokenHandlerExtendsExistingToken(t *testing.T) { + t.Parallel() + initStreamTestSources(t) + d := &requestContext{ + User: testUserWithView(1, "default"), + Token: "session-jwt", + } + token, err := utils.RandomHex(16) + if err != nil { + t.Fatal(err) + } + almostExpired := time.Now().Add(30 * time.Second).Unix() + utils.ViewGrantsCache.Set(token, utils.ViewGrant{ + Source: viewGrantScope(d, "default"), + ExpiresAt: almostExpired, + }) + utils.ViewGrantIndex.Set(viewGrantScope(d, "default"), token) + req := httptest.NewRequest(http.MethodPost, "/api/resources/view-token?source=default&viewToken="+token, nil) + rec := httptest.NewRecorder() + status, err := viewTokenHandler(rec, req, d) + if err != nil || status != http.StatusOK { + t.Fatalf("viewTokenHandler: status=%d err=%v", status, err) + } + var resp viewTokenResponse + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if resp.ViewToken != token { + t.Fatalf("expected same token extended, got %q", resp.ViewToken) + } + grantAfter, _ := utils.ViewGrantsCache.Get(token) + if grantAfter.ExpiresAt <= almostExpired { + t.Fatalf("expected extended expiry, before=%d after=%d", almostExpired, grantAfter.ExpiresAt) + } +} diff --git a/backend/http/swagger.go b/backend/internal/web/swagger.go similarity index 68% rename from backend/http/swagger.go rename to backend/internal/web/swagger.go index 5b96aa101a..5058e14d27 100644 --- a/backend/http/swagger.go +++ b/backend/internal/web/swagger.go @@ -1,17 +1,19 @@ -package http +package web import ( "net/http" httpSwagger "github.com/swaggo/http-swagger" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + ) func swaggerHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !d.user.Permissions.Api { + if !d.User.Permissions.Api { return http.StatusForbidden, nil } httpSwagger.Handler( - httpSwagger.URL(config.Server.BaseURL+"swagger/doc.json"), + httpSwagger.URL(settings.Config.Http.BaseURL+"swagger/doc.json"), httpSwagger.DeepLinking(true), httpSwagger.DocExpansion("none"), httpSwagger.DomID("swagger-ui"), diff --git a/backend/http/totp.go b/backend/internal/web/totp.go similarity index 78% rename from backend/http/totp.go rename to backend/internal/web/totp.go index a714089323..7b8a87e3fb 100644 --- a/backend/http/totp.go +++ b/backend/internal/web/totp.go @@ -1,12 +1,13 @@ -package http +package web import ( "fmt" "net/http" "net/url" - "github.com/gtsteffaniak/filebrowser/backend/auth" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/auth" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" ) // generateOTPHandler handles the generation of a new TOTP secret and QR code. @@ -21,16 +22,16 @@ import ( // @Success 200 {object} map[string]string "OTP secret generated successfully." // @Failure 500 {object} map[string]string "Internal server error" // @Router /api/auth/otp/generate [post] -func generateOTPHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +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 := store.Users.Get(r.URL.Query().Get("username")) + user, getErr := state.GetUserByUsername(r.URL.Query().Get("username")) if getErr != nil { return http.StatusNotFound, fmt.Errorf("user not found: %w", getErr) } - url, err := auth.GenerateOtpForUser(user, store.Users) + url, err := auth.GenerateOtpForUser(&user) if err != nil { return http.StatusInternalServerError, fmt.Errorf("error generating OTP secret: %w", err) } @@ -38,7 +39,7 @@ func generateOTPHandler(w http.ResponseWriter, r *http.Request, d *requestContex "message": "OTP secret generated successfully.", "url": url, // The otpauth:// URL for QR code generation } - return renderJSON(w, r, response) + return RenderJSON(w, r, response) } // verifyOTPHandler handles the verification of a TOTP code. @@ -54,7 +55,7 @@ func generateOTPHandler(w http.ResponseWriter, r *http.Request, d *requestContex // @Success 200 {object} HttpResponse "OTP token is valid." // @Failure 401 {object} map[string]string "Unauthorized - invalid TOTP token" // @Router /api/auth/otp/verify [post] -func verifyOTPHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func verifyOTPHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { code := r.Header.Get("X-Secret") if code == "" { return http.StatusUnauthorized, fmt.Errorf("code is required") @@ -63,27 +64,30 @@ func verifyOTPHandler(w http.ResponseWriter, r *http.Request, d *requestContext) if err != nil { return http.StatusUnauthorized, err } - user, getErr := store.Users.Get(r.URL.Query().Get("username")) + user, getErr := state.GetUserByUsername(r.URL.Query().Get("username")) if getErr != nil { return http.StatusNotFound, fmt.Errorf("user not found: %w", getErr) } - err = auth.VerifyTotpCode(user, code, store.Users) + err = auth.VerifyTotpCode(&user, code) if err != nil { return http.StatusUnauthorized, fmt.Errorf("invalid OTP token") } + if err := state.UpdateUser(&user, "", "TOTPSecret", "TOTPNonce", "OtpEnabled"); err != nil { + return http.StatusInternalServerError, err + } response := HttpResponse{ Status: http.StatusOK, Message: "OTP token is valid.", } // On success, return a simple confirmation. - return renderJSON(w, r, response) + return RenderJSON(w, r, response) } -func checkPassword(r *http.Request, d *requestContext) error { +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 + if d.User.Permissions.Admin { + username = d.User.Username } // url decode providedPassword, err := url.QueryUnescape(providedPassword) @@ -93,7 +97,7 @@ func checkPassword(r *http.Request, d *requestContext) error { if providedPassword == "" { return fmt.Errorf("password is required") } - user, getErr := store.Users.Get(username) + user, getErr := state.GetUserByUsername(username) var passwordHash string if getErr != nil { passwordHash = utils.InvalidPasswordHash diff --git a/backend/internal/web/totp_test.go b/backend/internal/web/totp_test.go new file mode 100644 index 0000000000..5788e12977 --- /dev/null +++ b/backend/internal/web/totp_test.go @@ -0,0 +1,135 @@ +package web + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "testing" + "time" + + "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" + "github.com/pquerna/otp/totp" +) + +func otpRequest(username, password, code, path string) *http.Request { + req := httptest.NewRequest(http.MethodPost, path+"?username="+username, http.NoBody) + req.Header.Set("X-Password", password) + if code != "" { + req.Header.Set("X-Secret", code) + } + return req +} + +func TestVerifyOTP_CachedSecretTakesPrecedence(t *testing.T) { + setupTestEnv(t) + + const oldSecret = "SOMEOLDSECRET234" + user := &users.User{ + FrontendUser: users.FrontendUser{Username: "test"}, + } + if err := state.CreateUser(user, "testPass"); err != nil { + t.Fatalf("failed to create user: %v", err) + } + user.TOTPSecret = oldSecret + user.OtpEnabled = true + if err := state.UpdateUser(user, "", "TOTPSecret", "OtpEnabled"); err != nil { + t.Fatalf("failed to set TOTP on user: %v", err) + } + t.Cleanup(func() { auth.TotpCache.Delete(user.Username) }) + + d := &Context{User: user} + + rec := httptest.NewRecorder() + if _, err := generateOTPHandler(rec, otpRequest(user.Username, "testPass", "", "/api/auth/otp/generate"), d); err != nil { + t.Fatalf("generation failed: %v", err) + } + var resp map[string]string + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatalf("failed to decode response: %v", err) + } + u, err := url.Parse(resp["url"]) + if err != nil { + t.Fatalf("failed to parse url: %v", err) + } + newSecret := u.Query().Get("secret") + if newSecret == oldSecret { + t.Fatal("expected a fresh secret") + } + oldCode, err := totp.GenerateCode(oldSecret, time.Now()) + if err != nil { + t.Fatalf("failed to generate old code: %v", err) + } + if _, verifyErr := verifyOTPHandler(httptest.NewRecorder(), otpRequest(user.Username, "testPass", oldCode, "/api/auth/otp/verify"), d); verifyErr == nil { + t.Error("expected old secret to be rejected") + } + newCode, err := totp.GenerateCode(newSecret, time.Now()) + if err != nil { + t.Fatalf("failed to generate new code: %v", err) + } + if _, verifyErr := verifyOTPHandler(httptest.NewRecorder(), otpRequest(user.Username, "testPass", newCode, "/api/auth/otp/verify"), d); verifyErr != nil { + t.Fatalf("expected new secret to be accepted: %v", verifyErr) + } + updated, err := state.GetUserByUsername(user.Username) + if err != nil { + t.Fatalf("failed to reload user: %v", err) + } + if updated.TOTPSecret != newSecret { + t.Error("expected TOTPSecret to be updated to the new secret") + } + if _, found := auth.TotpCache.Get(user.Username); found { + t.Error("expected cache to be cleared after verification") + } +} + +func TestLogin_RequiresOTPWhenTOTPSecretSet(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 }) + + const secret = "SOMEOLDSECRET234" + user := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "test", + LoginMethod: users.LoginMethodPassword, + }, + } + if err := state.CreateUser(user, "testPass"); err != nil { + t.Fatalf("failed to create user: %v", err) + } + user.TOTPSecret = secret + user.OtpEnabled = true + if err := state.UpdateUser(user, "", "TOTPSecret", "TOTPNonce", "OtpEnabled", "LoginMethod"); err != nil { + t.Fatalf("failed to set TOTP on user: %v", err) + } + + handler := wrapHandler(loginHelper(loginHandler)) + + rec := httptest.NewRecorder() + handler(rec, otpRequest(user.Username, "testPass", "", "/api/auth/login")) + if rec.Code != http.StatusForbidden { + t.Fatalf("expected 403 without OTP, got %d body=%s", rec.Code, rec.Body.String()) + } + var errResp HttpResponse + if err := json.Unmarshal(rec.Body.Bytes(), &errResp); err != nil { + t.Fatalf("failed to decode error response: %v", err) + } + if errResp.Message != "OTP code is required for user" { + t.Fatalf("expected OTP required message, got %q", errResp.Message) + } + + code, err := totp.GenerateCode(secret, time.Now()) + if err != nil { + t.Fatalf("failed to generate TOTP code: %v", err) + } + rec2 := httptest.NewRecorder() + handler(rec2, otpRequest(user.Username, "testPass", code, "/api/auth/login")) + if rec2.Code != http.StatusOK { + t.Fatalf("expected 200 with valid OTP, got %d body=%s", rec2.Code, rec2.Body.String()) + } +} diff --git a/backend/internal/web/users.go b/backend/internal/web/users.go new file mode 100644 index 0000000000..9781101382 --- /dev/null +++ b/backend/internal/web/users.go @@ -0,0 +1,556 @@ +package web + +import ( + "encoding/json" + stderrors "errors" + "fmt" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/internal/activity" + "io" + "net/http" + "net/url" + "reflect" + "sort" + "strings" + + 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" + "github.com/gtsteffaniak/filebrowser/backend/internal/usersidebar" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/go-logger/logger" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + +) + +type UserRequest struct { + Which []string `json:"which"` + User users.User `json:"data"` +} + +// userGetHandler lists users or returns one user by username. Numeric user IDs are not accepted. +// @Summary List users or get one by username +// @Description Returns all users (admins) or only the current user; with ?username=self, the logged-in user; with ?username=login, that user if permitted. Query id= is not supported. +// @Tags Users +// @Accept json +// @Produce json +// @Param username query string false "Login name, or 'self' for the current session user" +// @Success 200 {object} users.FrontendUser "User details or list of users" +// @Failure 400 {object} map[string]string "Bad Request" +// @Failure 403 {object} map[string]string "Forbidden" +// @Failure 404 {object} map[string]string "Not Found" +// @Failure 500 {object} map[string]string "Internal Server Error" +// @Router /api/users [get] +func userGetHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + // since api self is used to validate a logged in user + w.Header().Add("X-Renew-Token", "false") + + if strings.TrimSpace(r.URL.Query().Get("id")) != "" { + return http.StatusBadRequest, fmt.Errorf("query parameter id is not supported; use username=self for the current user or username=") + } + + usernameParam := strings.TrimSpace(r.URL.Query().Get("username")) + if usernameParam == "self" { + u, err := state.GetUserByUsername(d.User.Username) + if err == errors.ErrNotExist { + return http.StatusNotFound, err + } + if err != nil { + return http.StatusInternalServerError, err + } + u = PrepForFrontend(u) + return RenderJSON(w, r, u.FrontendUser) + } + + if usernameParam != "" { + userValue, err := state.GetUserByUsername(usernameParam) + if err == errors.ErrNotExist { + return http.StatusNotFound, err + } + if err != nil { + return http.StatusInternalServerError, err + } + if !d.User.Permissions.Admin && userValue.Username != d.User.Username { + return http.StatusForbidden, nil + } + userValue = PrepForFrontend(userValue) + return RenderJSON(w, r, userValue.FrontendUser) + } + + userList, err := state.GetAllUsers() + if err != nil { + return http.StatusInternalServerError, err + } + + userListFE := make([]users.FrontendUser, 0, len(userList)) + for i := range userList { + u := userList[i] + u = PrepForFrontend(u) + userListFE = append(userListFE, u.FrontendUser) + } + + sort.Slice(userListFE, func(i, j int) bool { + return userListFE[i].Username < userListFE[j].Username + }) + + if !d.User.Permissions.Admin { + var selfOnly []users.FrontendUser + for _, fe := range userListFE { + if fe.Username == d.User.Username { + selfOnly = append(selfOnly, fe) + } + } + userListFE = selfOnly + } + return RenderJSON(w, r, userListFE) +} + +// userDeleteHandler deletes a user by username (query ?username=). +// @Summary Delete a user by username +// @Description Deletes a user identified by login name. +// @Tags Users +// @Accept json +// @Produce json +// @Param username query string true "Username" +// @Success 200 "User deleted successfully" +// @Failure 403 {object} map[string]string "Forbidden" +// @Failure 500 {object} map[string]string "Internal Server Error" +// @Router /api/users [delete] +func userDeleteHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + username := strings.TrimSpace(r.URL.Query().Get("username")) + if username == "" { + return http.StatusBadRequest, fmt.Errorf("username query parameter is required") + } + + uVal, err := state.GetUserByUsername(username) + if err == errors.ErrNotExist { + return http.StatusNotFound, err + } + if err != nil { + return http.StatusInternalServerError, err + } + givenUserId := uVal.ID + + if givenUserId == d.User.ID { + return http.StatusForbidden, fmt.Errorf("cannot delete your own user") + } + + if !d.User.Permissions.Admin { + return http.StatusForbidden, fmt.Errorf("cannot delete users without admin permissions") + } + + status, err := verifyActorPasswordForUserActions(r, d) + if err != nil { + return status, err + } + + // Delete the user + err = state.DeleteUser(givenUserId) + if err != nil { + return ErrToStatus(err), err + } + activity.RecordUserMutation(r, toActor(d), activitydb.EventUserDelete, &uVal, nil) + return http.StatusOK, nil +} + +// usersPostHandler creates a new user. +// @Summary Create a new user +// @Description Adds a new user to the system. When the authenticated actor uses password login, they must send their current password in the X-Password header. +// @Tags Users +// @Accept json +// @Produce json +// @Param X-Password header string false "Actor's current password (URL-encoded); required for password-login actors" +// @Param data body users.User true "User data to create a new user" +// @Success 201 {object} users.User "Created user" +// @Failure 400 {object} map[string]string "Bad Request" +// @Failure 401 {object} map[string]string "Unauthorized - invalid or missing actor password when required" +// @Failure 500 {object} map[string]string "Internal Server Error" +// @Router /api/users [post] +func usersPostHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if !d.User.Permissions.Admin { + return http.StatusForbidden, nil + } + // Read the JSON body + body, err := io.ReadAll(r.Body) + if err != nil { + return http.StatusInternalServerError, err + } + // Parse the JSON into the UserRequest struct + var req UserRequest + if err = json.Unmarshal(body, &req); err != nil { + return http.StatusBadRequest, err + } + r.Body.Close() + + if req.User.Username == "" { + return http.StatusBadRequest, errors.ErrEmptyUsername + } + + if len(req.Which) != 0 { + return http.StatusBadRequest, nil + } + + if req.User.Password == "" && req.User.LoginMethod == "password" { + return http.StatusBadRequest, errors.ErrEmptyPassword + } + + // Extract plaintext password before creating user + status, err := verifyActorPasswordForUserActions(r, d) + if err != nil { + return status, err + } + plaintextPassword := req.User.Password + err = state.CreateUser(&req.User, plaintextPassword) + if err != nil { + return http.StatusInternalServerError, err + } + if dirErr := files.MakeUserDirs(&req.User, true); dirErr != nil { + logger.Error(dirErr.Error()) + } + + activity.RecordUserMutation(r, toActor(d), activitydb.EventUserCreate, &req.User, nil) + w.Header().Set("Location", "/settings/users/"+url.PathEscape(req.User.Username)) + return http.StatusCreated, nil +} + +// nonAdminEditableFieldNameSet returns User.NonAdminEditable struct field names (e.g. "Locale", "Preview"). +func nonAdminEditableFieldNameSet() map[string]struct{} { + m := make(map[string]struct{}) + t := reflect.TypeOf(users.NonAdminEditable{}) + for i := 0; i < t.NumField(); i++ { + m[t.Field(i).Name] = struct{}{} + } + return m +} + +// frontendUserPatchableJSONFields lists JSON keys allowed in PATCH which (FrontendUser + password). +var frontendUserPatchableJSONFields = buildFrontendUserPatchableJSONFieldSet() + +func buildFrontendUserPatchableJSONFieldSet() map[string]struct{} { + out := make(map[string]struct{}) + collectStructJSONFieldTags(reflect.TypeOf(users.FrontendUser{}), out) + out["password"] = struct{}{} + return out +} + +func collectStructJSONFieldTags(t reflect.Type, out map[string]struct{}) { + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + if field.Anonymous && field.Type.Kind() == reflect.Struct { + collectStructJSONFieldTags(field.Type, out) + continue + } + tag := field.Tag.Get("json") + if tag == "" || tag == "-" { + continue + } + name := strings.Split(tag, ",")[0] + if name == "" { + continue + } + out[strings.ToLower(name)] = struct{}{} + } +} + +// validatePatchWhich requires at least one FrontendUser JSON field name in which. +func validatePatchWhich(which []string) error { + if len(which) == 0 { + return fmt.Errorf("which must list at least one JSON field name to update") + } + for _, w := range which { + w = strings.TrimSpace(w) + if w == "" { + return fmt.Errorf("which must not contain empty field names") + } + if strings.EqualFold(w, "all") { + return fmt.Errorf("invalid which field %q", w) + } + if strings.EqualFold(w, "password") { + continue + } + if _, ok := frontendUserPatchableJSONFields[strings.ToLower(w)]; !ok { + return fmt.Errorf("unknown or read-only user field %q", w) + } + } + return nil +} + +// userPutOnlyNonAdminEditableFields reports whether req.Which lists exclusively NonAdminEditable fields, +// excluding Password. +func userPutOnlyNonAdminEditableFields(which []string) bool { + if len(which) == 0 { + return false + } + allowed := nonAdminEditableFieldNameSet() + for _, w := range which { + f := utils.CapitalizeFirst(strings.TrimSpace(w)) + if f == "" { + return false + } + if strings.EqualFold(f, "Password") { + return false + } + if _, ok := allowed[f]; !ok { + return false + } + } + return true +} + +// verifyActorPasswordForUserPut requires URL-encoded X-Password when the authenticated actor uses +// password login. Callers should invoke this only when the update requires re-authentication. +func verifyActorPasswordForUserActions(r *http.Request, d *Context) (int, error) { + if d.User.LoginMethod != users.LoginMethodPassword { + return 0, nil + } + encoded := r.Header.Get("X-Password") + if encoded == "" { + return http.StatusUnauthorized, fmt.Errorf("X-Password header is required to confirm your password") + } + plain, err := url.QueryUnescape(encoded) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid password encoding") + } + if plain == "" { + return http.StatusUnauthorized, fmt.Errorf("X-Password header is required to confirm your password") + } + actor, err := state.GetUserByID(d.User.ID) + if err != nil { + return http.StatusInternalServerError, err + } + if err := utils.CheckPwd(plain, actor.Password); err != nil { + return http.StatusUnauthorized, fmt.Errorf("invalid password") + } + return 0, nil +} + +// userPatchHandler updates an existing user's details. +// @Summary Update a user's details +// @Description Updates the details of a user identified by ID. which must list the JSON field names to update. When the authenticated actor uses password login, they must send their current password in the X-Password header unless the update only touches NonAdminEditable profile fields (not password). Any admin-only field requires confirmation. +// @Tags Users +// @Accept json +// @Param id query string false "user ID to update" +// @Param id query string false "usename to update" +// @Param X-Password header string false "Actor's current password (URL-encoded); required for password-login actors when updating password or any field outside NonAdminEditable" +// @Param data body users.User true "User data to update" +// @Success 204 "No Content - User updated successfully" +// @Failure 400 {object} map[string]string "Bad Request" +// @Failure 401 {object} map[string]string "Unauthorized - invalid or missing actor password when required" +// @Failure 403 {object} map[string]string "Forbidden" +// @Failure 500 {object} map[string]string "Internal Server Error" +// @Router /api/users [patch] +func userPatchHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + body, err := io.ReadAll(r.Body) + if err != nil { + return http.StatusBadRequest, err + } + defer r.Body.Close() + + var req UserRequest + if err = json.Unmarshal(body, &req); err != nil { + return http.StatusBadRequest, err + } + if err = validatePatchWhich(req.Which); err != nil { + return http.StatusBadRequest, err + } + + targetUsername := strings.TrimSpace(r.URL.Query().Get("username")) + if targetUsername == "" { + targetUsername = strings.TrimSpace(req.User.Username) + } + if targetUsername == "" && settings.Config.Auth.Methods.NoAuth { + admin := settings.Config.Auth.AdminUsername + if admin == "" { + admin = "admin" + } + targetUsername = admin + } + if targetUsername == "" && d.User != nil && d.User.Username != "" && d.User.Username != "anonymous" { + targetUsername = d.User.Username + } + if targetUsername == "" { + return http.StatusBadRequest, fmt.Errorf("username is required (?username= or in request data)") + } + + if !d.User.Permissions.Admin && targetUsername != d.User.Username { + return http.StatusForbidden, nil + } + + uValue, err2 := state.GetUserByUsername(targetUsername) + if err2 == errors.ErrNotExist { + return http.StatusBadRequest, fmt.Errorf("user not found: %s", targetUsername) + } + if err2 != nil { + return http.StatusInternalServerError, err2 + } + req.User.ID = uValue.ID + req.User.Username = uValue.Username + if state.FieldListIncludes(req.Which, "otpEnabled") && !req.User.OtpEnabled { + req.User.TOTPSecret = "" + req.User.TOTPNonce = "" + } + + // Get the old user to check if permissions changed + var oldUser *users.User + userValue, err := state.GetUserByID(req.User.ID) + if err == nil { + oldUser = &userValue + } + if err != nil { + return http.StatusBadRequest, fmt.Errorf("failed to get user: %w", err) + } + + if d.User.LoginMethod == users.LoginMethodPassword && !userPutOnlyNonAdminEditableFields(req.Which) { + var status int + status, err = verifyActorPasswordForUserActions(r, d) + if err != nil { + return status, err + } + } + + if targetUsername == d.User.Username { + if enfErr := settings.ValidateSelfUserUpdateNotEnforced(req.Which, state.GetEnforcedUserDefaults(), d.User); enfErr != nil { + var locked settings.ErrEnforcedUserField + if stderrors.As(enfErr, &locked) { + return http.StatusForbidden, enfErr + } + return http.StatusBadRequest, enfErr + } + if scopeErr := settings.ValidateSelfUserUpdateScopesNotEnforced(req.Which, state.GetEnforcedSourcePermissions(), d.User); scopeErr != nil { + var locked settings.ErrEnforcedUserField + if stderrors.As(scopeErr, &locked) { + return http.StatusForbidden, scopeErr + } + return http.StatusBadRequest, scopeErr + } + } + + err = state.UpdateUser(&req.User, req.User.Password, req.Which...) + if err != nil { + var locked settings.ErrEnforcedUserField + var mismatch settings.ErrEnforcedUserValueMismatch + if stderrors.As(err, &locked) || stderrors.As(err, &mismatch) { + return http.StatusForbidden, err + } + return http.StatusBadRequest, err + } + + // Revoke all API keys if API permission was removed + if state.FieldListIncludes(req.Which, "permissions") && oldUser.Permissions.Api && !req.User.Permissions.Api { + users.EachNamedToken(oldUser.Tokens, func(_ string, tokenInfo users.AuthToken) { + if err := state.RevokeToken(tokenInfo.Token); err != nil { + logger.Errorf("Failed to revoke API key: %v", err) + } + if err := state.RemoveApiToken(tokenInfo.Token); err != nil { + logger.Errorf("Failed to remove api token: %v", err) + } + }) + } + + updatedUser, getErr := state.GetUserByID(req.User.ID) + if getErr != nil { + return http.StatusInternalServerError, getErr + } + changes := activity.UserUpdateChanges(oldUser, &updatedUser, req.Which, req.User.Password != "") + if len(changes) > 0 { + activity.RecordUserMutation(r, toActor(d), activitydb.EventUserUpdate, &updatedUser, changes) + } + return http.StatusNoContent, nil +} + +// PrepForFrontend fills response-only fields for GET handlers. FrontendScopes are derived from +// persisted BackendScopes (GetFrontendScopes); they are not read from SQL and must not be written back as-is. +func PrepForFrontend(u users.User) users.User { + u.FrontendScopes = u.GetFrontendScopes() + u.Permissions = users.GlobalPermissionsOnly(u.Permissions) + u.SourcePermissions = nil + u.SidebarLinks = usersidebar.FrontendLinks(u.SidebarLinks, u.ShowToolsInSidebar) + u.Password = "" + u.ApiKeys = nil + u.Tokens = nil + u.OtpEnabled = u.TOTPSecret != "" + u.TOTPSecret = "" + u.TOTPNonce = "" + u.PinnedItems = nil + u.Locale = NormalizeLocaleForFrontend(u.Locale) + for i := range u.PasskeyCredentials { + u.PasskeyCredentials[i].PublicKey = "" + u.PasskeyCredentials[i].AttestationType = "" + u.PasskeyCredentials[i].AttestationFormat = "" + u.PasskeyCredentials[i].Flags = users.WebAuthnCredentialFlags{} + u.PasskeyCredentials[i].SignCount = 0 + u.PasskeyCredentials[i].ClientDataJSON = "" + u.PasskeyCredentials[i].ClientDataHash = "" + u.PasskeyCredentials[i].AuthenticatorData = "" + u.PasskeyCredentials[i].PublicKeyAlg = 0 + u.PasskeyCredentials[i].AttestationObj = "" + } + return u +} + +// normalizeLocaleForFrontend converts various locale formats to camelCase (e.g. zhCN, ptBR). +func NormalizeLocaleForFrontend(locale string) string { + if locale == "" { + return locale + } + + lower := strings.ToLower(locale) + + specialCases := map[string]string{ + "cs": "cz", + "uk": "ua", + "zh-cn": "zhCN", + "zh_cn": "zhCN", + "zhcn": "zhCN", + "zh-tw": "zhTW", + "zh_tw": "zhTW", + "zhtw": "zhTW", + "pt-br": "ptBR", + "pt_br": "ptBR", + "ptbr": "ptBR", + "sv-se": "svSE", + "sv_se": "svSE", + "svse": "svSE", + "nl-be": "nlBE", + "nl_be": "nlBE", + "nlbe": "nlBE", + } + + if normalized, ok := specialCases[lower]; ok { + return normalized + } + + if len(locale) >= 4 { + knownCamelCase := map[string]bool{ + "zhCN": true, "zhTW": true, "ptBR": true, "svSE": true, "nlBE": true, + } + if knownCamelCase[locale] { + return locale + } + } + + parts := strings.FieldsFunc(lower, func(r rune) bool { + return r == '_' || r == '-' + }) + + if len(parts) == 2 { + first := parts[0] + second := parts[1] + if len(second) > 0 { + second = strings.ToUpper(second[:1]) + second[1:] + } + normalized := first + second + + knownCompound := map[string]string{ + "zhcn": "zhCN", "zhtw": "zhTW", "ptbr": "ptBR", + "svse": "svSE", "nlbe": "nlBE", + } + if normalizedVal, ok := knownCompound[normalized]; ok { + return normalizedVal + } + return normalized + } + + return lower +} diff --git a/backend/internal/web/users_patch_test.go b/backend/internal/web/users_patch_test.go new file mode 100644 index 0000000000..49d7448f6c --- /dev/null +++ b/backend/internal/web/users_patch_test.go @@ -0,0 +1,55 @@ +package web + +import "testing" + +func TestValidatePatchWhich(t *testing.T) { + t.Run("accepts frontend fields", func(t *testing.T) { + for _, which := range [][]string{ + {"scopes", "permissions"}, + {"locale"}, + {"loginMethod", "otpEnabled"}, + {"password"}, + } { + if err := validatePatchWhich(which); err != nil { + t.Fatalf("unexpected error for which=%v: %v", which, err) + } + } + }) + + t.Run("rejects empty", func(t *testing.T) { + if err := validatePatchWhich(nil); err == nil { + t.Fatal("expected error for nil which") + } + if err := validatePatchWhich([]string{}); err == nil { + t.Fatal("expected error for empty which") + } + }) + + t.Run("rejects invalid field names", func(t *testing.T) { + for _, which := range [][]string{{"all"}, {"All"}, {"scopes", "all"}} { + if err := validatePatchWhich(which); err == nil { + t.Fatalf("expected error for which=%v", which) + } + } + }) + + t.Run("rejects blank field names", func(t *testing.T) { + if err := validatePatchWhich([]string{"scopes", " "}); err == nil { + t.Fatal("expected error for blank field name") + } + }) + + t.Run("rejects unknown field names", func(t *testing.T) { + if err := validatePatchWhich([]string{"notARealField"}); err == nil { + t.Fatal("expected error for unknown field name") + } + }) + + t.Run("rejects backend user fields", func(t *testing.T) { + for _, field := range []string{"id", "tokens", "backendScopes", "version", "totpSecret", "pinnedItems"} { + if err := validatePatchWhich([]string{field}); err == nil { + t.Fatalf("expected error for backend field %q", field) + } + } + }) +} diff --git a/backend/internal/web/view.go b/backend/internal/web/view.go new file mode 100644 index 0000000000..925b83b426 --- /dev/null +++ b/backend/internal/web/view.go @@ -0,0 +1,119 @@ +package web + +import ( + "fmt" + "net/http" + "path/filepath" + + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + +) + +func viewFilesHandler(w http.ResponseWriter, r *http.Request, d *Context, source string, scopedFileList []string) (int, error) { + if len(scopedFileList) != 1 { + return http.StatusForbidden, fmt.Errorf("view supports single file only") + } + scopedFilePath := scopedFileList[0] + displayName := filepath.Base(scopedFilePath) + if IsMediaStreamFile(displayName) { + return http.StatusForbidden, fmt.Errorf("view endpoint does not support audio or video; use /media/stream") + } + return ServeSingleFile(w, r, d, source, scopedFilePath, displayName, ServeSingleFileOptions{ + ForceInline: true, + RangeOnly: false, + }) +} + +// viewHandler serves inline file content for UI viewing with a valid viewToken. +// @Summary View content of a single non-media file inline +// @Description Returns raw file bytes for inline UI viewing. Requires a viewToken minted by GET /resources. Never counts toward download limits or activity and does not require download permission. +// @Tags Resources +// @Accept json +// @Param source query string true "Source name for the file (required)" +// @Param file query string true "File path" +// @Param viewToken query string true "Opaque view grant token from file metadata" +// @Success 200 {file} file "Raw file content (inline)" +// @Failure 403 {object} map[string]string "Missing or invalid view token" +// @Failure 404 {object} map[string]string "File not found" +// @Failure 500 {object} map[string]string "Internal server error" +// @Router /api/resources/view [get] +func viewHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + if r.URL.Query().Get("archiveToken") != "" || r.URL.Query().Get("algo") != "" { + return http.StatusForbidden, fmt.Errorf("archives not supported on view endpoint") + } + source := r.URL.Query().Get("source") + fileList := r.URL.Query()["file"] + if len(fileList) != 1 { + return http.StatusForbidden, fmt.Errorf("view supports single file only") + } + token := r.URL.Query().Get("viewToken") + if token == "" { + return http.StatusForbidden, fmt.Errorf("view token required") + } + cleanPath, err := utils.SanitizePath(fileList[0]) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid file path: %v", err) + } + if err = ValidateViewGrant(token, d, source); err != nil { + return http.StatusForbidden, err + } + + userscope, err := d.User.GetScopeForSourceName(source) + if err != nil { + return http.StatusForbidden, err + } + scopedPath := utils.JoinPathAsUnix(userscope, cleanPath) + return viewFilesHandler(w, r, d, source, []string{scopedPath}) +} + +// publicViewHandler serves inline file content from a public share with a valid viewToken. +// @Summary View a single non-media file from a public share inline +// @Description Returns raw file bytes for inline UI viewing on a share link. Requires viewToken from GET /public/api/resources. Does not count toward download limits. +// @Tags Resources +// @Accept json +// @Produce octet-stream +// @Param hash query string true "Share hash for authentication" +// @Param file query string true "File path within the share" +// @Param viewToken query string true "Opaque view grant token from share file metadata" +// @Success 200 {file} file "Raw file content (inline)" +// @Failure 403 {object} map[string]string "Missing or invalid view token" +// @Failure 404 {object} map[string]string "Share or file not found" +// @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) { + if d.Share.ShareType == "upload" { + return http.StatusNotImplemented, fmt.Errorf("viewing is disabled for upload shares") + } + if r.URL.Query().Get("archiveToken") != "" || r.URL.Query().Get("algo") != "" { + return http.StatusForbidden, fmt.Errorf("archives not supported on view endpoint") + } + files := r.URL.Query()["file"] + if len(files) != 1 { + return http.StatusForbidden, fmt.Errorf("view supports single file only") + } + token := r.URL.Query().Get("viewToken") + if token == "" { + return http.StatusForbidden, fmt.Errorf("view token required") + } + cleanFile, err := utils.SanitizePath(files[0]) + if err != nil { + return http.StatusBadRequest, fmt.Errorf("invalid file path: %v", err) + } + sourceInfo, ok := settings.Config.Server.SourceMap[d.Share.SourcePath] + if !ok { + return http.StatusInternalServerError, fmt.Errorf("source not found for share") + } + if err = ValidateViewGrant(token, d, ""); err != nil { + return http.StatusForbidden, err + } + scopedPath := utils.JoinPathAsUnix(d.Share.Path, cleanFile) + status, err := viewFilesHandler(w, r, d, sourceInfo.Name, []string{scopedPath}) + if err != nil { + if status == http.StatusForbidden { + return http.StatusForbidden, fmt.Errorf("access denied") + } + return status, fmt.Errorf("error viewing file") + } + return status, nil +} diff --git a/backend/http/webauthn.go b/backend/internal/web/webauthn.go similarity index 72% rename from backend/http/webauthn.go rename to backend/internal/web/webauthn.go index b6c8dbb9dd..f8f7de5a93 100644 --- a/backend/http/webauthn.go +++ b/backend/internal/web/webauthn.go @@ -1,4 +1,4 @@ -package http +package web import ( "encoding/json" @@ -8,8 +8,11 @@ import ( "strings" - "github.com/gtsteffaniak/filebrowser/backend/auth" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" + "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/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/state" ) // @Summary Begin passkey MFA login @@ -22,14 +25,12 @@ import ( // @Success 200 {object} map[string]interface{} "Passkey assertion options" // @Failure 403 {object} map[string]string "Forbidden" // @Router /api/auth/webauthn/begin-login [post] -func beginPasskeyLoginHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func beginPasskeyLoginHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { if !auth.IsWebAuthnEnabled() { return http.StatusForbidden, errors.ErrPasskeyNotEnabled } - if err := validateRequestOrigin(r); err != nil { - return http.StatusForbidden, err - } + registerRequestOrigin(r) username := r.URL.Query().Get("username") password := r.Header.Get("X-Password") @@ -40,7 +41,7 @@ func beginPasskeyLoginHandler(w http.ResponseWriter, r *http.Request, d *request rpID := deriveRPID(r) svc := auth.GetWebAuthn() - sessionID, assertion, err := svc.BeginMFALogin(username, password, rpID, store.Users) + sessionID, assertion, err := svc.BeginMFALogin(username, password, rpID) if err != nil { if err == errors.ErrPasskeyNoCredential { return http.StatusForbidden, err @@ -67,14 +68,12 @@ func beginPasskeyLoginHandler(w http.ResponseWriter, r *http.Request, d *request // @Success 200 {string} string "JWT token" // @Failure 403 {object} map[string]string "Forbidden" // @Router /api/auth/webauthn/finish-login [post] -func finishPasskeyLoginHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func finishPasskeyLoginHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { if !auth.IsWebAuthnEnabled() { return http.StatusForbidden, errors.ErrPasskeyNotEnabled } - if err := validateRequestOrigin(r); err != nil { - return http.StatusForbidden, err - } + registerRequestOrigin(r) sessionID := r.URL.Query().Get("session_id") if sessionID == "" { @@ -82,13 +81,21 @@ func finishPasskeyLoginHandler(w http.ResponseWriter, r *http.Request, d *reques } svc := auth.GetWebAuthn() - user, err := svc.FinishMFALogin(sessionID, r, store.Users) + user, err := svc.FinishMFALogin(sessionID, r) if err != nil { return http.StatusForbidden, err } + if err = state.UpdateUser(user, "", "PasskeyCredentials"); err != nil { + return http.StatusInternalServerError, err + } - d.user = user - return printToken(w, r, d.user) + d.User = user + status, err := printToken(w, r, d.User) + if err != nil || status != 0 { + return status, err + } + activity.RecordLogin(r, d.User) + return 0, nil } // @Summary Begin passkey registration @@ -99,18 +106,16 @@ func finishPasskeyLoginHandler(w http.ResponseWriter, r *http.Request, d *reques // @Success 200 {object} map[string]interface{} "Passkey creation options" // @Failure 403 {object} map[string]string "Forbidden" // @Router /api/auth/webauthn/begin-register [post] -func beginPasskeyRegistrationHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func beginPasskeyRegistrationHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { if !auth.IsWebAuthnEnabled() { return http.StatusForbidden, errors.ErrPasskeyNotEnabled } - if err := validateRequestOrigin(r); err != nil { - return http.StatusForbidden, err - } + registerRequestOrigin(r) rpID := deriveRPID(r) svc := auth.GetWebAuthn() - sessionID, creation, err := svc.BeginRegistration(d.user, rpID) + sessionID, creation, err := svc.BeginRegistration(d.User, rpID) if err != nil { return http.StatusInternalServerError, err } @@ -135,14 +140,12 @@ func beginPasskeyRegistrationHandler(w http.ResponseWriter, r *http.Request, d * // @Success 200 {object} map[string]string "Success" // @Failure 403 {object} map[string]string "Forbidden" // @Router /api/auth/webauthn/finish-register [post] -func finishPasskeyRegistrationHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func finishPasskeyRegistrationHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { if !auth.IsWebAuthnEnabled() { return http.StatusForbidden, errors.ErrPasskeyNotEnabled } - if err := validateRequestOrigin(r); err != nil { - return http.StatusForbidden, err - } + registerRequestOrigin(r) sessionID := r.URL.Query().Get("session_id") credentialName := r.URL.Query().Get("name") @@ -154,14 +157,18 @@ func finishPasskeyRegistrationHandler(w http.ResponseWriter, r *http.Request, d } svc := auth.GetWebAuthn() - if err := svc.FinishRegistration(d.user, sessionID, credentialName, r); err != nil { + if err := svc.FinishRegistration(d.User, sessionID, credentialName, r); err != nil { return http.StatusForbidden, err } - if err := store.Users.Update(d.user, false, "PasskeyCredentials"); err != nil { + if err := state.UpdateUser(d.User, "", "PasskeyCredentials"); err != nil { return http.StatusInternalServerError, err } + activity.RecordAuth(r, d.User, activitydb.EventPasskeyRegister, activitydb.Details{ + PasskeyName: credentialName, + }) + w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(map[string]string{"status": "ok"}); err != nil { @@ -177,7 +184,7 @@ func finishPasskeyRegistrationHandler(w http.ResponseWriter, r *http.Request, d // @Success 200 {object} map[string]string "Success" // @Failure 403 {object} map[string]string "Forbidden" // @Router /api/auth/webauthn/{id} [delete] -func deletePasskeyCredentialHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { +func deletePasskeyCredentialHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { if !auth.IsWebAuthnEnabled() { return http.StatusForbidden, errors.ErrPasskeyNotEnabled } @@ -187,15 +194,27 @@ func deletePasskeyCredentialHandler(w http.ResponseWriter, r *http.Request, d *r return http.StatusBadRequest, nil } + passkeyName := credentialID + for _, cred := range d.User.PasskeyCredentials { + if cred.ID == credentialID { + passkeyName = cred.Name + break + } + } + svc := auth.GetWebAuthn() - if err := svc.DeleteCredential(d.user, credentialID); err != nil { + if err := svc.DeleteCredential(d.User, credentialID); err != nil { return http.StatusNotFound, err } - if err := store.Users.Update(d.user, false, "PasskeyCredentials"); err != nil { + if err := state.UpdateUser(d.User, "", "PasskeyCredentials"); err != nil { return http.StatusInternalServerError, err } + activity.RecordAuth(r, d.User, activitydb.EventPasskeyDelete, activitydb.Details{ + PasskeyName: passkeyName, + }) + w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(map[string]string{"status": "ok"}); err != nil { @@ -205,36 +224,24 @@ func deletePasskeyCredentialHandler(w http.ResponseWriter, r *http.Request, d *r } func deriveRPID(r *http.Request) string { - host := r.Header.Get("X-Forwarded-Host") - if host == "" { - host = r.Host - } + host := requestHost(r) if i := strings.LastIndex(host, ":"); i != -1 { host = host[:i] } return host } -// validateRequestOrigin validates that the request's origin is in the configured whitelist. -// Returns an error if the origin is not allowed. -func validateRequestOrigin(r *http.Request) error { - scheme := "http" - if r.TLS != nil { - scheme = "https" - } else if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" { - scheme = strings.ToLower(proto) - } - host := r.Header.Get("X-Forwarded-Host") - if host == "" { - host = r.Host - } - origin := fmt.Sprintf("%s://%s", scheme, host) - +func webAuthnRequestOrigin(r *http.Request) string { + return fmt.Sprintf("%s://%s", requestScheme(r), requestHost(r)) +} + +// registerRequestOrigin registers the request's origin and RP ID with the WebAuthn service. +func registerRequestOrigin(r *http.Request) { + origin := webAuthnRequestOrigin(r) + rpID := deriveRPID(r) svc := auth.GetWebAuthn() if svc != nil { - if !svc.ValidateOrigin(origin) { - return fmt.Errorf("origin %s is not in the configured whitelist", origin) - } + svc.EnsureOrigin(origin) + svc.EnsureRPID(rpID) } - return nil } diff --git a/backend/internal/web/webauthn_test.go b/backend/internal/web/webauthn_test.go new file mode 100644 index 0000000000..10a1e023a0 --- /dev/null +++ b/backend/internal/web/webauthn_test.go @@ -0,0 +1,64 @@ +package web + +import ( + "net/http/httptest" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func TestDeriveRPIDTrustProxyHeaders(t *testing.T) { + orig := settings.Config.Http.TrustProxyHeaders + t.Cleanup(func() { settings.Config.Http.TrustProxyHeaders = orig }) + + t.Run("trusted forwarded host", func(t *testing.T) { + settings.Config.Http.TrustProxyHeaders = true + req := httptest.NewRequest("GET", "http://127.0.0.1:8080/", nil) + req.Host = "127.0.0.1:8080" + req.Header.Set("X-Forwarded-Host", "files.example.com") + + if got := deriveRPID(req); got != "files.example.com" { + t.Fatalf("deriveRPID() = %q, want files.example.com", got) + } + }) + + t.Run("ignores untrusted forwarded host", func(t *testing.T) { + settings.Config.Http.TrustProxyHeaders = false + req := httptest.NewRequest("GET", "http://127.0.0.1:8080/", nil) + req.Host = "127.0.0.1:8080" + req.Header.Set("X-Forwarded-Host", "evil.example.com") + + if got := deriveRPID(req); got != "127.0.0.1" { + t.Fatalf("deriveRPID() = %q, want 127.0.0.1", got) + } + }) +} + +func TestWebAuthnRequestOriginTrustProxyHeaders(t *testing.T) { + orig := settings.Config.Http.TrustProxyHeaders + t.Cleanup(func() { settings.Config.Http.TrustProxyHeaders = orig }) + + t.Run("trusted forwarded host and proto", func(t *testing.T) { + settings.Config.Http.TrustProxyHeaders = true + req := httptest.NewRequest("GET", "http://127.0.0.1:8080/", nil) + req.Host = "127.0.0.1:8080" + req.Header.Set("X-Forwarded-Host", "files.example.com") + req.Header.Set("X-Forwarded-Proto", "https") + + if got := webAuthnRequestOrigin(req); got != "https://files.example.com" { + t.Fatalf("webAuthnRequestOrigin() = %q, want https://files.example.com", got) + } + }) + + t.Run("ignores untrusted forwarded headers", func(t *testing.T) { + settings.Config.Http.TrustProxyHeaders = false + req := httptest.NewRequest("GET", "http://127.0.0.1:8080/", nil) + req.Host = "127.0.0.1:8080" + req.Header.Set("X-Forwarded-Host", "evil.example.com") + req.Header.Set("X-Forwarded-Proto", "https") + + if got := webAuthnRequestOrigin(req); got != "http://127.0.0.1:8080" { + t.Fatalf("webAuthnRequestOrigin() = %q, want http://127.0.0.1:8080", got) + } + }) +} diff --git a/backend/http/webdav.go b/backend/internal/web/webdav.go similarity index 65% rename from backend/http/webdav.go rename to backend/internal/web/webdav.go index af283c43e8..0a3a84d419 100644 --- a/backend/http/webdav.go +++ b/backend/internal/web/webdav.go @@ -1,24 +1,31 @@ -package http +package web import ( "context" "errors" "fmt" "net/http" + "net/url" "os" + "path" + "path/filepath" + "strconv" "strings" "time" "github.com/gtsteffaniak/go-logger/logger" "golang.org/x/net/webdav" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - commonerrors "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/filebrowser/backend/indexing" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + commonerrors "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" ) // fileInfoWrapper wraps iteminfo.ItemInfo to implement os.FileInfo @@ -42,10 +49,11 @@ func (f *fileInfoWrapper) mode() os.FileMode { // filteredFileSystem wraps a webdav.FileSystem and filters directory listings using FileInfoFaster type filteredFileSystem struct { - fs webdav.FileSystem - source string - user *users.User - userScope string + fs webdav.FileSystem + source string + user *users.User + filePerms users.SourceFilePermissions + httpReq *http.Request // Cache FileInfoFaster results per path to avoid redundant calls within the same request fileInfoCache map[string]*iteminfo.ExtendedFileInfo } @@ -87,7 +95,7 @@ func (ffs *filteredFileSystem) getFileInfo(requestPath string, expand bool) (*it HideFileExt: ffs.user.HideFileExt, SkipExtendedAttrs: true, FollowSymlinks: true, - }, store.Access, ffs.user, store.Share) + }, ffs.user) if err != nil { return nil, err } @@ -135,7 +143,7 @@ func (ffs *filteredFileSystem) checkAccess(requestPath string) error { Path: requestPath, Source: ffs.source, ShowHidden: ffs.user.ShowHidden, - }, store.Access, ffs.user) + }, ffs.user) if err != nil { logger.Debugf("checkAccess: CheckPermissions denied for %s: %v", requestPath, err) return err @@ -199,9 +207,28 @@ func (ffs *filteredFileSystem) checkAccess(requestPath string) error { // filteredFile wraps a webdav.File and filters Readdir results based on FileInfoFaster type filteredFile struct { webdav.File - fs *filteredFileSystem - requestPath string // The request path (without user scope) - isDir bool // Whether this is a directory + fs *filteredFileSystem + requestPath string // The request path (without user scope) + isDir bool // Whether this is a directory + desiredMtime time.Time // client-requested mtime (with X-OC-Mtime header) +} + +// closes the file and if a client-requested mtime was captured for a new file, applies it after the write completes +func (ff *filteredFile) Close() error { + err := ff.File.Close() + if err != nil { + return err + } + if !ff.desiredMtime.IsZero() { + dir, ok := ff.fs.fs.(webdav.Dir) + if ok { + realPath := filepath.Join(string(dir), filepath.FromSlash(ff.requestPath)) + if chtimesErr := os.Chtimes(realPath, time.Now(), ff.desiredMtime); chtimesErr != nil { + logger.Errorf("failed to set mtime on %s: %v", realPath, chtimesErr) + } + } + } + return nil } func (ff *filteredFile) Readdir(count int) ([]os.FileInfo, error) { @@ -248,8 +275,12 @@ func (ff *filteredFile) Readdir(count int) ([]os.FileInfo, error) { return entries, nil } +func (ffs *filteredFileSystem) sourceFilePerms() users.SourceFilePermissions { + return ffs.filePerms +} + func (ffs *filteredFileSystem) Mkdir(ctx context.Context, name string, perm os.FileMode) error { - if !ffs.user.Permissions.Create { + if !ffs.sourceFilePerms().Create { return fmt.Errorf("create permission required") } @@ -259,7 +290,19 @@ func (ffs *filteredFileSystem) Mkdir(ctx context.Context, name string, perm os.F return err } - return ffs.fs.Mkdir(ctx, name, perm) + if err := ffs.fs.Mkdir(ctx, name, perm); err != nil { + return err + } + activity.RecordWebDAVUser(ffs.httpReq, ffs.user, activitydb.Entry{ + EventType: activitydb.EventUpload, + Source: ffs.source, + Path: name + "/", + Details: activitydb.Details{ + Source: ffs.source, + Path: name + "/", + }, + }) + return nil } func (ffs *filteredFileSystem) OpenFile(ctx context.Context, requestPath string, flag int, perm os.FileMode) (webdav.File, error) { @@ -268,7 +311,7 @@ func (ffs *filteredFileSystem) OpenFile(ctx context.Context, requestPath string, if isWrite { // Check user permissions first - if !ffs.user.Permissions.Create && !ffs.user.Permissions.Modify { + if !ffs.sourceFilePerms().Create && !ffs.sourceFilePerms().Modify { return nil, fmt.Errorf("write permission required") } @@ -290,18 +333,31 @@ func (ffs *filteredFileSystem) OpenFile(ctx context.Context, requestPath string, return nil, err } + // only new uploads carry mtime + var desiredMtime time.Time + if flag&os.O_CREATE != 0 && ffs.httpReq != nil { + if raw := ffs.httpReq.Header.Get("X-OC-Mtime"); raw != "" { + if seconds, parseErr := strconv.ParseFloat(raw, 64); parseErr == nil { + desiredMtime = time.Unix(int64(seconds), 0) + } else { + logger.Debugf("OpenFile: invalid X-OC-Mtime header %q for %s: %v", raw, requestPath, parseErr) + } + } + } + // Wrap the file to filter directory listings // name is the request path (without user scope) return &filteredFile{ - File: file, - fs: ffs, - requestPath: requestPath, - isDir: stat.IsDir(), + File: file, + fs: ffs, + requestPath: requestPath, + isDir: stat.IsDir(), + desiredMtime: desiredMtime, }, nil } func (ffs *filteredFileSystem) RemoveAll(ctx context.Context, requestPath string) error { - if !ffs.user.Permissions.Delete { + if !ffs.sourceFilePerms().Delete { return fmt.Errorf("delete permission required") } @@ -311,11 +367,23 @@ func (ffs *filteredFileSystem) RemoveAll(ctx context.Context, requestPath string return err } - return ffs.fs.RemoveAll(ctx, requestPath) + if err := ffs.fs.RemoveAll(ctx, requestPath); err != nil { + return err + } + activity.RecordWebDAVUser(ffs.httpReq, ffs.user, activitydb.Entry{ + EventType: activitydb.EventDelete, + Source: ffs.source, + Path: requestPath, + Details: activitydb.Details{ + Source: ffs.source, + Path: requestPath, + }, + }) + return nil } func (ffs *filteredFileSystem) Rename(ctx context.Context, oldPath, newPath string) error { - if !ffs.user.Permissions.Modify { + if !ffs.sourceFilePerms().Modify { return fmt.Errorf("modify permission required") } @@ -330,7 +398,21 @@ func (ffs *filteredFileSystem) Rename(ctx context.Context, oldPath, newPath stri return err } - return ffs.fs.Rename(ctx, oldPath, newPath) + if err := ffs.fs.Rename(ctx, oldPath, newPath); err != nil { + return err + } + activity.RecordWebDAVUser(ffs.httpReq, ffs.user, activitydb.Entry{ + EventType: activitydb.EventMove, + Source: ffs.source, + Path: oldPath, + TargetPath: newPath, + Details: activitydb.Details{ + Source: ffs.source, + Path: oldPath, + TargetPath: newPath, + }, + }) + return nil } func (ffs *filteredFileSystem) Stat(ctx context.Context, requestPath string) (os.FileInfo, error) { @@ -361,30 +443,26 @@ func (ffs *filteredFileSystem) Stat(ctx context.Context, requestPath string) (os } // webDAVHandler serves WebDAV requests. -func webDAVHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - if !d.user.Permissions.Download { - return http.StatusForbidden, fmt.Errorf("download permission required") +func webDAVHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) { + source := r.PathValue("source") + filePerms, err := effectiveFilePerms(d, source) + if err != nil { + return http.StatusForbidden, err } - if r.Method == "DELETE" && !d.user.Permissions.Delete { - return http.StatusForbidden, fmt.Errorf("delete permission required") - } - isWrite := r.Method == http.MethodPut || r.Method == "MKCOL" - if isWrite && !userCanWrite(d.user.Permissions) { - return http.StatusForbidden, fmt.Errorf("user has no permission to modify") + if status, permErr := webDAVMethodPermission(r.Method, filePerms); permErr != nil { + return status, permErr } requestPath := utils.AddTrailingSlashIfNotExists(r.PathValue("path")) - source := r.PathValue("source") if !strings.HasPrefix(requestPath, "/") { requestPath = "/" + requestPath } - logger.Debugf("webdav: method=%s, request=%s, source=%s, requestPath=%s", r.Method, r.URL.Path, source, requestPath) _, userScope, err := files.CheckPermissions(utils.FileOptions{ FollowSymlinks: false, Path: requestPath, Source: source, - ShowHidden: d.user.ShowHidden, - HideFileExt: d.user.HideFileExt, - }, store.Access, d.user) + ShowHidden: d.User.ShowHidden, + HideFileExt: d.User.HideFileExt, + }, d.User) if err != nil { return http.StatusForbidden, err } @@ -396,22 +474,27 @@ func webDAVHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i // Get the user's scope to determine the WebDAV root directory // Resolve the scope path to get the real filesystem root for WebDAV - // This is the root directory that WebDAV will use to resolve relative paths - scopePath, _, err := idx.GetRealPath(userScope) + // This is the root directory that WebDAV will use to resolve relative paths. + // userScope is an index path (e.g. "/", "/public"); strip the leading "/" so + // filepath.Join inside GetRealPath does not treat it as a host-absolute path + // and discard idx.Path (e.g. Join(sourceRoot, "/") would become "/"). + scopeRel := strings.TrimPrefix(userScope, "/") + scopePath, _, err := idx.GetRealPath(scopeRel) if err != nil { return http.StatusNotFound, err } // Construct the WebDAV prefix from BaseURL - webDavPrefix := config.Server.BaseURL + "dav" + webDavPrefix := settings.Config.Http.BaseURL + "dav" prefix := webDavPrefix + "/" + source // Wrap the filesystem to filter directory listings using FileInfoFaster // We pass requestPath (without scope) to FileInfoFaster, which applies scope internally filteredFS := &filteredFileSystem{ fs: webdav.Dir(scopePath), source: source, - user: d.user, - userScope: userScope, + user: d.User, + filePerms: filePerms, + httpReq: r, } wd := &webdav.Handler{ @@ -430,11 +513,85 @@ func webDAVHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i } }, } - + if r.Method == "COPY" { + srcRealPath := filepath.Join(scopePath, requestPath) + sw := &statusResponseWriter{ResponseWriter: w, status: http.StatusOK} + wd.ServeHTTP(sw, r) + if destRealPath, ok := resolveDestination(r, prefix, scopePath); sw.status < 300 && ok { + if err := fileutils.PreserveModTimes(srcRealPath, destRealPath); err != nil { + logger.Debugf("could not preserve modification time on webdav copy: %v", err) + } + } + return 200, nil + } wd.ServeHTTP(w, r) return 200, nil // errors and responses (XML-formatted) are handled by webdav handler } -func userCanWrite(permissions users.Permissions) bool { - return permissions.Create && permissions.Modify && permissions.Delete +func webDAVMethodPermission(method string, perms users.SourceFilePermissions) (int, error) { + switch method { + case "PROPFIND", http.MethodOptions: + if !perms.View { + return http.StatusForbidden, fmt.Errorf("view permission required") + } + case http.MethodGet, http.MethodHead: + if !perms.Download { + return http.StatusForbidden, fmt.Errorf("download permission required") + } + case "MKCOL": + if !perms.Create { + return http.StatusForbidden, fmt.Errorf("create permission required") + } + case http.MethodPut: + if !perms.Modify { + return http.StatusForbidden, fmt.Errorf("modify permission required") + } + case http.MethodDelete: + if !perms.Delete { + return http.StatusForbidden, fmt.Errorf("delete permission required") + } + case "COPY": + if !perms.Download || !perms.Create { + return http.StatusForbidden, fmt.Errorf("copy permission required") + } + case "MOVE": + if !perms.Modify { + return http.StatusForbidden, fmt.Errorf("modify permission required") + } + default: + return http.StatusForbidden, fmt.Errorf("webdav method %s not permitted", method) + } + return 0, nil +} + +// statusResponseWriter records the status code written by the wrapped handler +type statusResponseWriter struct { + http.ResponseWriter + status int +} + +func (sw *statusResponseWriter) WriteHeader(status int) { + sw.status = status + sw.ResponseWriter.WriteHeader(status) +} + +// resolveDestination resolves the real fs path when doing a copy request +func resolveDestination(r *http.Request, prefix, scopePath string) (string, bool) { + raw := r.Header.Get("Destination") + if raw == "" { + return "", false + } + u, err := url.Parse(raw) + if err != nil { + return "", false + } + rest, ok := strings.CutPrefix(u.Path, prefix) + if !ok || (rest != "" && rest[0] != '/') { + return "", false + } + rel := path.Clean("/" + rest) + if rel == "/" { + return "", false + } + return filepath.Join(scopePath, rel), true } diff --git a/backend/http/webdav_test.go b/backend/internal/web/webdav_test.go similarity index 62% rename from backend/http/webdav_test.go rename to backend/internal/web/webdav_test.go index 85405750bc..b927c20b9d 100644 --- a/backend/http/webdav_test.go +++ b/backend/internal/web/webdav_test.go @@ -1,4 +1,4 @@ -package http +package web import ( "fmt" @@ -7,20 +7,21 @@ import ( "net/http/httptest" "os" "path/filepath" + "strconv" "strings" "testing" + "time" - storm "github.com/asdine/storm/v3" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files" - commonerrors "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/access" - "github.com/gtsteffaniak/filebrowser/backend/database/share" - "github.com/gtsteffaniak/filebrowser/backend/database/storage/bolt" - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/filebrowser/backend/indexing" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/internal/app" + _ "github.com/gtsteffaniak/filebrowser/backend/internal/database/sqldb" // Import to register SQL driver + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + commonerrors "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/indexing" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" ) // setupWebDAVTestEnv sets up the test environment with multiple sources and users @@ -64,55 +65,40 @@ func setupWebDAVTestEnv(t *testing.T) (string, string) { } } - // Setup database - dbPath := filepath.Join(tempDir, "db") - db, err := storm.Open(dbPath) + // Setup database with state + dbPath := filepath.Join(tempDir, "test.sqlite") + _, err := state.Initialize(dbPath) if err != nil { t.Fatal(err) } - store, err = bolt.NewStorage(db) - if err != nil { - t.Fatal(err) - } - - // Clear any previous access rules - store.Access.AllRules = make(access.SourceRuleMap) - store.Access.Groups = make(access.GroupMap) + app.MustWireServices(state.Default()) + t.Cleanup(func() { + state.Close() + }) // Set cache directory for index database - config.Server.CacheDir = tempDir - - // Setup config with sources - update both the local config var AND the global config - config = &settings.Settings{ - Server: settings.Server{ - BaseURL: "/", // Use / for tests to avoid prefix mismatch - CacheDir: tempDir, - SourceMap: map[string]*settings.Source{ - source1Path: { - Path: source1Path, - Name: "source1", - }, - source2Path: { - Path: source2Path, - Name: "source2", - }, - }, - NameToSource: map[string]*settings.Source{ - "source1": { - Path: source1Path, - Name: "source1", - }, - "source2": { - Path: source2Path, - Name: "source2", - }, - }, + settings.Config.Server.CacheDir = tempDir + settings.Config.Http.BaseURL = "/" + settings.Config.Server.SourceMap = map[string]*settings.Source{ + source1Path: { + Path: source1Path, + Name: "source1", + }, + source2Path: { + Path: source2Path, + Name: "source2", + }, + } + settings.Config.Server.NameToSource = map[string]*settings.Source{ + "source1": { + Path: source1Path, + Name: "source1", + }, + "source2": { + Path: source2Path, + Name: "source2", }, } - - // CRITICAL: Also update the global config so access.Permitted can find sources - settings.Config.Server.SourceMap = config.Server.SourceMap - settings.Config.Server.NameToSource = config.Server.NameToSource // Initialize user resolvers settings.InitializeUserResolvers() @@ -133,6 +119,30 @@ func setupWebDAVTestEnv(t *testing.T) (string, string) { return source1Path, source2Path } +func webDAVPermsForPaths(download, modify, create, delete bool, paths ...string) map[string]users.SourceFilePermissions { + m := make(map[string]users.SourceFilePermissions, len(paths)) + perms := users.SourceFilePermissions{ + View: true, + Download: download, + Modify: modify, + Create: create, + Delete: delete, + } + for _, path := range paths { + m[path] = perms + } + return m +} + +func applyBackendSourcePerms(user *users.User, perms map[string]users.SourceFilePermissions) { + user.BackendSourcePermissions = perms + for i, scope := range user.BackendScopes { + if p, ok := perms[scope.Path]; ok { + user.BackendScopes[i].Permissions = p + } + } +} + // mockCheckPermissions mocks the CheckPermissions function to bypass index lookups func mockCheckPermissions(t *testing.T, source1Path, source2Path string) { t.Helper() @@ -142,7 +152,7 @@ func mockCheckPermissions(t *testing.T, source1Path, source2Path string) { t.Cleanup(func() { files.CheckPermissionsFunc = originalCheckPermissions }) // Mock the function - files.CheckPermissionsFunc = func(opts utils.FileOptions, access *access.Storage, user *users.User) (string, string, error) { + files.CheckPermissionsFunc = func(opts utils.FileOptions, user *users.User) (string, string, error) { // Get the source path var sourcePath string if opts.Source == "source1" { @@ -156,8 +166,8 @@ func mockCheckPermissions(t *testing.T, source1Path, source2Path string) { // Get user scope for this source - match by source PATH, not name userScope := "/" hasScope := false - for _, scope := range user.Scopes { - if scope.Name == sourcePath { + for _, scope := range user.BackendScopes { + if scope.Path == sourcePath { userScope = scope.Scope hasScope = true break @@ -165,12 +175,12 @@ func mockCheckPermissions(t *testing.T, source1Path, source2Path string) { } // If user has no scope for this source, deny access - if !hasScope && len(user.Scopes) > 0 { + if !hasScope && len(user.BackendScopes) > 0 { return "", "", fmt.Errorf("user has no access to source: %s", opts.Source) } // Sanitize path - safePath, err := utils.SanitizeUserPath(opts.Path) + safePath, err := utils.SanitizePath(opts.Path) if err != nil { return "", "", commonerrors.ErrAccessDenied } @@ -179,7 +189,7 @@ func mockCheckPermissions(t *testing.T, source1Path, source2Path string) { indexPath := utils.JoinPathAsUnix(userScope, safePath) // Check access control - if access != nil && !access.Permitted(sourcePath, indexPath, user.Username) { + if !state.AccessPermitted(sourcePath, utils.IndexPathFromNormalized(indexPath, true), user.Username) { return "", "", commonerrors.ErrAccessDenied } @@ -193,7 +203,7 @@ func mockWebDAVIndexing(t *testing.T, source1Path, source2Path string) { originalFileInfoFaster := files.FileInfoFasterFunc t.Cleanup(func() { files.FileInfoFasterFunc = originalFileInfoFaster }) - files.FileInfoFasterFunc = func(opts utils.FileOptions, access *access.Storage, user *users.User, share *share.Storage) (*iteminfo.ExtendedFileInfo, error) { + files.FileInfoFasterFunc = func(opts utils.FileOptions, user *users.User) (*iteminfo.ExtendedFileInfo, error) { // Resolve source name to source path first sourcePath := "" if opts.Source == "source1" { @@ -205,24 +215,20 @@ func mockWebDAVIndexing(t *testing.T, source1Path, source2Path string) { } // Simulate access control - if access != nil && user != nil { - // Simple scope check based on user's configured scopes (which use source PATH) + if user != nil { hasAccess := false - for _, scope := range user.Scopes { - if scope.Name == sourcePath { + for _, scope := range user.BackendScopes { + if scope.Path == sourcePath { hasAccess = true - // Check if path is within user's scope userScope := scope.Scope fullPath := utils.JoinPathAsUnix(userScope, opts.Path) - - // Check if user has permission using the access storage - if !access.Permitted(sourcePath, fullPath, user.Username) { + if !state.AccessPermitted(sourcePath, utils.IndexPathFromNormalized(fullPath, true), user.Username) { return nil, commonerrors.ErrAccessDenied } break } } - if !hasAccess && len(user.Scopes) > 0 { + if !hasAccess && len(user.BackendScopes) > 0 { return nil, commonerrors.ErrAccessDenied } } @@ -284,53 +290,49 @@ func TestWebDAV_PROPFIND_UserScopes(t *testing.T) { // Create users with different scopes // IMPORTANT: SourceScope.Name should be the source PATH, not the source name adminUser := &users.User{ - ID: 1, - Username: "admin", - Permissions: users.Permissions{ - Admin: true, - Download: true, - Create: true, - Delete: true, - Modify: true, + ID: 1, + FrontendUser: users.FrontendUser{ + Username: "admin", + Permissions: users.Permissions{ + Admin: true, + }, }, - Scopes: []users.SourceScope{ - {Name: source1Path, Scope: "/"}, - {Name: source2Path, Scope: "/"}, + BackendScopes: []users.BackendScope{ + {Path: source1Path, Scope: "/"}, + {Path: source2Path, Scope: "/"}, }, + BackendSourcePermissions: webDAVPermsForPaths(true, true, true, true, source1Path, source2Path), + Version: users.SourcePermissionsMigrationVersion, } + applyBackendSourcePerms(adminUser, adminUser.BackendSourcePermissions) scopedUser := &users.User{ - ID: 2, - Username: "scoped", - Permissions: users.Permissions{ - Download: true, + ID: 2, + FrontendUser: users.FrontendUser{ + Username: "scoped", }, - Scopes: []users.SourceScope{ - {Name: source1Path, Scope: "/_docker"}, + BackendScopes: []users.BackendScope{ + {Path: source1Path, Scope: "/_docker"}, }, + BackendSourcePermissions: webDAVPermsForPaths(true, false, false, false, source1Path), + Version: users.SourcePermissionsMigrationVersion, } restrictedUser := &users.User{ - ID: 3, - Username: "restricted", - Permissions: users.Permissions{ - Download: true, + ID: 3, + FrontendUser: users.FrontendUser{ + Username: "restricted", }, - Scopes: []users.SourceScope{ - {Name: source1Path, Scope: "/public"}, + BackendScopes: []users.BackendScope{ + {Path: source1Path, Scope: "/public"}, }, + BackendSourcePermissions: webDAVPermsForPaths(true, false, false, false, source1Path), + Version: users.SourcePermissionsMigrationVersion, } - // Save users - if err := store.Users.Save(adminUser, true, true); err != nil { - t.Fatal(err) - } - if err := store.Users.Save(scopedUser, true, true); err != nil { - t.Fatal(err) - } - if err := store.Users.Save(restrictedUser, true, true); err != nil { - t.Fatal(err) - } + // Users are passed in requestContext only; do not call state.CreateUser here. + // CreateUser runs MakeUserDirs which rewrites scope "/" to "/", breaking + // WebDAV chroot (expects index scope "/" to map to the source root). testCases := []struct { name string @@ -392,7 +394,7 @@ func TestWebDAV_PROPFIND_UserScopes(t *testing.T) { req.SetPathValue("path", tc.path) w := httptest.NewRecorder() - ctx := &requestContext{user: tc.user} + ctx := &requestContext{User: tc.user} status, err := webDAVHandler(w, req, ctx) @@ -425,53 +427,39 @@ func TestWebDAV_WriteOperations(t *testing.T) { // Create users with different permissions // IMPORTANT: SourceScope.Name should be the source PATH, not the source name fullAccessUser := &users.User{ - ID: 1, - Username: "fullaccess", - Permissions: users.Permissions{ - Download: true, - Create: true, - Delete: true, - Modify: true, + ID: 1, + FrontendUser: users.FrontendUser{ + Username: "fullaccess", }, - Scopes: []users.SourceScope{ - {Name: source1Path, Scope: "/"}, + BackendScopes: []users.BackendScope{ + {Path: source1Path, Scope: "/"}, }, + BackendSourcePermissions: webDAVPermsForPaths(true, true, true, true, source1Path), + Version: users.SourcePermissionsMigrationVersion, } readOnlyUser := &users.User{ - ID: 2, - Username: "readonly", - Permissions: users.Permissions{ - Download: true, + ID: 2, + FrontendUser: users.FrontendUser{ + Username: "readonly", }, - Scopes: []users.SourceScope{ - {Name: source1Path, Scope: "/"}, + BackendScopes: []users.BackendScope{ + {Path: source1Path, Scope: "/"}, }, + BackendSourcePermissions: webDAVPermsForPaths(true, false, false, false, source1Path), + Version: users.SourcePermissionsMigrationVersion, } scopedUser := &users.User{ - ID: 3, - Username: "scoped", - Permissions: users.Permissions{ - Download: true, - Create: true, - Modify: true, - Delete: true, + ID: 3, + FrontendUser: users.FrontendUser{ + Username: "scoped", }, - Scopes: []users.SourceScope{ - {Name: source1Path, Scope: "/public"}, + BackendScopes: []users.BackendScope{ + {Path: source1Path, Scope: "/public"}, }, - } - - // Save users - if err := store.Users.Save(fullAccessUser, true, true); err != nil { - t.Fatal(err) - } - if err := store.Users.Save(readOnlyUser, true, true); err != nil { - t.Fatal(err) - } - if err := store.Users.Save(scopedUser, true, true); err != nil { - t.Fatal(err) + BackendSourcePermissions: webDAVPermsForPaths(true, true, true, true, source1Path), + Version: users.SourcePermissionsMigrationVersion, } initTestIndex(t, "source1", source1Path) @@ -553,7 +541,7 @@ func TestWebDAV_WriteOperations(t *testing.T) { req.SetPathValue("path", tc.path) w := httptest.NewRecorder() - ctx := &requestContext{user: tc.user} + ctx := &requestContext{User: tc.user} status, err := webDAVHandler(w, req, ctx) @@ -579,58 +567,37 @@ func TestWebDAV_AccessControl(t *testing.T) { // Create users // IMPORTANT: SourceScope.Name should be the source PATH, not the source name user1 := &users.User{ - ID: 1, - Username: "user1", - Permissions: users.Permissions{ - Download: true, - Create: true, + ID: 1, + FrontendUser: users.FrontendUser{ + Username: "user1", }, - Scopes: []users.SourceScope{ - {Name: source1Path, Scope: "/"}, + BackendScopes: []users.BackendScope{ + {Path: source1Path, Scope: "/"}, }, + BackendSourcePermissions: webDAVPermsForPaths(true, true, false, false, source1Path), + Version: users.SourcePermissionsMigrationVersion, } user2 := &users.User{ - ID: 2, - Username: "user2", - Permissions: users.Permissions{ - Download: true, + ID: 2, + FrontendUser: users.FrontendUser{ + Username: "user2", }, - Scopes: []users.SourceScope{ - {Name: source1Path, Scope: "/"}, + BackendScopes: []users.BackendScope{ + {Path: source1Path, Scope: "/"}, }, - } - - // Save users - if err := store.Users.Save(user1, true, true); err != nil { - t.Fatal(err) - } - if err := store.Users.Save(user2, true, true); err != nil { - t.Fatal(err) + BackendSourcePermissions: webDAVPermsForPaths(true, false, false, false, source1Path), + Version: users.SourcePermissionsMigrationVersion, } // Initialize index initTestIndex(t, "source1", source1Path) - // Create access rules by using the internal structure - // User1 can access /private, user2 cannot - // Set up a deny rule for user2 at /private - // IMPORTANT: Access system requires trailing slashes for exact match - rule := &access.AccessRule{ - Deny: access.RuleSet{ - Users: access.StringSet{"user2": struct{}{}}, - }, + err := state.DenyUser(source1Path, utils.IndexPathFromNormalized("/private/", true), "user2") + if err != nil { + t.Fatalf("failed to set up access rule: %v", err) } - // Add the rule to the access storage - if store.Access.AllRules == nil { - store.Access.AllRules = make(access.SourceRuleMap) - } - if store.Access.AllRules[source1Path] == nil { - store.Access.AllRules[source1Path] = make(access.RuleMap) - } - store.Access.AllRules[source1Path]["/private/"] = rule // Add trailing slash - testCases := []struct { name string user *users.User @@ -670,7 +637,7 @@ func TestWebDAV_AccessControl(t *testing.T) { req.SetPathValue("path", tc.path) w := httptest.NewRecorder() - ctx := &requestContext{user: tc.user} + ctx := &requestContext{User: tc.user} status, err := webDAVHandler(w, req, ctx) @@ -695,21 +662,15 @@ func TestWebDAV_IndexingStates(t *testing.T) { // IMPORTANT: SourceScope.Name should be the source PATH, not the source name user := &users.User{ - ID: 1, - Username: "testuser", - Permissions: users.Permissions{ - Download: true, - Create: true, - Modify: true, - Delete: true, + ID: 1, + FrontendUser: users.FrontendUser{ + Username: "testuser", }, - Scopes: []users.SourceScope{ - {Name: source1Path, Scope: "/"}, + BackendScopes: []users.BackendScope{ + {Path: source1Path, Scope: "/"}, }, - } - - if err := store.Users.Save(user, true, true); err != nil { - t.Fatal(err) + BackendSourcePermissions: webDAVPermsForPaths(true, true, true, true, source1Path), + Version: users.SourcePermissionsMigrationVersion, } initTestIndex(t, "source1", source1Path) @@ -777,7 +738,7 @@ func TestWebDAV_IndexingStates(t *testing.T) { req.SetPathValue("path", tc.path) w := httptest.NewRecorder() - ctx := &requestContext{user: user} + ctx := &requestContext{User: user} status, err := webDAVHandler(w, req, ctx) @@ -796,6 +757,124 @@ func TestWebDAV_IndexingStates(t *testing.T) { } } +// Test that PUT with X-OC-Mtime header applies the mod time to the file on initial creation and on overwrite +func TestWebDAV_PutSetsMtimeFromOCHeader(t *testing.T) { + source1Path, _ := setupWebDAVTestEnv(t) + + user := &users.User{ + ID: 1, + FrontendUser: users.FrontendUser{ + Username: "mtimeuser", + }, + BackendScopes: []users.BackendScope{{Path: source1Path, Scope: "/"}}, + BackendSourcePermissions: webDAVPermsForPaths(true, true, true, true, source1Path), + Version: users.SourcePermissionsMigrationVersion, + } + filePath := filepath.Join(source1Path, "public", "file.txt") + + put := func(body string, mtime time.Time, wantStatus int) { + t.Helper() + req := httptest.NewRequest(http.MethodPut, "/dav/source1/public/file.txt", strings.NewReader(body)) + req.SetPathValue("source", "source1") + req.SetPathValue("path", "/public/file.txt") + req.Header.Set("X-OC-Mtime", strconv.FormatInt(mtime.Unix(), 10)) + + w := httptest.NewRecorder() + if _, err := webDAVHandler(w, req, &requestContext{User: user}); err != nil { + t.Fatalf("webDAVHandler: %v", err) + } + if w.Code != wantStatus { + t.Fatalf("expected %d, got %d", wantStatus, w.Code) + } + + got, err := os.Stat(filePath) + if err != nil { + t.Fatalf("stat file: %v", err) + } + if !got.ModTime().Equal(mtime) { + t.Errorf("mtime = %v, want %v", got.ModTime(), mtime) + } + } + put("hi", time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC), http.StatusCreated) + put("updated!", time.Date(2021, 6, 7, 8, 9, 10, 0, time.UTC), http.StatusCreated) +} + +func TestWebDAV_PutIgnoresInvalidOCMtimeHeader(t *testing.T) { + source1Path, _ := setupWebDAVTestEnv(t) + user := &users.User{ + ID: 1, + FrontendUser: users.FrontendUser{ + Username: "mtimeuser2", + }, + BackendScopes: []users.BackendScope{{Path: source1Path, Scope: "/"}}, + BackendSourcePermissions: webDAVPermsForPaths(true, true, true, true, source1Path), + Version: users.SourcePermissionsMigrationVersion, + } + filePath := filepath.Join(source1Path, "public", "file2.txt") + + before := time.Now() + req := httptest.NewRequest(http.MethodPut, "/dav/source1/public/file2.txt", strings.NewReader("hi")) + req.SetPathValue("source", "source1") + req.SetPathValue("path", "/public/file2.txt") + req.Header.Set("X-OC-Mtime", "not-a-number") + + w := httptest.NewRecorder() + if _, err := webDAVHandler(w, req, &requestContext{User: user}); err != nil { + t.Fatalf("webDAVHandler: %v", err) + } + after := time.Now() + if w.Code != http.StatusCreated { + t.Fatalf("expected %d, got %d", http.StatusCreated, w.Code) + } + + got, err := os.Stat(filePath) + if err != nil { + t.Fatalf("stat file: %v", err) + } + if got.ModTime().Before(before.Add(-time.Second)) || got.ModTime().After(after.Add(time.Second)) { + t.Errorf("mtime = %v, want between %v and %v", got.ModTime(), before, after) + } +} + +func TestWebDAV_CopyPreservesModTime(t *testing.T) { + source1Path, _ := setupWebDAVTestEnv(t) + user := &users.User{ + ID: 1, + FrontendUser: users.FrontendUser{ + Username: "testcopy", + }, + BackendScopes: []users.BackendScope{{Path: source1Path, Scope: "/"}}, + BackendSourcePermissions: webDAVPermsForPaths(true, true, true, true, source1Path), + Version: users.SourcePermissionsMigrationVersion, + } + fileTime := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + readme := filepath.Join(source1Path, "public", "readme.txt") + if err := os.Chtimes(readme, fileTime, fileTime); err != nil { + t.Fatal(err) + } + req := httptest.NewRequest("COPY", "/dav/source1/public/", nil) + req.SetPathValue("source", "source1") + req.SetPathValue("path", "/public/") + req.Header.Set("Destination", "/dav/source1/copy") + req.Header.Set("Depth", "infinity") + + w := httptest.NewRecorder() + if _, err := webDAVHandler(w, req, &requestContext{User: user}); err != nil { + t.Fatalf("webDAVHandler: %v", err) + } + if w.Code != http.StatusCreated { + t.Fatalf("expected %d, got %d", http.StatusCreated, w.Code) + } + got, err := os.Stat(filepath.Join(source1Path, "copy", "readme.txt")) + if err != nil { + t.Fatalf("stat copy: %v", err) + } + if !got.ModTime().Equal(fileTime) { + t.Errorf("mtime = %v, want %v", got.ModTime(), fileTime) + } +} + + // Helper function to initialize a test index - simplified for WebDAV tests func initTestIndex(t *testing.T, name, path string) { // For WebDAV tests, indices are already initialized in setupWebDAVTestEnv diff --git a/backend/indexing/conditionalRules_test.go b/backend/pkg/indexing/conditionalRules_test.go similarity index 80% rename from backend/indexing/conditionalRules_test.go rename to backend/pkg/indexing/conditionalRules_test.go index 1658d16587..05e862d312 100644 --- a/backend/indexing/conditionalRules_test.go +++ b/backend/pkg/indexing/conditionalRules_test.go @@ -4,22 +4,21 @@ import ( "testing" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" ) -// setupConditionalTestIndex creates a test index with conditional rules configured -func setupConditionalTestIndex(conditionals settings.ConditionalFilter) *Index { +// setupConditionalTestIndex creates a test index with source rules configured. +func setupConditionalTestIndex(rules []settings.ConditionalRule) *Index { source := &settings.Source{ Name: "test", Path: "/test/path", Config: settings.SourceConfig{ - Conditionals: conditionals, + Rules: rules, }, } - // Build the conditional maps (this is normally done during config loading) - source.Config.ResolvedRules = settings.ResolvedRulesConfig{ + resolved := settings.ResolvedRulesConfig{ FileNames: make(map[string]settings.ConditionalRule), FolderNames: make(map[string]settings.ConditionalRule), FilePaths: make(map[string]settings.ConditionalRule), @@ -30,73 +29,60 @@ func setupConditionalTestIndex(conditionals settings.ConditionalFilter) *Index { IgnoreAllZeroSizeFolders: false, IgnoreAllSymlinks: false, IndexingDisabled: false, + NoRules: len(rules) == 0, } - // Backwards compatibility: if old format fields are set, treat as global rules - if conditionals.IgnoreHidden { - source.Config.ResolvedRules.IgnoreAllHidden = true - } - if conditionals.ZeroSizeFolders { - source.Config.ResolvedRules.IgnoreAllZeroSizeFolders = true - } - - // Build maps from ItemRules - match the real setConditionals implementation - for _, rule := range conditionals.ItemRules { - // Check if this is a root-level rule (folderPath == "/") - // Root-level rules with ignoreHidden/ignoreZeroSizeFolders/viewable set global flags + for _, rule := range rules { isRootLevelRule := rule.FolderPath == "/" - - // Infer global flags from root-level rules if isRootLevelRule { if rule.IgnoreHidden { - source.Config.ResolvedRules.IgnoreAllHidden = true + resolved.IgnoreAllHidden = true } if rule.IgnoreSymlinks { - source.Config.ResolvedRules.IgnoreAllSymlinks = true + resolved.IgnoreAllSymlinks = true } if rule.IgnoreZeroSizeFolders { - source.Config.ResolvedRules.IgnoreAllZeroSizeFolders = true + resolved.IgnoreAllZeroSizeFolders = true } if rule.Viewable { - source.Config.ResolvedRules.IndexingDisabled = true + resolved.IndexingDisabled = true } } - // Note: FileNames and FolderNames are NOT populated from rules in the real implementation - // They remain empty maps (unused in current implementation) - // Handle exact path matches if rule.FilePath != "" { - source.Config.ResolvedRules.FilePaths[rule.FilePath] = rule + resolved.FilePaths[rule.FilePath] = rule } if rule.FolderPath != "" { - source.Config.ResolvedRules.FolderPaths[rule.FolderPath] = rule + resolved.FolderPaths[rule.FolderPath] = rule } - - // Handle StartsWith/EndsWith (stored in slices) if rule.FileEndsWith != "" { - source.Config.ResolvedRules.FileEndsWith = append(source.Config.ResolvedRules.FileEndsWith, rule) + resolved.FileEndsWith = append(resolved.FileEndsWith, rule) } if rule.FolderEndsWith != "" { - source.Config.ResolvedRules.FolderEndsWith = append(source.Config.ResolvedRules.FolderEndsWith, rule) + resolved.FolderEndsWith = append(resolved.FolderEndsWith, rule) } if rule.FileStartsWith != "" { - source.Config.ResolvedRules.FileStartsWith = append(source.Config.ResolvedRules.FileStartsWith, rule) + resolved.FileStartsWith = append(resolved.FileStartsWith, rule) } if rule.FolderStartsWith != "" { - source.Config.ResolvedRules.FolderStartsWith = append(source.Config.ResolvedRules.FolderStartsWith, rule) + resolved.FolderStartsWith = append(resolved.FolderStartsWith, rule) } - - // Handle NeverWatchPath if rule.NeverWatchPath != "" { - source.Config.ResolvedRules.NeverWatchPaths[rule.NeverWatchPath] = struct{}{} + resolved.NeverWatchPaths[rule.NeverWatchPath] = struct{}{} } - - // Handle IncludeRootItem if rule.IncludeRootItem != "" { - source.Config.ResolvedRules.IncludeRootItems[rule.IncludeRootItem] = struct{}{} + resolved.IncludeRootItems[rule.IncludeRootItem] = struct{}{} + } + if rule.FileName != "" { + resolved.FileNames[rule.FileName] = rule + } + if rule.FolderName != "" { + resolved.FolderNames[rule.FolderName] = rule } } + source.Config.ResolvedRules = resolved + return &Index{ Source: *source, mock: true, @@ -156,10 +142,8 @@ func TestShouldSkip_FolderStartsWith(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - idx := setupConditionalTestIndex(settings.ConditionalFilter{ - ItemRules: []settings.ConditionalRule{ + idx := setupConditionalTestIndex([]settings.ConditionalRule{ {FolderStartsWith: tt.ruleValue}, - }, }) result := idx.ShouldSkip(true, tt.fullPath, false, false, false) @@ -204,15 +188,10 @@ func TestShouldSkip_FolderNames(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - idx := setupConditionalTestIndex(settings.ConditionalFilter{ - ItemRules: []settings.ConditionalRule{ - {FolderNames: tt.ruleValue}, - }, + idx := setupConditionalTestIndex([]settings.ConditionalRule{ + {FolderName: tt.ruleValue}, }) - // Manually populate FolderNames map since setConditionals doesn't do it - idx.Config.ResolvedRules.FolderNames[tt.ruleValue] = settings.ConditionalRule{FolderNames: tt.ruleValue} - result := idx.ShouldSkip(true, "/"+tt.baseName+"/", false, false, false) if result != tt.shouldSkip { t.Errorf("%s: expected shouldSkip=%v, got %v (baseName=%s, rule=%s)", @@ -267,10 +246,8 @@ func TestShouldSkip_FolderPaths(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - idx := setupConditionalTestIndex(settings.ConditionalFilter{ - ItemRules: []settings.ConditionalRule{ + idx := setupConditionalTestIndex([]settings.ConditionalRule{ {FolderPath: tt.ruleValue}, - }, }) result := idx.ShouldSkip(true, tt.fullPath, false, false, false) @@ -315,10 +292,8 @@ func TestShouldSkip_FileStartsWith(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - idx := setupConditionalTestIndex(settings.ConditionalFilter{ - ItemRules: []settings.ConditionalRule{ + idx := setupConditionalTestIndex([]settings.ConditionalRule{ {FileStartsWith: tt.ruleValue}, - }, }) result := idx.ShouldSkip(false, "/"+tt.baseName, false, false, false) @@ -363,10 +338,8 @@ func TestShouldSkip_FileEndsWith(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - idx := setupConditionalTestIndex(settings.ConditionalFilter{ - ItemRules: []settings.ConditionalRule{ + idx := setupConditionalTestIndex([]settings.ConditionalRule{ {FileEndsWith: tt.ruleValue}, - }, }) result := idx.ShouldSkip(false, "/"+tt.baseName, false, false, false) @@ -415,10 +388,8 @@ func TestShouldSkip_FilePaths(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - idx := setupConditionalTestIndex(settings.ConditionalFilter{ - ItemRules: []settings.ConditionalRule{ + idx := setupConditionalTestIndex([]settings.ConditionalRule{ {FilePath: tt.ruleValue}, - }, }) result := idx.ShouldSkip(false, tt.fullPath, false, false, false) @@ -433,11 +404,9 @@ func TestShouldSkip_FilePaths(t *testing.T) { func TestShouldSkip_FileInExcludedFolderPath(t *testing.T) { // Test that files in excluded folder paths are also skipped // Uses FilePaths rule which applies to both the folder and its files via prefix matching - idx := setupConditionalTestIndex(settings.ConditionalFilter{ - ItemRules: []settings.ConditionalRule{ - {FilePath: "/graham/"}, - }, - }) + idx := setupConditionalTestIndex([]settings.ConditionalRule{ + {FilePath: "/graham/" }, + }) tests := []struct { fullPath string @@ -461,22 +430,16 @@ func TestShouldSkip_FileInExcludedFolderPath(t *testing.T) { func TestShouldSkip_MultipleRules(t *testing.T) { // Test that multiple rules work together - idx := setupConditionalTestIndex(settings.ConditionalFilter{ - ItemRules: []settings.ConditionalRule{ - {FolderStartsWith: "temp"}, - {FolderStartsWith: "tmp"}, - {FolderNames: "node_modules"}, - {FolderNames: "@eaDir"}, - {FileStartsWith: "."}, - {FileEndsWith: ".tmp"}, - {FileEndsWith: "~"}, - }, + idx := setupConditionalTestIndex([]settings.ConditionalRule{ + {FolderStartsWith: "temp"}, + {FolderStartsWith: "tmp"}, + {FolderName: "node_modules"}, + {FolderName: "@eaDir"}, + {FileStartsWith: "."}, + {FileEndsWith: ".tmp"}, + {FileEndsWith: "~"}, }) - // Manually populate FolderNames map - idx.Config.ResolvedRules.FolderNames["node_modules"] = settings.ConditionalRule{FolderNames: "node_modules"} - idx.Config.ResolvedRules.FolderNames["@eaDir"] = settings.ConditionalRule{FolderNames: "@eaDir"} - tests := []struct { isDir bool fullPath string @@ -510,10 +473,8 @@ func TestShouldSkip_MultipleRules(t *testing.T) { func TestShouldSkip_ViewableStillSkips(t *testing.T) { // Test that Viewable:true doesn't affect shouldSkip behavior // The Viewable field is checked separately in IsViewable(), not in shouldSkip() - idx := setupConditionalTestIndex(settings.ConditionalFilter{ - ItemRules: []settings.ConditionalRule{ - {FolderStartsWith: "important", Viewable: true}, // Viewable but still skipped from indexing - }, + idx := setupConditionalTestIndex([]settings.ConditionalRule{ + {FolderStartsWith: "important", Viewable: true}, // Viewable but still skipped from indexing }) // ShouldSkip still returns true even with Viewable:true (it's checked separately) @@ -524,9 +485,9 @@ func TestShouldSkip_ViewableStillSkips(t *testing.T) { } func TestShouldSkip_HiddenFiles(t *testing.T) { - idx := setupConditionalTestIndex(settings.ConditionalFilter{ - IgnoreHidden: true, // Skip hidden files - }) + idx := setupConditionalTestIndex(nil) + idx.Config.ResolvedRules.NoRules = false + idx.Config.ResolvedRules.IgnoreAllHidden = true tests := []struct { path string @@ -550,11 +511,9 @@ func TestShouldSkip_HiddenFiles(t *testing.T) { func TestIsNeverWatchPath(t *testing.T) { // Test NeverWatchPath functionality - paths indexed once, then never re-indexed - idx := setupConditionalTestIndex(settings.ConditionalFilter{ - ItemRules: []settings.ConditionalRule{ - {NeverWatchPath: "/temp/"}, - {NeverWatchPath: "/cache/"}, - }, + idx := setupConditionalTestIndex([]settings.ConditionalRule{ + {NeverWatchPath: "/temp/"}, + {NeverWatchPath: "/cache/"}, }) tests := []struct { @@ -626,10 +585,11 @@ func TestIsNeverWatchPath(t *testing.T) { // TestIsViewable_DoesNotMutateFolderPaths verifies that IsViewable doesn't modify FolderPaths func TestIsViewable_DoesNotMutateFolderPaths(t *testing.T) { - idx := setupConditionalTestIndex(settings.ConditionalFilter{}) + idx := setupConditionalTestIndex(nil) + idx.Config.ResolvedRules.NoRules = false idx.Config.ResolvedRules.FolderNames["private"] = settings.ConditionalRule{ - FolderNames: "private", - Viewable: false, + FolderName: "private", + Viewable: false, } if len(idx.Config.ResolvedRules.FolderPaths) != 0 { @@ -647,7 +607,8 @@ func TestIsViewable_DoesNotMutateFolderPaths(t *testing.T) { // TestIsViewableWithParentCheck_RecursiveParentWalking tests API request parent checking func TestIsViewableWithParentCheck_RecursiveParentWalking(t *testing.T) { - idx := setupConditionalTestIndex(settings.ConditionalFilter{}) + idx := setupConditionalTestIndex(nil) + idx.Config.ResolvedRules.NoRules = false idx.Config.ResolvedRules.FolderPaths["/private"] = settings.ConditionalRule{ FolderPath: "/private", Viewable: false, @@ -744,9 +705,10 @@ func TestIsViewableWithParentCheck_RecursiveParentWalking(t *testing.T) { // TestIsViewableWithParentCheck_DoesNotMutate verifies thread safety func TestIsViewableWithParentCheck_DoesNotMutate(t *testing.T) { - idx := setupConditionalTestIndex(settings.ConditionalFilter{}) + idx := setupConditionalTestIndex(nil) + idx.Config.ResolvedRules.NoRules = false idx.Config.ResolvedRules.FolderNames["restricted"] = settings.ConditionalRule{ - FolderNames: "restricted", + FolderName: "restricted", Viewable: false, } diff --git a/backend/indexing/deletion_test.go b/backend/pkg/indexing/deletion_test.go similarity index 97% rename from backend/indexing/deletion_test.go rename to backend/pkg/indexing/deletion_test.go index ec44c55542..0df5a28bd7 100644 --- a/backend/indexing/deletion_test.go +++ b/backend/pkg/indexing/deletion_test.go @@ -5,9 +5,9 @@ import ( "testing" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - dbsql "github.com/gtsteffaniak/filebrowser/backend/database/sql" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + dbsql "github.com/gtsteffaniak/filebrowser/backend/internal/database/sql" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" ) // setupTestIndexForDeletion creates a test index with mock data for deletion testing diff --git a/backend/indexing/getDirInfoCore_test.go b/backend/pkg/indexing/getDirInfoCore_test.go similarity index 100% rename from backend/indexing/getDirInfoCore_test.go rename to backend/pkg/indexing/getDirInfoCore_test.go diff --git a/backend/indexing/indexingFiles.go b/backend/pkg/indexing/indexingFiles.go similarity index 97% rename from backend/indexing/indexingFiles.go rename to backend/pkg/indexing/indexingFiles.go index 3d1b48a1f9..95dddc42f8 100644 --- a/backend/indexing/indexingFiles.go +++ b/backend/pkg/indexing/indexingFiles.go @@ -9,12 +9,12 @@ import ( "sync" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/errors" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/database/dbindex" - dbsql "github.com/gtsteffaniak/filebrowser/backend/database/sql" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "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/database/dbindex" + dbsql "github.com/gtsteffaniak/filebrowser/backend/internal/database/sql" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" "github.com/gtsteffaniak/go-cache/cache" "github.com/gtsteffaniak/go-logger/logger" "golang.org/x/net/webdav" @@ -126,16 +126,15 @@ type Index struct { // WebDAV lock system for this source (isolated per source) WebdavLock webdav.LockSystem - // Adaptive scheduler: shared slot map (UTC unix seconds -> scanners). Only used when IndexingInterval == 0. + // Adaptive scheduler: shared slot map (UTC unix seconds -> scanners). scheduleSlotsMu sync.Mutex scheduleSlots map[int64][]*Scanner } var ( - indexes map[string]*Index - indexesMutex sync.RWMutex - indexDB *dbsql.IndexDB // Shared database for all indexes - indexingStorage *dbindex.Storage // Persistent storage for index metadata + indexes map[string]*Index + indexesMutex sync.RWMutex + indexDB *dbsql.IndexDB // Shared database for all indexes ) type IndexStatus string @@ -373,10 +372,7 @@ func SetIndexDBForTesting(db *dbsql.IndexDB) { indexDB = db } -// SetIndexingStorage sets the persistent storage for index metadata. -func SetIndexingStorage(storage *dbindex.Storage) { - indexingStorage = storage -} +// SetIndexingStorage is removed; index metadata persists via SetMetaStore from app.WireServices. func Initialize(source *settings.Source, mock bool, isNewDb bool) { indexesMutex.Lock() @@ -1017,12 +1013,12 @@ func (idx *Index) GetRealPath(relativePath ...string) (string, bool, error) { func (idx *Index) RefreshFileInfo(opts utils.FileOptions) error { // For files, refresh the parent directory if !opts.IsDir { - parentPath := idx.MakeIndexPath(filepath.Dir(opts.Path), true) + parentPath := idx.MakeIndexPath(filepath.Dir(opts.Path), true).String() return idx.RefreshDirectory(parentPath, false) // non-recursive for file changes } // For directories, use the recursive flag from opts - indexPath := idx.MakeIndexPath(opts.Path, true) + indexPath := idx.MakeIndexPath(opts.Path, true).String() return idx.RefreshDirectory(indexPath, opts.Recursive) } @@ -1516,17 +1512,13 @@ func (idx *Index) getActiveScannerPathUnlocked() string { // input should be non-index path. // isDir indicates whether the path is a directory (true) or file (false). -// Directories will have a trailing slash added, files will not. -func (idx *Index) MakeIndexPath(path string, isDir bool) string { +func (idx *Index) MakeIndexPath(path string, isDir bool) utils.IndexPath { if path == "." || strings.HasPrefix(path, "./") { path = strings.TrimPrefix(path, ".") } path = strings.TrimPrefix(path, idx.Path) path = idx.MakeIndexPathPlatform(path) - if isDir { - path = utils.AddTrailingSlashIfNotExists(path) - } - return path + return utils.IndexPathFromNormalized(path, isDir) } // MakeAbsolutePath converts a relative index path to an absolute path by combining @@ -1551,9 +1543,9 @@ func (idx *Index) shouldInclude(baseName string) bool { return false } -// useAdaptiveScheduling is true when the index uses tiered/aligned scheduling (IndexingInterval == 0). +// useAdaptiveScheduling reports whether the index uses tiered/aligned scheduling. func (idx *Index) useAdaptiveScheduling() bool { - return idx.Config.IndexingInterval == 0 + return true } // Save persists the index and scanner information to the database and notifies clients via SSE. @@ -1569,7 +1561,7 @@ func (idx *Index) Save() error { // writePersistedIndexInfo writes scanners, stats, and disk totals to Bolt (no SSE broadcast). func (idx *Index) writePersistedIndexInfo() error { - if indexingStorage == nil { + if !metaStoreConfigured() { return nil } @@ -1608,16 +1600,16 @@ func (idx *Index) writePersistedIndexInfo() error { Scanners: scanners, } - return indexingStorage.Save(info) + return saveIndexInfo(info) } // Load restores index and scanner information from the database func (idx *Index) Load() error { - if indexingStorage == nil { - return nil // No storage available, skip loading + if !metaStoreConfigured() { + return nil } - info, err := indexingStorage.GetByPath(idx.Path) + info, err := getIndexInfoByPath(idx.Path) if err != nil { if err == errors.ErrNotExist { // No persisted data exists, this is fine for new indexes diff --git a/backend/indexing/indexingFiles_test.go b/backend/pkg/indexing/indexingFiles_test.go similarity index 97% rename from backend/indexing/indexingFiles_test.go rename to backend/pkg/indexing/indexingFiles_test.go index af06669ea8..77e5d7582e 100644 --- a/backend/indexing/indexingFiles_test.go +++ b/backend/pkg/indexing/indexingFiles_test.go @@ -4,9 +4,9 @@ import ( "testing" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - dbsql "github.com/gtsteffaniak/filebrowser/backend/database/sql" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + dbsql "github.com/gtsteffaniak/filebrowser/backend/internal/database/sql" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" ) // setupTestIndex creates a test index with mock data (no filesystem dependencies) diff --git a/backend/indexing/indexingScanner.go b/backend/pkg/indexing/indexingScanner.go similarity index 99% rename from backend/indexing/indexingScanner.go rename to backend/pkg/indexing/indexingScanner.go index 6995e59c8d..5eb462fa10 100644 --- a/backend/indexing/indexingScanner.go +++ b/backend/pkg/indexing/indexingScanner.go @@ -8,8 +8,8 @@ import ( "sync" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" "github.com/gtsteffaniak/go-logger/logger" ) diff --git a/backend/indexing/indexingScanner_test.go b/backend/pkg/indexing/indexingScanner_test.go similarity index 72% rename from backend/indexing/indexingScanner_test.go rename to backend/pkg/indexing/indexingScanner_test.go index 263ff62919..eac5b7b024 100644 --- a/backend/indexing/indexingScanner_test.go +++ b/backend/pkg/indexing/indexingScanner_test.go @@ -5,38 +5,11 @@ import ( "testing" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - dbsql "github.com/gtsteffaniak/filebrowser/backend/database/sql" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + dbsql "github.com/gtsteffaniak/filebrowser/backend/internal/database/sql" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" ) -func TestPrepareScanStateInitializesMaps(t *testing.T) { - idx := &Index{ - Source: settings.Source{Name: "test", Path: t.TempDir()}, - } - s := &Scanner{scanPath: "/music/", idx: idx} - - s.prepareScanState() - - idx.mu.Lock() - idx.scanUpdatedPaths["/music/"] = true - idx.mu.Unlock() - - if s.processedInodes == nil { - t.Fatal("processedInodes should be initialized") - } - s.processedInodes[1] = struct{}{} -} - -func TestIsPathGone(t *testing.T) { - if isPathGone(nil) { - t.Fatal("nil error should not be path gone") - } - if !isPathGone(os.ErrNotExist) { - t.Fatal("os.ErrNotExist should be path gone") - } -} - // TestCheckFolderModtime_unchangedPreservesHasPreviewAndHidden verifies quick-scan touch updates // do not clobber has_preview/hidden when folder modtime is unchanged. func TestCheckFolderModtime_unchangedPreservesHasPreviewAndHidden(t *testing.T) { diff --git a/backend/indexing/indexingSchedule.go b/backend/pkg/indexing/indexingSchedule.go similarity index 97% rename from backend/indexing/indexingSchedule.go rename to backend/pkg/indexing/indexingSchedule.go index da7ba98b22..63022260b2 100644 --- a/backend/indexing/indexingSchedule.go +++ b/backend/pkg/indexing/indexingSchedule.go @@ -5,9 +5,9 @@ import ( "strconv" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - indexingdb "github.com/gtsteffaniak/filebrowser/backend/database/dbindex" - "github.com/gtsteffaniak/filebrowser/backend/events" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + indexingdb "github.com/gtsteffaniak/filebrowser/backend/internal/database/dbindex" + "github.com/gtsteffaniak/filebrowser/backend/internal/events" "github.com/gtsteffaniak/go-logger/logger" ) @@ -257,8 +257,8 @@ func (idx *Index) setupMultiScanner(isNewDb bool) { // Load persisted scanner info if available var persistedScanners map[string]*indexingdb.PersistedScannerInfo - if indexingStorage != nil && !isNewDb { - info, err := indexingStorage.GetByPath(idx.Path) + if !isNewDb && metaStoreConfigured() { + info, err := getIndexInfoByPath(idx.Path) if err == nil && info != nil { persistedScanners = info.Scanners } diff --git a/backend/indexing/indexingSchedulerLoop.go b/backend/pkg/indexing/indexingSchedulerLoop.go similarity index 92% rename from backend/indexing/indexingSchedulerLoop.go rename to backend/pkg/indexing/indexingSchedulerLoop.go index 1dfcf19f81..e00bcc2cba 100644 --- a/backend/indexing/indexingSchedulerLoop.go +++ b/backend/pkg/indexing/indexingSchedulerLoop.go @@ -4,7 +4,7 @@ import ( "sort" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" "github.com/gtsteffaniak/go-logger/logger" ) @@ -302,25 +302,6 @@ func (idx *Index) runIndexScheduler() { } }() - if !idx.useAdaptiveScheduling() { - idx.mu.RLock() - n := len(idx.scanners) - idx.mu.RUnlock() - interval := time.Duration(idx.Config.IndexingInterval) * time.Minute - logger.Debugf("[%s] scheduler: started fixed interval=%v scanners=%d", idx.Name, interval, n) - idx.runSerialScanPass() - for { - select { - case <-idx.schedulerStop: - logger.Debugf("[%s] scheduler: fixed loop stopped", idx.Name) - return - case <-time.After(interval): - logger.Debugf("[%s] scheduler: fixed interval wake", idx.Name) - idx.runSerialScanPass() - } - } - } - idx.mu.RLock() n := len(idx.scanners) idx.mu.RUnlock() diff --git a/backend/indexing/indexingSchedulerLoop_test.go b/backend/pkg/indexing/indexingSchedulerLoop_test.go similarity index 100% rename from backend/indexing/indexingSchedulerLoop_test.go rename to backend/pkg/indexing/indexingSchedulerLoop_test.go diff --git a/backend/indexing/indexing_test.go b/backend/pkg/indexing/indexing_test.go similarity index 92% rename from backend/indexing/indexing_test.go rename to backend/pkg/indexing/indexing_test.go index 2a34db2fbe..ae2dfe6de0 100644 --- a/backend/indexing/indexing_test.go +++ b/backend/pkg/indexing/indexing_test.go @@ -5,8 +5,9 @@ import ( "reflect" "testing" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - dbsql "github.com/gtsteffaniak/filebrowser/backend/database/sql" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + dbsql "github.com/gtsteffaniak/filebrowser/backend/internal/database/sql" ) func BenchmarkFillIndex(b *testing.B) { @@ -159,7 +160,7 @@ func TestMakeIndexPath(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { idx := &Index{Source: settings.Source{Path: "/srv"}, mock: true} - result := idx.MakeIndexPath(tt.subPath, true) // All test paths are directories + result := idx.MakeIndexPath(tt.subPath, true).String() if result != tt.expected { t.Errorf("MakeIndexPath(%q)\ngot %q\nwant %q", tt.name, result, tt.expected) } @@ -180,7 +181,7 @@ func TestMakeIndexPath(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { idx := &Index{Source: settings.Source{Path: "C:\\Users"}, mock: true} - result := idx.MakeIndexPath(tt.subPath, true) // All test paths are directories + result := idx.MakeIndexPath(tt.subPath, true).String() if result != tt.expected { t.Errorf("MakeIndexPath(%q)\ngot %q\nwant %q", tt.name, result, tt.expected) } @@ -188,6 +189,15 @@ func TestMakeIndexPath(t *testing.T) { } } +func TestMakeIndexPath_File(t *testing.T) { + idx := &Index{Source: settings.Source{Path: "/srv"}, mock: true} + got := idx.MakeIndexPath("/srv/docs/readme.txt", false) + want := utils.IndexPathFromNormalized("/docs/readme.txt", false) + if got.String() != want.String() { + t.Errorf("MakeIndexPath file got %q want %q", got.String(), want.String()) + } +} + func TestMakeIndexPathRoot(t *testing.T) { tests := []struct { name string @@ -201,7 +211,7 @@ func TestMakeIndexPathRoot(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { idx := &Index{Source: settings.Source{Path: "/rootpath", Name: "default"}, mock: true} - result := idx.MakeIndexPath(tt.subPath, true) // Root path is a directory + result := idx.MakeIndexPath(tt.subPath, true).String() if result != tt.expected { t.Errorf("MakeIndexPath(%q)\ngot %q\nwant %q", tt.name, result, tt.expected) } @@ -209,7 +219,7 @@ func TestMakeIndexPathRoot(t *testing.T) { } } -// TODO: Update these tests to use new ConditionalFilter structure +// TODO: Update these tests to use config.rules structure /* func TestCheckIndexExclude(t *testing.T) { tests := []struct { diff --git a/backend/indexing/iteminfo/conditions.go b/backend/pkg/indexing/iteminfo/conditions.go similarity index 99% rename from backend/indexing/iteminfo/conditions.go rename to backend/pkg/indexing/iteminfo/conditions.go index 218320eddf..90d2b0402c 100644 --- a/backend/indexing/iteminfo/conditions.go +++ b/backend/pkg/indexing/iteminfo/conditions.go @@ -6,7 +6,7 @@ import ( "strconv" "strings" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" ) const ( diff --git a/backend/indexing/iteminfo/conditions_test.go b/backend/pkg/indexing/iteminfo/conditions_test.go similarity index 100% rename from backend/indexing/iteminfo/conditions_test.go rename to backend/pkg/indexing/iteminfo/conditions_test.go diff --git a/backend/indexing/iteminfo/fileinfo.go b/backend/pkg/indexing/iteminfo/fileinfo.go similarity index 83% rename from backend/indexing/iteminfo/fileinfo.go rename to backend/pkg/indexing/iteminfo/fileinfo.go index 703a4ef0f2..0b95630b79 100644 --- a/backend/indexing/iteminfo/fileinfo.go +++ b/backend/pkg/indexing/iteminfo/fileinfo.go @@ -3,7 +3,7 @@ package iteminfo import ( "time" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" ) type ItemInfo struct { @@ -20,7 +20,8 @@ type ItemInfo struct { // This avoids adding memory overhead to indexed items type ExtendedItemInfo struct { ItemInfo - Metadata *MediaMetadata `json:"metadata,omitempty"` // optional media metadata (audio/video only) + Metadata *MediaMetadata `json:"metadata,omitempty"` // optional media metadata (audio/video only) + ViewToken string `json:"viewToken,omitempty"` // opaque token for inline viewing via /resources/view or /media/stream } // FileInfo describes a file. @@ -49,6 +50,9 @@ type MediaMetadata struct { Genre string `json:"genre,omitempty"` // music/video genre Track int `json:"track,omitempty"` // track number Duration int `json:"duration,omitempty"` // duration in seconds + VideoCodec string `json:"videoCodec,omitempty"` // video codec name (e.g. h264) + AudioCodec string `json:"audioCodec,omitempty"` // audio codec name (e.g. aac) + Container string `json:"container,omitempty"` // container/format name (e.g. mov,mp4,m4a,3gp,3g2,mj2) AlbumArt []byte `json:"albumArt,omitempty"` // album art image data (automatically base64-encoded in JSON) Lyrics []Lyric `json:"lyrics,omitempty"` // lyrics (from embedded tags or .lrc files) HasLyrics bool `json:"hasLyrics,omitempty"` // checks if lyrics are available without parse them @@ -68,4 +72,5 @@ type ExtendedFileInfo struct { Hash string `json:"hash,omitempty"` // hash for the file -- used for sharing RealPath string `json:"-"` PinnedItems []string `json:"pinnedItems,omitempty"` // pinned item names in this directory listing + ViewToken string `json:"viewToken,omitempty"` // opaque token for inline viewing via /resources/view or /media/stream } diff --git a/backend/indexing/iteminfo/mediaMeta.go b/backend/pkg/indexing/iteminfo/mediaMeta.go similarity index 99% rename from backend/indexing/iteminfo/mediaMeta.go rename to backend/pkg/indexing/iteminfo/mediaMeta.go index fa6ff82de2..1f4c6f3535 100644 --- a/backend/indexing/iteminfo/mediaMeta.go +++ b/backend/pkg/indexing/iteminfo/mediaMeta.go @@ -411,6 +411,7 @@ func ShouldBubbleUpToFolderPreview(item ItemInfo) bool { if item.Type == "directory" || !item.HasPreview { return false } + // Get the simple type (e.g., "image", "video", "text") simpleType := strings.Split(item.Type, "/")[0] // Only allow images, videos, and audio with album art to bubble up if simpleType == "image" || simpleType == "video" || simpleType == "audio" { diff --git a/backend/indexing/iteminfo/mediaMeta_test.go b/backend/pkg/indexing/iteminfo/mediaMeta_test.go similarity index 100% rename from backend/indexing/iteminfo/mediaMeta_test.go rename to backend/pkg/indexing/iteminfo/mediaMeta_test.go diff --git a/backend/indexing/iteminfo/searchPatterns.go b/backend/pkg/indexing/iteminfo/searchPatterns.go similarity index 100% rename from backend/indexing/iteminfo/searchPatterns.go rename to backend/pkg/indexing/iteminfo/searchPatterns.go diff --git a/backend/indexing/iteminfo/searchPatterns_test.go b/backend/pkg/indexing/iteminfo/searchPatterns_test.go similarity index 100% rename from backend/indexing/iteminfo/searchPatterns_test.go rename to backend/pkg/indexing/iteminfo/searchPatterns_test.go diff --git a/backend/indexing/iteminfo/searchQuery.go b/backend/pkg/indexing/iteminfo/searchQuery.go similarity index 100% rename from backend/indexing/iteminfo/searchQuery.go rename to backend/pkg/indexing/iteminfo/searchQuery.go diff --git a/backend/indexing/iteminfo/utils.go b/backend/pkg/indexing/iteminfo/utils.go similarity index 98% rename from backend/indexing/iteminfo/utils.go rename to backend/pkg/indexing/iteminfo/utils.go index d9ce3b4ca5..f43acc1a90 100644 --- a/backend/indexing/iteminfo/utils.go +++ b/backend/pkg/indexing/iteminfo/utils.go @@ -8,7 +8,7 @@ import ( "strconv" "strings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" ) type FFProbeOutput struct { diff --git a/backend/pkg/indexing/meta_store.go b/backend/pkg/indexing/meta_store.go new file mode 100644 index 0000000000..6eba563a45 --- /dev/null +++ b/backend/pkg/indexing/meta_store.go @@ -0,0 +1,36 @@ +package indexing + +import ( + "github.com/gtsteffaniak/filebrowser/backend/internal/database/dbindex" + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/ports" +) + +var metaStore ports.IndexMetaStore + +// SetMetaStore registers the index metadata persistence port (called from app.WireServices). +func SetMetaStore(s ports.IndexMetaStore) { + metaStore = s +} + +func getIndexInfoByPath(path string) (*dbindex.IndexInfo, error) { + if metaStore == nil { + return nil, errors.ErrNotExist + } + info, err := metaStore.GetIndexInfo(path) + if err != nil { + return nil, err + } + return &info, nil +} + +func saveIndexInfo(info *dbindex.IndexInfo) error { + if metaStore == nil { + return nil + } + return metaStore.SaveIndexInfo(info) +} + +func metaStoreConfigured() bool { + return metaStore != nil +} diff --git a/backend/indexing/mock.go b/backend/pkg/indexing/mock.go similarity index 93% rename from backend/indexing/mock.go rename to backend/pkg/indexing/mock.go index 3fc6bbb51e..d7edb93dd4 100644 --- a/backend/indexing/mock.go +++ b/backend/pkg/indexing/mock.go @@ -4,8 +4,8 @@ import ( "math/rand" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" ) func (idx *Index) CreateMockData(numDirs, numFilesPerDir int) { diff --git a/backend/indexing/mutate.go b/backend/pkg/indexing/mutate.go similarity index 92% rename from backend/indexing/mutate.go rename to backend/pkg/indexing/mutate.go index 0764987fb6..46e57e1410 100644 --- a/backend/indexing/mutate.go +++ b/backend/pkg/indexing/mutate.go @@ -5,10 +5,10 @@ import ( "path/filepath" "strings" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "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/go-logger/logger" ) @@ -44,9 +44,7 @@ func (idx *Index) UpdateMetadata(info *iteminfo.FileInfo, scanner *Scanner, pers items = append(items, fileItem) } - // Use scanner-specific batch if available if scanner != nil { - // Track that this directory was updated by the scan (for timestamp conflict detection) normalizedPath := utils.AddTrailingSlashIfNotExists(info.Path) idx.mu.Lock() if idx.scanUpdatedPaths == nil { @@ -55,16 +53,13 @@ func (idx *Index) UpdateMetadata(info *iteminfo.FileInfo, scanner *Scanner, pers idx.scanUpdatedPaths[normalizedPath] = true idx.mu.Unlock() - // Accumulate items for bulk insert in scanner's batch scanner.batchItems = append(scanner.batchItems, items...) - // Progressive flushing: flush every BATCH_SIZE items to keep memory bounded if len(scanner.batchItems) >= idx.db.BatchSize { scanner.flushBatch() } return true } - // Not in a batch scan - insert immediately (e.g., API-triggered updates) if err := idx.db.BulkInsertItems(idx.Name, items); err != nil { logger.Errorf("Failed to update metadata for %s: %v", info.Path, err) return false @@ -120,11 +115,7 @@ func (idx *Index) DeleteMetadata(path string, isDir bool, recursive bool) bool { // GetMetadataInfo retrieves the FileInfo from the specified file or directory in the index. func (idx *Index) GetReducedMetadata(target string, isDir bool) (*iteminfo.FileInfo, bool) { - checkPath := idx.MakeIndexPath(target, isDir) - - if checkPath == "" { - checkPath = "/" - } + checkPath := idx.MakeIndexPath(target, isDir).String() // checkPath is already an index path (relative to source root) item, err := idx.db.GetItem(idx.Name, checkPath) @@ -157,13 +148,9 @@ func (idx *Index) GetMetadataInfo(target string, isDir bool, shallow bool) (*ite var checkDir string if !isDir { - checkDir = idx.MakeIndexPath(filepath.Dir(target), true) + checkDir = idx.MakeIndexPath(filepath.Dir(target), true).String() } else { - checkDir = idx.MakeIndexPath(target, true) - } - - if checkDir == "" { - checkDir = "/" + checkDir = idx.MakeIndexPath(target, true).String() } // checkDir is already an index path (relative to source root) @@ -318,7 +305,7 @@ func GetIndexInfo(sourceName string, forceCacheRefresh bool) (ReducedIndex, erro } idx.SetUsage(totalPartitionSize, partitionUsed, indexedSizeFromDB) utils.DiskUsageCache.Set(cacheKey, true) - if indexingStorage != nil { + if metaStoreConfigured() { if err := idx.writePersistedIndexInfo(); err != nil { logger.Warningf("GetIndexInfo: failed to persist index disk stats for %s: %v", sourceName, err) } diff --git a/backend/indexing/mutate_test.go b/backend/pkg/indexing/mutate_test.go similarity index 97% rename from backend/indexing/mutate_test.go rename to backend/pkg/indexing/mutate_test.go index 580c71022a..efa8b07188 100644 --- a/backend/indexing/mutate_test.go +++ b/backend/pkg/indexing/mutate_test.go @@ -5,9 +5,9 @@ import ( "testing" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - dbsql "github.com/gtsteffaniak/filebrowser/backend/database/sql" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + dbsql "github.com/gtsteffaniak/filebrowser/backend/internal/database/sql" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" "github.com/stretchr/testify/assert" ) diff --git a/backend/indexing/search.go b/backend/pkg/indexing/search.go similarity index 98% rename from backend/indexing/search.go rename to backend/pkg/indexing/search.go index f7bd68a738..5b46936c39 100644 --- a/backend/indexing/search.go +++ b/backend/pkg/indexing/search.go @@ -6,8 +6,8 @@ import ( "sync" "time" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" "github.com/gtsteffaniak/go-cache/cache" "github.com/gtsteffaniak/go-logger/logger" ) diff --git a/backend/indexing/search_test.go b/backend/pkg/indexing/search_test.go similarity index 98% rename from backend/indexing/search_test.go rename to backend/pkg/indexing/search_test.go index a275f3ef43..a7c9b594cd 100644 --- a/backend/indexing/search_test.go +++ b/backend/pkg/indexing/search_test.go @@ -8,11 +8,11 @@ import ( "testing" "time" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - dbsql "github.com/gtsteffaniak/filebrowser/backend/database/sql" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + dbsql "github.com/gtsteffaniak/filebrowser/backend/internal/database/sql" + "github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo" "github.com/stretchr/testify/assert" ) diff --git a/backend/indexing/test_helpers.go b/backend/pkg/indexing/test_helpers.go similarity index 91% rename from backend/indexing/test_helpers.go rename to backend/pkg/indexing/test_helpers.go index 32be80d59b..b97b766bb5 100644 --- a/backend/indexing/test_helpers.go +++ b/backend/pkg/indexing/test_helpers.go @@ -1,7 +1,7 @@ package indexing import ( - "github.com/gtsteffaniak/filebrowser/backend/common/settings" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" "golang.org/x/net/webdav" ) @@ -10,7 +10,7 @@ import ( func SetTestIndex(name string, path string) { indexesMutex.Lock() defer indexesMutex.Unlock() - + idx := &Index{ Source: settings.Source{ Name: name, diff --git a/backend/indexing/unix.go b/backend/pkg/indexing/unix.go similarity index 100% rename from backend/indexing/unix.go rename to backend/pkg/indexing/unix.go diff --git a/backend/indexing/windows.go b/backend/pkg/indexing/windows.go similarity index 100% rename from backend/indexing/windows.go rename to backend/pkg/indexing/windows.go diff --git a/backend/common/settings/apply_user_defaults_test.go b/backend/pkg/settings/apply_user_defaults_test.go similarity index 59% rename from backend/common/settings/apply_user_defaults_test.go rename to backend/pkg/settings/apply_user_defaults_test.go index f2860a7da5..5b80da303c 100644 --- a/backend/common/settings/apply_user_defaults_test.go +++ b/backend/pkg/settings/apply_user_defaults_test.go @@ -5,7 +5,7 @@ import ( "github.com/google/go-cmp/cmp" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" ) // TestApplyUserDefaults_copiesUserDefaultsOntoUser guards against drift between @@ -15,7 +15,6 @@ func TestApplyUserDefaults_copiesUserDefaultsOntoUser(t *testing.T) { defer func() { Config = saved }() dark := false - dlFalse := false Config = Settings{ Server: Server{}, UserDefaults: UserDefaults{ @@ -59,7 +58,6 @@ func TestApplyUserDefaults_copiesUserDefaultsOntoUser(t *testing.T) { DisableOnlyOfficeExt: ".x", PreferEditorForMarkdown: true, DebugOffice: true, - DefaultMediaPlayer: true, }, Search: UserDefaultsSearch{ DisableOptions: true, @@ -79,12 +77,8 @@ func TestApplyUserDefaults_copiesUserDefaultsOntoUser(t *testing.T) { Permissions: UserDefaultsAccountPermissions{ Api: true, Admin: true, - Modify: true, Share: true, Realtime: true, - Delete: true, - Create: true, - Download: &dlFalse, }, LockPassword: true, DisableSettings: true, @@ -94,68 +88,69 @@ func TestApplyUserDefaults_copiesUserDefaultsOntoUser(t *testing.T) { }, } - u := &users.User{Username: "alice"} + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "alice", + }, + } ApplyUserDefaults(u) want := users.User{ - DisableSettings: true, - LockPassword: true, - LoginMethod: users.LoginMethodPassword, - Permissions: users.Permissions{ - Api: true, - Admin: true, - Modify: true, - Share: true, - Realtime: true, - Delete: true, - Create: true, - Download: false, - }, - NonAdminEditable: users.NonAdminEditable{ - EditorQuickSave: true, - HideSidebarFileActions: true, - DisableQuickToggles: true, - DisableSearchOptions: true, - StickySidebar: false, - HideFilesInTree: true, - DarkMode: false, - Locale: "de", - ViewMode: "list", - SingleClick: true, - ShowHidden: true, - DateFormat: true, - GallerySize: 7, - ThemeColor: "var(--red)", - QuickDownload: true, - DisablePreviewExt: ".exe", - DisableViewingExt: ".bat", - DisableUpdateNotifications: true, - DisableOfficePreviewExt: ".x", // deprecated: mapped to DisableOnlyOfficeExt - DisableOnlyOfficeExt: ".x", - CustomTheme: "Night", - ShowSelectMultiple: true, - DebugOffice: true, - DeleteWithoutConfirming: true, - DeleteAfterArchive: false, - PreferEditorForMarkdown: true, - ShowToolsInSidebar: true, - FileLoading: users.FileLoading{ - MaxConcurrent: 3, - UploadChunkSize: 5, - DownloadChunkSize: 2, + FrontendUser: users.FrontendUser{ + DisableSettings: true, + LockPassword: true, + LoginMethod: users.LoginMethodPassword, + Permissions: users.Permissions{ + Api: true, + Admin: true, + Share: true, + Realtime: true, }, - Preview: users.Preview{ - DisableHideSidebar: true, - Image: false, - Video: false, - Audio: false, - MotionVideoPreview: false, - Office: false, - PopUp: false, - AutoplayMedia: false, - DefaultMediaPlayer: true, - Folder: false, - Models: false, + NonAdminEditable: users.NonAdminEditable{ + EditorQuickSave: true, + HideSidebarFileActions: true, + DisableQuickToggles: true, + DisableSearchOptions: true, + StickySidebar: false, + HideFilesInTree: true, + DarkMode: false, + Locale: "de", + ViewMode: "list", + SingleClick: true, + ShowHidden: true, + DateFormat: true, + GallerySize: 7, + ThemeColor: "var(--red)", + QuickDownload: true, + DisablePreviewExt: ".exe", + DisableViewingExt: ".bat", + DisableUpdateNotifications: true, + DisableOfficePreviewExt: ".x", // deprecated: mapped to DisableOnlyOfficeExt + DisableOnlyOfficeExt: ".x", + CustomTheme: "Night", + ShowSelectMultiple: true, + DebugOffice: true, + DeleteWithoutConfirming: true, + DeleteAfterArchive: false, + PreferEditorForMarkdown: true, + ShowToolsInSidebar: true, + FileLoading: users.FileLoading{ + MaxConcurrent: 3, + UploadChunkSize: 5, + DownloadChunkSize: 2, + }, + Preview: users.Preview{ + DisableHideSidebar: true, + Image: false, + Video: false, + Audio: false, + MotionVideoPreview: false, + Office: false, + PopUp: false, + AutoplayMedia: false, + Folder: false, + Models: false, + }, }, }, } @@ -189,7 +184,9 @@ func TestApplyUserDefaults_setsLoginMethodWhenEmpty(t *testing.T) { }, }, } - u := &users.User{Username: "x"} + u := &users.User{ + FrontendUser: users.FrontendUser{Username: "x"}, + } ApplyUserDefaults(u) if u.LoginMethod != users.LoginMethodJwt { t.Fatalf("LoginMethod: got %q want jwt", u.LoginMethod) @@ -208,9 +205,31 @@ func TestApplyUserDefaults_preservesLoginMethodWhenAlreadySet(t *testing.T) { }, }, } - u := &users.User{Username: "x", LoginMethod: users.LoginMethodProxy} + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "x", + LoginMethod: users.LoginMethodProxy, + }, + } ApplyUserDefaults(u) if u.LoginMethod != users.LoginMethodProxy { t.Fatalf("LoginMethod: got %q want proxy", u.LoginMethod) } } + +func TestExpandBackendScopesForCreateUserDir(t *testing.T) { + loadConfigForUserDefaultsTests(t, jwtPlaywrightConfig) + u := &users.User{ + FrontendUser: users.FrontendUser{Username: "testadmin"}, + BackendScopes: []users.BackendScope{ + {Path: Config.Server.Sources[0].Path, Scope: "/"}, + }, + } + ExpandBackendScopesForCreateUserDir(u) + if len(u.BackendScopes) != 1 { + t.Fatalf("scopes: %+v", u.BackendScopes) + } + if u.BackendScopes[0].Scope != "/testadmin" { + t.Fatalf("scope=%q want /testadmin", u.BackendScopes[0].Scope) + } +} diff --git a/backend/common/settings/auth.go b/backend/pkg/settings/auth.go similarity index 99% rename from backend/common/settings/auth.go rename to backend/pkg/settings/auth.go index a555eb9e00..b0da68dbc8 100644 --- a/backend/common/settings/auth.go +++ b/backend/pkg/settings/auth.go @@ -11,7 +11,7 @@ import ( "github.com/coreos/go-oidc/v3/oidc" ldap "github.com/go-ldap/ldap/v3" - "github.com/gtsteffaniak/filebrowser/backend/common/version" + "github.com/gtsteffaniak/filebrowser/backend/internal/version" "github.com/gtsteffaniak/go-logger/logger" ) diff --git a/backend/common/settings/auth_ldap_test.go b/backend/pkg/settings/auth_ldap_test.go similarity index 100% rename from backend/common/settings/auth_ldap_test.go rename to backend/pkg/settings/auth_ldap_test.go diff --git a/backend/common/settings/config.go b/backend/pkg/settings/config.go similarity index 68% rename from backend/common/settings/config.go rename to backend/pkg/settings/config.go index be372c3435..6dde2c3527 100644 --- a/backend/common/settings/config.go +++ b/backend/pkg/settings/config.go @@ -2,11 +2,12 @@ package settings import ( "bytes" + "context" + "flag" "fmt" "io" "log" "os" - "os/exec" "path/filepath" "slices" "strconv" @@ -15,10 +16,11 @@ import ( "github.com/go-playground/validator/v10" "github.com/goccy/go-yaml" - "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" - "github.com/gtsteffaniak/filebrowser/backend/common/utils" - "github.com/gtsteffaniak/filebrowser/backend/common/version" - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/ffmpeg" + "github.com/gtsteffaniak/filebrowser/backend/internal/utils" + "github.com/gtsteffaniak/filebrowser/backend/internal/version" "github.com/gtsteffaniak/go-logger/logger" ) @@ -38,8 +40,6 @@ func Initialize(configFile string) { setupLogging() // setup logging first to ensure we log any errors setupEnv() - // Migrate deprecated UserDefaults fields to new organized structure - migrateUserDefaults() err = ValidateConfig(Config) if err != nil { errmsg := "The provided config file failed validation. " @@ -57,22 +57,16 @@ func Initialize(configFile string) { setupSources(false) InitializeUserResolvers() // Initialize user package resolvers after sources are set up setupUrls() + warnHttpProxyConfig() setupFrontend(false) setupMedia(false) } func setupServer() { - if Config.Server.Socket != "" && (Config.Server.TLSCert != "" || Config.Server.TLSKey != "") { - logger.Fatal("server.socket cannot be used with tlsCert or tlsKey") - } - if Config.Server.ListenAddress == "" { - Config.Server.ListenAddress = "0.0.0.0" - } // Check environment variable first (overrides config file) if os.Getenv("FILEBROWSER_SQL_WAL") == "true" { Config.Server.IndexSqlConfig.WalMode = true } - // WalMode is false by default (OFF journaling) } func setupEnv() { @@ -87,14 +81,41 @@ func setupEnv() { } func setupHttp() { - if len(Config.Http.TrustedHeadersArray) > 0 { - Config.Http.TrustedHeaders = make(map[string]bool) - for _, header := range Config.Http.TrustedHeadersArray { - Config.Http.TrustedHeaders[strings.ToLower(header)] = true + if err := ValidateHttpConfig(Config.Http); err != nil { + logger.Fatal(err.Error()) + } + if Config.Http.ListenAddress == "" { + Config.Http.ListenAddress = "0.0.0.0" + } +} + +func warnHttpProxyConfig() { + if Env.IsDevMode || Env.IsPlaywright { + return + } + if Config.Http.BaseURL != "/" && !Config.Http.TrustProxyHeaders { + logger.Warning(`http.baseURL is not "/" but http.trustProxyHeaders is false. Behind a reverse proxy on a subpath, set trustProxyHeaders: true so cookies, client IP, OIDC redirects, and URLs resolve correctly. See https://filebrowserquantum.com/en/docs/configuration/http/#trustproxyheaders`) + } + if !Env.IsDevMode { + if u := Config.Http.ExternalUrl; u != "" && strings.HasPrefix(strings.ToLower(u), "http://") { + logger.Warning("http.externalUrl uses http when the url should be https for a production environment") + } + if u := Config.Integrations.OnlyOffice.Url; u != "" && strings.HasPrefix(strings.ToLower(u), "http://") { + logger.Warning("integrations.office.url uses http when it should be https for a production environment.") } } } +func warnOidcProxyHeaders() { + if !Config.Auth.Methods.OidcAuth.Enabled { + return + } + if Config.Http.TrustProxyHeaders { + return + } + logger.Warning("OIDC is enabled but http.trustProxyHeaders is false. Behind a reverse proxy, FileBrowser builds the OIDC redirect_uri from the incoming request; set trustProxyHeaders: true and configure your proxy to send X-Forwarded-Proto and X-Forwarded-Host. http.externalUrl does not apply to OIDC redirects.") +} + func setupFs() { // Convert permission values (like 644, 755) to octal interpretation filePermOctal, err := strconv.ParseUint(Config.Server.Filesystem.CreateFilePermission, 8, 32) @@ -334,18 +355,45 @@ func setupMedia(generate bool) { Config.Integrations.Media.Convert.VideoPreview[k] = v } - // Resolve exiftool path once at startup: validate user path or discover via PATH - if Config.Integrations.Media.ExiftoolPath != "" && !generate { - if err := exec.Command(Config.Integrations.Media.ExiftoolPath, "-ver").Run(); err != nil { - logger.Warningf("exiftool path is invalid or not executable: %q (%v); disabling exiftool", Config.Integrations.Media.ExiftoolPath, err) - Config.Integrations.Media.ExiftoolPath = "" - } + if !generate && !isGoTest() { + setupFFmpegIntegration() } - if Config.Integrations.Media.ExiftoolPath == "" && !generate { - if path, err := exec.LookPath("exiftool"); err == nil && path != "" { - Config.Integrations.Media.ExiftoolPath = path - } +} + +func isGoTest() bool { + return flag.Lookup("test.v") != nil +} + +func setupFFmpegIntegration() { + maxConcurrent := Config.Server.NumImageProcessors + if maxConcurrent < 1 { + maxConcurrent = 4 } + ffmpegConcurrency := (maxConcurrent + 1) / 2 + err := ffmpeg.Initialize(context.Background(), ffmpeg.InitOptions{ + FFmpegPath: Config.Integrations.Media.FfmpegPath, + MaxConcurrent: ffmpegConcurrency, + CacheDir: Config.Server.CacheDir, + SkipHWTests: !Config.Integrations.Media.HardwareAcceleration, + HardwareAcceleration: Config.Integrations.Media.HardwareAcceleration, + }) + if err != nil { + logger.Warningf("ffmpeg unavailable: %v", err) + Env.FFmpegAvailable = false + Env.FFmpegPath = "" + Env.FFprobePath = "" + return + } + + svc := ffmpeg.Get() + if svc == nil { + Env.FFmpegAvailable = false + return + } + + Env.FFmpegAvailable = true + Env.FFmpegPath = svc.FFmpegPath() + Env.FFprobePath = svc.FFprobePath() } func setupSources(generate bool) { @@ -392,7 +440,7 @@ func setupSources(generate bool) { } // clean up the in memory source list to be accurate and unique sourceList := []*Source{} - defaultScopes := []users.SourceScope{} + defaultScopes := []users.BackendScope{} allSourceNames := []string{} if len(Config.Server.Sources) == 1 { Config.Server.Sources[0].Config.DefaultEnabled = true @@ -407,8 +455,8 @@ func setupSources(generate bool) { if ok && !slices.Contains(allSourceNames, source.Name) { sourceList = append(sourceList, source) if source.Config.DefaultEnabled { - defaultScopes = append(defaultScopes, users.SourceScope{ - Name: source.Path, + defaultScopes = append(defaultScopes, users.BackendScope{ + Path: source.Path, Scope: source.Config.DefaultUserScope, }) } @@ -419,23 +467,40 @@ func setupSources(generate bool) { } Config.UserDefaults.DefaultScopes = defaultScopes Config.Server.Sources = sourceList + finalizeConfigSourceDefaultPermissions() +} + +func finalizeConfigSourceDefaultPermissions() { + Env.ConfigSourceDefaultPermissions = nil + for _, source := range Config.Server.Sources { + if source == nil || len(source.Config.DefaultPermissionsFromConfig) == 0 { + continue + } + Env.ConfigSourceDefaultPermissions = source.Config.DefaultPermissionsFromConfig + perms := NormalizeSourceFilePermissions(source.Config.DefaultPermissions) + for flag, val := range source.Config.DefaultPermissionsFromConfig { + setSourcePermissionFlag(&perms, flag, val) + } + source.Config.DefaultPermissions = users.MarkSourceFilePermissionsConfigured(perms) + return + } } func setupUrls() { - baseurl := strings.Trim(Config.Server.BaseURL, "/") + baseurl := strings.Trim(Config.Http.BaseURL, "/") if baseurl == "" { - Config.Server.BaseURL = "/" + Config.Http.BaseURL = "/" } else { - Config.Server.BaseURL = "/" + baseurl + "/" + Config.Http.BaseURL = "/" + baseurl + "/" } - if Config.Server.BaseURL != "/" { - if Config.Server.ExternalUrl != "" { - Config.Server.ExternalUrl = strings.TrimSuffix(Config.Server.ExternalUrl, "/") + "/" - Config.Server.ExternalUrl = strings.TrimSuffix(Config.Server.ExternalUrl, Config.Server.BaseURL) + if Config.Http.BaseURL != "/" { + if Config.Http.ExternalUrl != "" { + Config.Http.ExternalUrl = strings.TrimSuffix(Config.Http.ExternalUrl, "/") + "/" + Config.Http.ExternalUrl = strings.TrimSuffix(Config.Http.ExternalUrl, Config.Http.BaseURL) } - if Config.Server.InternalUrl != "" { - Config.Server.InternalUrl = strings.TrimSuffix(Config.Server.InternalUrl, "/") + "/" - Config.Server.InternalUrl = strings.TrimSuffix(Config.Server.InternalUrl, Config.Server.BaseURL) + if Config.Http.InternalUrl != "" { + Config.Http.InternalUrl = strings.TrimSuffix(Config.Http.InternalUrl, "/") + "/" + Config.Http.InternalUrl = strings.TrimSuffix(Config.Http.InternalUrl, Config.Http.BaseURL) } } Config.Integrations.OnlyOffice.Url = strings.Trim(Config.Integrations.OnlyOffice.Url, "/") @@ -463,6 +528,9 @@ func setupAuth(generate bool) { logger.Fatalf("Error validating OIDC auth: %v", err) } logger.Info("OIDC Auth configured successfully") + if !generate { + warnOidcProxyHeaders() + } } if Config.Auth.Methods.LdapAuth.Enabled || generate { Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "ldap") @@ -530,294 +598,6 @@ func setupLogging() { } } -// migrateUserDefaults migrates deprecated UserDefaults fields to the new organized structure. -// This function maintains backwards compatibility by checking if new fields are unset and copying -// values from old deprecated fields if found. Logs warnings when old fields are migrated. -func migrateUserDefaults() { - ud := &Config.UserDefaults - hasOldFields := false - - // Helper function to check if a bool pointer is unset (nil) - isUnsetBoolPtr := func(v *bool) bool { - return v == nil - } - - // Helper function to check if a string is unset (empty) - isUnsetString := func(v string) bool { - return v == "" - } - - // Helper function to check if an int is unset (zero) - isUnsetInt := func(v int) bool { - return v == 0 - } - - // Migrate Preview-related deprecated fields - if !ud.Sidebar.DisableHideOnPreview && ud.Preview.DisableHideSidebar { - ud.Sidebar.DisableHideOnPreview = ud.Preview.DisableHideSidebar - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'preview.disableHideSidebar' to 'sidebar.disableHideOnPreview'") - } - - if !ud.FileViewer.DefaultMediaPlayer && ud.Preview.DefaultMediaPlayer { - ud.FileViewer.DefaultMediaPlayer = ud.Preview.DefaultMediaPlayer - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'preview.defaultMediaPlayer' to 'fileViewer.defaultMediaPlayer'") - } - - if isUnsetBoolPtr(ud.FileViewer.AutoplayMedia) && ud.Preview.AutoplayMedia { - autoplay := ud.Preview.AutoplayMedia - ud.FileViewer.AutoplayMedia = &autoplay - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'preview.autoplayMedia' to 'fileViewer.autoplayMedia'") - } - - if isUnsetString(ud.Preview.DisablePreviewExt) && !isUnsetString(ud.DisablePreviewExt) { - ud.Preview.DisablePreviewExt = ud.DisablePreviewExt - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'disablePreviewExt' to 'preview.disablePreviewExt'") - } - - // Migrate Sidebar fields - if !ud.Sidebar.DisableQuickToggles && ud.DisableQuickToggles { - ud.Sidebar.DisableQuickToggles = ud.DisableQuickToggles - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'disableQuickToggles' to 'sidebar.disableQuickToggles'") - } - - if !ud.Sidebar.HideFileActions && ud.HideSidebarFileActions { - ud.Sidebar.HideFileActions = ud.HideSidebarFileActions - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'hideSidebarFileActions' to 'sidebar.hideFileActions'") - } - - if !ud.Sidebar.Sticky && ud.StickySidebar { - ud.Sidebar.Sticky = ud.StickySidebar - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'stickySidebar' to 'sidebar.sticky'") - } - - if isUnsetString(ud.Listing.ViewMode) && !isUnsetString(ud.ViewMode) { - ud.Listing.ViewMode = ud.ViewMode - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'viewMode' to 'sidebar.viewMode'") - } - - if isUnsetInt(ud.Listing.GallerySize) && !isUnsetInt(ud.GallerySize) { - ud.Listing.GallerySize = ud.GallerySize - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'gallerySize' to 'sidebar.gallerySize'") - } - - if !ud.Sidebar.HideFiles && ud.HideFilesInTree { - ud.Sidebar.HideFiles = ud.HideFilesInTree - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'hideFilesInTree' to 'sidebar.hideFiles'") - } - - if isUnsetBoolPtr(ud.Sidebar.ShowTools) && ud.ShowToolsInSidebar != nil { - ud.Sidebar.ShowTools = ud.ShowToolsInSidebar - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'showToolsInSidebar' to 'sidebar.showTools'") - } - - // Migrate Listing fields - if !ud.Listing.DeleteWithoutConfirming && ud.DeleteWithoutConfirming { - ud.Listing.DeleteWithoutConfirming = ud.DeleteWithoutConfirming - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'deleteWithoutConfirming' to 'listing.deleteWithoutConfirming'") - } - - if !ud.Listing.DateFormat && ud.DateFormat { - ud.Listing.DateFormat = ud.DateFormat - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'dateFormat' to 'listing.dateFormat'") - } - - if !ud.Listing.ShowHidden && ud.ShowHidden { - ud.Listing.ShowHidden = ud.ShowHidden - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'showHidden' to 'listing.showHidden'") - } - - if !ud.Listing.QuickDownload && ud.QuickDownload { - ud.Listing.QuickDownload = ud.QuickDownload - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'quickDownload' to 'listing.quickDownload'") - } - - if !ud.Listing.ShowSelectMultiple && ud.ShowSelectMultiple { - ud.Listing.ShowSelectMultiple = ud.ShowSelectMultiple - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'showSelectMultiple' to 'listing.showSelectMultiple'") - } - - if !ud.Listing.SingleClick && ud.SingleClick { - ud.Listing.SingleClick = ud.SingleClick - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'singleClick' to 'listing.singleClick'") - } - - if isUnsetString(ud.Listing.HideFileExt) && !isUnsetString(ud.HideFileExt) { - ud.Listing.HideFileExt = ud.HideFileExt - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'hideFileExt' to 'listing.hideFileExt'") - } - - if !ud.Listing.ShowCopyPath && ud.ShowCopyPath { - ud.Listing.ShowCopyPath = ud.ShowCopyPath - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'showCopyPath' to 'listing.showCopyPath'") - } - - if !ud.Listing.DeleteAfterArchive && ud.DeleteAfterArchive { - ud.Listing.DeleteAfterArchive = ud.DeleteAfterArchive - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'deleteAfterArchive' to 'listing.deleteAfterArchive'") - } - - // Migrate FileViewer fields - if !ud.FileViewer.EditorQuickSave && ud.EditorQuickSave { - ud.FileViewer.EditorQuickSave = ud.EditorQuickSave - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'editorQuickSave' to 'fileViewer.editorQuickSave'") - } - - if isUnsetString(ud.FileViewer.DisableViewingExt) && !isUnsetString(ud.DisableViewingExt) { - ud.FileViewer.DisableViewingExt = ud.DisableViewingExt - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'disableViewingExt' to 'fileViewer.disableViewingExt'") - } - - if isUnsetString(ud.FileViewer.DisableOnlyOfficeExt) && !isUnsetString(ud.DisableOnlyOfficeExt) { - ud.FileViewer.DisableOnlyOfficeExt = ud.DisableOnlyOfficeExt - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'disableOnlyOfficeExt' to 'fileViewer.disableOnlyOfficeExt'") - } - - if !ud.FileViewer.PreferEditorForMarkdown && ud.PreferEditorForMarkdown { - ud.FileViewer.PreferEditorForMarkdown = ud.PreferEditorForMarkdown - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'preferEditorForMarkdown' to 'fileViewer.preferEditorForMarkdown'") - } - - if !ud.FileViewer.DebugOffice && ud.DebugOffice { - ud.FileViewer.DebugOffice = ud.DebugOffice - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'debugOffice' to 'fileViewer.debugOffice'") - } - - // Migrate Search fields - if !ud.Search.DisableOptions && ud.DisableSearchOptions { - ud.Search.DisableOptions = ud.DisableSearchOptions - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'disableSearchOptions' to 'search.disableOptions'") - } - - // Migrate UI fields - if isUnsetBoolPtr(ud.UI.DarkMode) && ud.DarkMode != nil { - ud.UI.DarkMode = ud.DarkMode - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'darkMode' to 'ui.darkMode'") - } - - if isUnsetString(ud.UI.ThemeColor) && !isUnsetString(ud.ThemeColor) { - ud.UI.ThemeColor = ud.ThemeColor - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'themeColor' to 'ui.themeColor'") - } - - if isUnsetString(ud.UI.CustomTheme) && !isUnsetString(ud.CustomTheme) { - ud.UI.CustomTheme = ud.CustomTheme - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'customTheme' to 'ui.customTheme'") - } - - if isUnsetString(ud.UI.Locale) && !isUnsetString(ud.Locale) { - ud.UI.Locale = ud.Locale - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'locale' to 'ui.locale'") - } - - // Migrate Account fields - if !ud.Account.LockPassword && ud.LockPassword { - ud.Account.LockPassword = ud.LockPassword - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'lockPassword' to 'account.lockPassword'") - } - - if !ud.Account.DisableSettings && ud.DisableSettings { - ud.Account.DisableSettings = ud.DisableSettings - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'disableSettings' to 'account.disableSettings'") - } - - if isUnsetString(ud.Account.LoginMethod) && !isUnsetString(ud.LoginMethod) { - ud.Account.LoginMethod = ud.LoginMethod - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'loginMethod' to 'account.loginMethod'") - } - - if !ud.Account.DisableUpdateNotifications && ud.DisableUpdateNotifications { - ud.Account.DisableUpdateNotifications = ud.DisableUpdateNotifications - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'disableUpdateNotifications' to 'account.disableUpdateNotifications'") - } - - // Migrate Account Permissions fields - if !ud.Account.Permissions.Api && ud.Permissions.Api { - ud.Account.Permissions.Api = ud.Permissions.Api - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'permissions.api' to 'account.permissions.api'") - } - - if !ud.Account.Permissions.Admin && ud.Permissions.Admin { - ud.Account.Permissions.Admin = ud.Permissions.Admin - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'permissions.admin' to 'account.permissions.admin'") - } - - if !ud.Account.Permissions.Modify && ud.Permissions.Modify { - ud.Account.Permissions.Modify = ud.Permissions.Modify - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'permissions.modify' to 'account.permissions.modify'") - } - - if !ud.Account.Permissions.Share && ud.Permissions.Share { - ud.Account.Permissions.Share = ud.Permissions.Share - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'permissions.share' to 'account.permissions.share'") - } - - if !ud.Account.Permissions.Realtime && ud.Permissions.Realtime { - ud.Account.Permissions.Realtime = ud.Permissions.Realtime - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'permissions.realtime' to 'account.permissions.realtime'") - } - - if !ud.Account.Permissions.Delete && ud.Permissions.Delete { - ud.Account.Permissions.Delete = ud.Permissions.Delete - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'permissions.delete' to 'account.permissions.delete'") - } - - if !ud.Account.Permissions.Create && ud.Permissions.Create { - ud.Account.Permissions.Create = ud.Permissions.Create - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'permissions.create' to 'account.permissions.create'") - } - - if isUnsetBoolPtr(ud.Account.Permissions.Download) && ud.Permissions.Download != nil { - ud.Account.Permissions.Download = ud.Permissions.Download - hasOldFields = true - logger.Warning("userDefaults: migrating deprecated field 'permissions.download' to 'account.permissions.download'") - } - - if hasOldFields { - logger.Warning("userDefaults: Please update your configuration to use the new organized structure. See documentation for details.") - } -} - func loadConfigWithDefaults(configFile string, generate bool) error { Config = SetDefaults(generate) @@ -832,7 +612,7 @@ func loadConfigWithDefaults(configFile string, generate bool) error { }, } loadEnvConfig() - return nil + return ResolveDatabasePaths() } // Try multi-file config first (combine all YAML files in the directory) @@ -867,6 +647,19 @@ func loadConfigWithDefaults(configFile string, generate bool) error { } } + if udRaw, ok := filteredConfig["userDefaults"]; ok { + Env.ConfigUserDefaultsSpecified = true + if udMap, ok := udRaw.(map[string]interface{}); ok { + Env.ConfigUserDefaultsSpecifiedPaths = CollectMapLeafPaths(udMap, "") + } + } + + // check if database is set in the config + val, ok := filteredConfig["server"].(map[string]interface{})["database"].(string) + if ok && val != "" { + return fmt.Errorf("old database path is set in the config, please migrate your database to SQLite") + } + // Marshal the filtered config back to YAML filteredYAML, err := yaml.Marshal(filteredConfig) if err != nil { @@ -880,10 +673,67 @@ func loadConfigWithDefaults(configFile string, generate bool) error { return fmt.Errorf("error unmarshaling YAML data: %v", err) } + if err := applyLoadedUserDefaultsFromConfig(generate); err != nil { + return err + } + + attachSourceDefaultPermissionsFromConfig(filteredConfig) + loadEnvConfig() + return ResolveDatabasePaths() +} + +// applyLoadedUserDefaultsFromConfig merges config-specified userDefaults paths onto +// SetDefaults so partial YAML (e.g. only account.permissions.share) does not zero +// unspecified sections such as preview thumbnails or fileViewer.autoplayMedia. +func applyLoadedUserDefaultsFromConfig(generate bool) error { + if !Env.ConfigUserDefaultsSpecified { + return nil + } + base := SetDefaults(generate).UserDefaults + merged, err := ApplyConfigSpecifiedPathsToUserDefaults(base, Config.UserDefaults) + if err != nil { + return fmt.Errorf("merge user defaults with config: %w", err) + } + Config.UserDefaults = merged return nil } +func attachSourceDefaultPermissionsFromConfig(raw map[string]interface{}) { + server, ok := raw["server"].(map[string]interface{}) + if !ok { + return + } + sources, ok := server["sources"].([]interface{}) + if !ok { + return + } + for i, srcRaw := range sources { + if i >= len(Config.Server.Sources) || Config.Server.Sources[i] == nil { + continue + } + src, ok := srcRaw.(map[string]interface{}) + if !ok { + continue + } + config, ok := src["config"].(map[string]interface{}) + if !ok { + continue + } + dp, ok := config["defaultPermissions"].(map[string]interface{}) + if !ok || len(dp) == 0 { + continue + } + fromConfig := make(map[string]bool, len(dp)) + for key, val := range dp { + if b, ok := val.(bool); ok { + fromConfig[key] = b + } + } + Config.Server.Sources[i].Config.DefaultPermissionsFromConfig = fromConfig + } +} + func ValidateConfig(config Settings) error { validate := validator.New() @@ -974,23 +824,31 @@ func loadEnvConfig() { } func SetDefaults(generate bool) Settings { - database := os.Getenv("FILEBROWSER_DATABASE") - if database == "" { - database = "database.db" - } - if _, err := os.Stat(database); os.IsNotExist(err) { - logger.Warning("database file could not be found. If this is unexpected, please set the FILEBROWSER_DATABASE environment variable to the correct path.") + // New SQLite database path + databaseV2 := os.Getenv("FILEBROWSER_DATABASE_PATH") + if databaseV2 == "" { + databaseV2 = "filebrowser.sqlite" } + s := Settings{ + Http: Http{ + Port: 80, + BaseURL: "", + }, Server: Server{ - Port: 80, NumImageProcessors: 4, - BaseURL: "", - Database: database, - SourceMap: map[string]*Source{}, - NameToSource: map[string]*Source{}, - CacheDir: "tmp", - MaxArchiveSizeGB: 20, + DatabaseV2: Database{ + Path: databaseV2, + Activity: ActivityConfig{ + RetentionDays: 30, + FlushIntervalSeconds: 10, + MaxBufferSize: 10000, + }, + }, + SourceMap: map[string]*Source{}, + NameToSource: map[string]*Source{}, + CacheDir: "tmp", + MaxArchiveSizeGB: 20, IndexSqlConfig: IndexSqlConfig{ WalMode: false, BatchSize: 1000, @@ -1059,7 +917,6 @@ func SetDefaults(generate bool) Settings { DisableOnlyOfficeExt: ".md .txt .pdf .html .xml", PreferEditorForMarkdown: false, DebugOffice: false, - DefaultMediaPlayer: false, }, Search: UserDefaultsSearch{ DisableOptions: false, @@ -1079,12 +936,8 @@ func SetDefaults(generate bool) Settings { Permissions: UserDefaultsAccountPermissions{ Api: false, Admin: false, - Modify: false, Share: false, Realtime: false, - Delete: false, - Create: false, - Download: boolPtr(true), // defaults to true }, LockPassword: false, DisableSettings: false, @@ -1215,11 +1068,9 @@ func loadLoginIcon() { logger.Infof("Using custom login icon: %s", Env.LoginIconPath) } -// setConditionalsMap builds optimized map structures from conditional rules for O(1) lookups +// setConditionals builds optimized map structures from source rules for O(1) lookups. func setConditionals(config *Source) { - - // Merge rules from both old format (Conditionals.ItemRules) and new format (Rules) - rules := append(config.Config.Conditionals.ItemRules, config.Config.Rules...) + rules := config.Config.Rules // Initialize the maps structure (only exact match maps for Names) resolved := ResolvedRulesConfig{ @@ -1287,12 +1138,6 @@ func setConditionals(config *Source) { if rule.IncludeRootItem != "" { resolved.IncludeRootItems[rule.IncludeRootItem] = struct{}{} } - if rule.FileNames != "" { - resolved.FileNames[rule.FileNames] = rule - } - if rule.FolderNames != "" { - resolved.FolderNames[rule.FolderNames] = rule - } if rule.FileName != "" { resolved.FileNames[rule.FileName] = rule } @@ -1325,16 +1170,12 @@ func modifyExcludeInclude(config *Source) { return normalized } - // Helper to normalize a name-based value (FileNames, FolderNames, StartsWith, EndsWith) - // These match against baseName, so no leading slash normalizeName := func(value string) string { - // Just trim slashes - names shouldn't have slashes return strings.Trim(value, "/") } // Normalize []ConditionalRule slices for full paths - // Handle both old format (Conditionals.ItemRules) and new format (Rules) - allRules := append(config.Config.Conditionals.ItemRules, config.Config.Rules...) + allRules := config.Config.Rules for i, rule := range allRules { // normalize full paths @@ -1357,15 +1198,10 @@ func modifyExcludeInclude(config *Source) { } // normalize names - allRules[i].FileNames = normalizeName(rule.FileNames) - allRules[i].FolderNames = normalizeName(rule.FolderNames) allRules[i].FileName = normalizeName(rule.FileName) allRules[i].FolderName = normalizeName(rule.FolderName) } - // Update the original slices with normalized values - itemRulesLen := len(config.Config.Conditionals.ItemRules) - config.Config.Conditionals.ItemRules = allRules[:itemRulesLen] - config.Config.Rules = allRules[itemRulesLen:] + config.Config.Rules = allRules } diff --git a/backend/common/settings/configFunctions.go b/backend/pkg/settings/configFunctions.go similarity index 90% rename from backend/common/settings/configFunctions.go rename to backend/pkg/settings/configFunctions.go index 3d0456fdaf..a795f6af7b 100644 --- a/backend/common/settings/configFunctions.go +++ b/backend/pkg/settings/configFunctions.go @@ -23,5 +23,5 @@ func CanConvertVideo(ext string) bool { } func MediaEnabled() bool { - return Env.FFmpegPath != "" && Env.FFprobePath != "" + return Env.FFmpegAvailable } diff --git a/backend/common/settings/config_test.go b/backend/pkg/settings/config_test.go similarity index 79% rename from backend/common/settings/config_test.go rename to backend/pkg/settings/config_test.go index ebc6f5033e..82835b6628 100644 --- a/backend/common/settings/config_test.go +++ b/backend/pkg/settings/config_test.go @@ -3,45 +3,11 @@ package settings import ( "os" "path/filepath" - "reflect" "testing" "github.com/google/go-cmp/cmp" ) -func TestInitialize(t *testing.T) { - type args struct { - configFile string - } - tests := []struct { - name string - args args - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - Initialize(tt.args.configFile) - }) - } -} - -func Test_setDefaults(t *testing.T) { - tests := []struct { - name string - want Settings - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := SetDefaults(true); !reflect.DeepEqual(got, tt.want) { - t.Errorf("setDefaults() = %v, want %v", got, tt.want) - } - }) - } -} - func TestConfigLoadChanged(t *testing.T) { // Create isolated test directory testDir := t.TempDir() @@ -79,8 +45,7 @@ func TestConfigLoadEnvVars(t *testing.T) { defaultConfig := SetDefaults(true) expectedKey := "MYKEY" - // mock environment variables - os.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", expectedKey) + t.Setenv("FILEBROWSER_ONLYOFFICE_SECRET", expectedKey) err = loadConfigWithDefaults(configFile, true) if err != nil { t.Fatalf("error loading config file: %v", err) @@ -101,8 +66,7 @@ server: sources: - path: "." http: - trustedHeaders: - - X-Forwarded-For + trustProxyHeaders: true disableRateLimit: true `) configFile := filepath.Join(testDir, "config.yaml") @@ -114,8 +78,8 @@ http: t.Fatalf("error loading config file: %v", err) } - if len(Config.Http.TrustedHeadersArray) != 1 || Config.Http.TrustedHeadersArray[0] != "X-Forwarded-For" { - t.Fatalf("expected trusted headers to contain X-Forwarded-For, got %v", Config.Http.TrustedHeadersArray) + if !Config.Http.TrustProxyHeaders { + t.Fatal("expected http.trustProxyHeaders to be true") } if !Config.Http.DisableRateLimit { t.Fatal("expected http.disableRateLimit to be true") @@ -144,7 +108,7 @@ func TestConfigLoadSpecificValues(t *testing.T) { globalVal interface{} newVal interface{} }{ - {"Server.Database", Config.Server.Database, defaultConfig.Server.Database}, + {"Server.DatabaseV2", Config.Server.DatabaseV2, defaultConfig.Server.DatabaseV2}, } for _, tc := range testCases { diff --git a/backend/pkg/settings/config_test_export.go b/backend/pkg/settings/config_test_export.go new file mode 100644 index 0000000000..e7cb9b91ec --- /dev/null +++ b/backend/pkg/settings/config_test_export.go @@ -0,0 +1,25 @@ +package settings + +// LoadConfigWithDefaultsForTest loads YAML and runs source wiring used in integration tests. +func LoadConfigWithDefaultsForTest(configPath string) error { + Config = SetDefaults(true) + if err := loadConfigWithDefaults(configPath, true); err != nil { + return err + } + if err := ValidateConfig(Config); err != nil { + return err + } + setupSources(true) + InitializeUserResolvers() + applyInitialSourceAccessFromLoadedConfig() + return nil +} + +func applyInitialSourceAccessFromLoadedConfig() { + for _, src := range Config.Server.Sources { + if src != nil && !src.Config.DefaultPermissions.IsUnset() { + ApplySourceAccessDefaultsToAllSources(src.Config.DefaultPermissions) + return + } + } +} diff --git a/backend/pkg/settings/config_test_helpers_test.go b/backend/pkg/settings/config_test_helpers_test.go new file mode 100644 index 0000000000..55cfa0aea4 --- /dev/null +++ b/backend/pkg/settings/config_test_helpers_test.go @@ -0,0 +1,10 @@ +package settings + +import "testing" + +func loadConfigForUserDefaultsTests(t *testing.T, configPath string) { + t.Helper() + if err := LoadConfigWithDefaultsForTest(configPath); err != nil { + t.Fatalf("LoadConfigWithDefaultsForTest(%q): %v", configPath, err) + } +} diff --git a/backend/pkg/settings/config_user_defaults_yaml_test.go b/backend/pkg/settings/config_user_defaults_yaml_test.go new file mode 100644 index 0000000000..a06612a096 --- /dev/null +++ b/backend/pkg/settings/config_user_defaults_yaml_test.go @@ -0,0 +1,248 @@ +package settings + +import ( + "os" + "path/filepath" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +const ( + proxyPlaywrightConfig = "../../../_docker/src/proxy/backend/config.yaml" + jwtPlaywrightConfig = "../../../_docker/src/jwt/backend/config.yaml" +) + +func TestYAMLConfig_proxy_newStyleUserDefaults(t *testing.T) { + loadConfigForUserDefaultsTests(t, proxyPlaywrightConfig) + + if !Config.UserDefaults.Account.Permissions.Share { + t.Fatal("expected account.permissions.share true from organized userDefaults") + } + if len(Config.Server.Sources) != 1 { + t.Fatalf("sources: %d", len(Config.Server.Sources)) + } + src := Config.Server.Sources[0] + if !src.Config.CreateUserDir || !src.Config.DefaultEnabled { + t.Fatalf("source config: createUserDir=%v defaultEnabled=%v", src.Config.CreateUserDir, src.Config.DefaultEnabled) + } + p := src.Config.DefaultPermissions + if !p.View || !p.Download || !p.Modify || !p.Create { + t.Fatalf("source defaultPermissions: %+v", p) + } + ud := Config.UserDefaults + if ud.Preview.Image == nil || !*ud.Preview.Image || ud.Preview.Video == nil || !*ud.Preview.Video { + t.Fatalf("expected preview thumbnail defaults true when omitted from yaml: image=%v video=%v", ud.Preview.Image, ud.Preview.Video) + } + if ud.FileViewer.AutoplayMedia == nil || !*ud.FileViewer.AutoplayMedia { + t.Fatalf("expected fileViewer.autoplayMedia true when omitted from yaml: %v", ud.FileViewer.AutoplayMedia) + } +} + +func TestYAMLConfig_proxy_sourceAccessDefaultsMatchYAML(t *testing.T) { + loadConfigForUserDefaultsTests(t, proxyPlaywrightConfig) + got := DefaultSourceFilePermissions() + if !got.View || !got.Download || !got.Modify || !got.Create { + t.Fatalf("DefaultSourceFilePermissions: %+v", got) + } +} + +func TestYAMLConfig_jwt_organizedUserDefaults(t *testing.T) { + loadConfigForUserDefaultsTests(t, jwtPlaywrightConfig) + + ud := Config.UserDefaults + if !ud.Account.Permissions.Share { + t.Fatal("expected account.permissions.share true") + } + if ud.UI.DarkMode == nil || !*ud.UI.DarkMode { + t.Fatal("expected ui.darkMode true") + } + if ud.Listing.SingleClick { + t.Fatal("expected listing.singleClick false") + } + if ud.Preview.Image == nil || !*ud.Preview.Image || ud.Preview.PopUp == nil || !*ud.Preview.PopUp { + t.Fatalf("preview flags: image=%v popup=%v", ud.Preview.Image, ud.Preview.PopUp) + } + got := DefaultSourceFilePermissions() + if !got.Modify || !got.Create || !got.Download { + t.Fatalf("source defaultPermissions from jwt yaml: %+v", got) + } +} + +func TestYAMLConfig_validConfig_organizedPermissions(t *testing.T) { + loadConfigForUserDefaultsTests(t, "./validConfig.yaml") + if !Config.UserDefaults.Account.Permissions.Admin { + t.Fatal("validConfig account.permissions.admin should be true") + } + if !Config.UserDefaults.Account.Permissions.Share || !Config.UserDefaults.Account.Permissions.Api { + t.Fatalf("account permissions: %+v", Config.UserDefaults.Account.Permissions) + } + if !Config.UserDefaults.Listing.SingleClick { + t.Fatal("expected listing.singleClick true") + } +} + +func TestYAMLConfig_applyUserDefaultsFrom_proxyAndJwt(t *testing.T) { + t.Run("proxy", func(t *testing.T) { + loadConfigForUserDefaultsTests(t, proxyPlaywrightConfig) + u := &users.User{FrontendUser: users.FrontendUser{Username: "demo-127.0.0.1", LoginMethod: users.LoginMethodProxy}} + ApplyUserDefaultsFrom(u, Config.UserDefaults) + if !u.Permissions.Share { + t.Fatal("Share=false after ApplyUserDefaultsFrom") + } + if len(u.BackendScopes) != 1 || u.BackendScopes[0].Scope != "/demo-127.0.0.1" { + t.Fatalf("createUserDir scope: %+v", u.BackendScopes) + } + perms := u.BackendScopes[0].Permissions + if !perms.View || !perms.Modify || !perms.Create || !perms.Download { + t.Fatalf("scope permissions: %+v", perms) + } + }) + + t.Run("jwt", func(t *testing.T) { + loadConfigForUserDefaultsTests(t, jwtPlaywrightConfig) + u := &users.User{FrontendUser: users.FrontendUser{Username: "testuser", LoginMethod: users.LoginMethodJwt}} + ApplyUserDefaultsFrom(u, Config.UserDefaults) + if !u.Permissions.Share { + t.Fatal("Share=false after ApplyUserDefaultsFrom") + } + if !u.DarkMode { + t.Fatal("expected darkMode from ui defaults") + } + if !u.Preview.Image || !u.Preview.PopUp { + t.Fatalf("preview: %+v", u.Preview) + } + if u.SingleClick { + t.Fatal("expected listing.singleClick false on user") + } + if u.BackendScopes[0].Scope != "/testuser" { + t.Fatalf("scope=%q", u.BackendScopes[0].Scope) + } + }) +} + +func TestYAMLConfig_profileMerge_matchesApplyUserDefaults(t *testing.T) { + loadConfigForUserDefaultsTests(t, jwtPlaywrightConfig) + fromDefaults := ProfileFromUserDefaults(Config.UserDefaults) + u := &users.User{FrontendUser: users.FrontendUser{Username: "merge-check"}} + ExpandProfileIntoUser(u, fromDefaults) + if !u.DarkMode || !u.Preview.Image { + t.Fatalf("ExpandProfileIntoUser: darkMode=%v preview.image=%v", u.DarkMode, u.Preview.Image) + } + u2 := &users.User{FrontendUser: users.FrontendUser{Username: "merge-check"}} + ApplyFullProfileFromDefaults(u2, Config.UserDefaults) + if u2.DarkMode != u.DarkMode || u2.Preview.Image != u.Preview.Image { + t.Fatalf("ApplyFullProfileFromDefaults diverged from ExpandProfileIntoUser") + } +} + +func TestYAMLConfig_seedSourcePermissionsAfterMigration(t *testing.T) { + loadConfigForUserDefaultsTests(t, proxyPlaywrightConfig) + defaults := DefaultSourceFilePermissions() + user := &users.User{ + Version: users.SourcePermissionsMigrationVersion, + BackendScopes: []users.BackendScope{ + {Path: Config.Server.Sources[0].Path, Scope: "/extra"}, + }, + } + if !users.SeedSourcePermissionsForPath(user, Config.Server.Sources[0].Path, defaults) { + t.Fatal("expected seed") + } + p := user.BackendScopes[0].Permissions + if !p.Modify || !p.Create { + t.Fatalf("seeded permissions: %+v", p) + } +} + +func TestLoadConfig_partialUserDefaults_preservesPreviewAndAutoplayDefaults(t *testing.T) { + loadPartialUserDefaultsConfig(t, partialUserDefaultsYAML("")) + assertPreviewDefaultsTrue(t, Config.UserDefaults) + assertAutoplayDefaultTrue(t, Config.UserDefaults) + if !Config.UserDefaults.Account.Permissions.Share { + t.Fatal("expected account.permissions.share true from config") + } +} + +func TestLoadConfig_partialUserDefaults_preservesOtherSetDefaults(t *testing.T) { + loadPartialUserDefaultsConfig(t, partialUserDefaultsYAML("")) + ud := Config.UserDefaults + if ud.UI.DarkMode == nil || !*ud.UI.DarkMode { + t.Fatalf("ui.darkMode: %v", ud.UI.DarkMode) + } + if ud.Sidebar.ShowTools == nil || !*ud.Sidebar.ShowTools { + t.Fatalf("sidebar.showTools: %v", ud.Sidebar.ShowTools) + } + if !ud.Listing.DeleteAfterArchive { + t.Fatal("expected listing.deleteAfterArchive true") + } + if !ud.Sidebar.Sticky { + t.Fatal("expected sidebar.sticky true") + } +} + +func TestLoadConfig_partialUserDefaults_explicitFalseOverride(t *testing.T) { + loadPartialUserDefaultsConfig(t, partialUserDefaultsYAML(` + preview: + image: false + fileViewer: + autoplayMedia: false +`)) + ud := Config.UserDefaults + if ud.Preview.Image == nil || *ud.Preview.Image { + t.Fatalf("preview.image: %v", ud.Preview.Image) + } + if ud.Preview.Video == nil || !*ud.Preview.Video { + t.Fatalf("preview.video should stay true: %v", ud.Preview.Video) + } + if ud.FileViewer.AutoplayMedia == nil || *ud.FileViewer.AutoplayMedia { + t.Fatalf("fileViewer.autoplayMedia: %v", ud.FileViewer.AutoplayMedia) + } +} + +func partialUserDefaultsYAML(extra string) string { + return `server: + sources: + - path: "." +userDefaults: + account: + permissions: + share: true +` + extra +} + +func loadPartialUserDefaultsConfig(t *testing.T, content string) { + t.Helper() + testDir := t.TempDir() + configFile := filepath.Join(testDir, "config.yaml") + if err := os.WriteFile(configFile, []byte(content), 0644); err != nil { + t.Fatalf("write config: %v", err) + } + if err := LoadConfigWithDefaultsForTest(configFile); err != nil { + t.Fatalf("LoadConfigWithDefaultsForTest: %v", err) + } +} + +func assertPreviewDefaultsTrue(t *testing.T, ud UserDefaults) { + t.Helper() + check := func(name string, ptr *bool) { + if ptr == nil || !*ptr { + t.Fatalf("preview.%s: %v", name, ptr) + } + } + check("image", ud.Preview.Image) + check("video", ud.Preview.Video) + check("audio", ud.Preview.Audio) + check("popup", ud.Preview.PopUp) + check("office", ud.Preview.Office) + check("folder", ud.Preview.Folder) + check("models", ud.Preview.Models) + check("motionVideoPreview", ud.Preview.MotionVideoPreview) + check("highQuality", ud.Preview.HighQuality) +} + +func assertAutoplayDefaultTrue(t *testing.T, ud UserDefaults) { + t.Helper() + if ud.FileViewer.AutoplayMedia == nil || !*ud.FileViewer.AutoplayMedia { + t.Fatalf("fileViewer.autoplayMedia: %v", ud.FileViewer.AutoplayMedia) + } +} diff --git a/backend/pkg/settings/database_paths.go b/backend/pkg/settings/database_paths.go new file mode 100644 index 0000000000..97636c0389 --- /dev/null +++ b/backend/pkg/settings/database_paths.go @@ -0,0 +1,42 @@ +package settings + +import ( + "os" + "strings" + + "github.com/gtsteffaniak/go-logger/logger" +) + +// MigrateFromDefault resolves server.database.migrateFrom from FILEBROWSER_DATABASE or database.db. +const MigrateFromDefault = "default" + +const defaultLegacyDatabasePath = "database.db" + +// ResolveDatabasePaths applies migrateFrom "default" and fills an empty SQLite path from existing defaults. +func ResolveDatabasePaths() error { + db := &Config.Server.DatabaseV2 + if strings.TrimSpace(db.Path) == "" { + if v := os.Getenv("FILEBROWSER_DATABASE_PATH"); v != "" { + db.Path = v + } else { + db.Path = "filebrowser.sqlite" + } + } + + migrateFrom := strings.TrimSpace(db.MigrateFrom) + legacyEnv := strings.TrimSpace(os.Getenv("FILEBROWSER_DATABASE")) + + if migrateFrom == MigrateFromDefault { + if legacyEnv != "" { + db.MigrateFrom = legacyEnv + } else { + db.MigrateFrom = defaultLegacyDatabasePath + } + } else if legacyEnv != "" { + logger.Fatalf( + "FILEBROWSER_DATABASE environment variable is deprecated. " + + `Remove it, or set server.database.migrateFrom to "default" to migrate from that path on first start.`, + ) + } + return nil +} diff --git a/backend/pkg/settings/database_paths_test.go b/backend/pkg/settings/database_paths_test.go new file mode 100644 index 0000000000..fabb546582 --- /dev/null +++ b/backend/pkg/settings/database_paths_test.go @@ -0,0 +1,52 @@ +package settings + +import ( + "path/filepath" + "testing" +) + +func TestResolveDatabasePaths_migrateFromDefaultUsesEnv(t *testing.T) { + boltPath := filepath.Join(t.TempDir(), "database.db") + t.Setenv("FILEBROWSER_DATABASE", boltPath) + + Config = SetDefaults(false) + Config.Server.DatabaseV2.MigrateFrom = MigrateFromDefault + + if err := ResolveDatabasePaths(); err != nil { + t.Fatalf("ResolveDatabasePaths: %v", err) + } + if Config.Server.DatabaseV2.MigrateFrom != boltPath { + t.Fatalf("migrateFrom = %q, want %q", Config.Server.DatabaseV2.MigrateFrom, boltPath) + } +} + +func TestResolveDatabasePaths_migrateFromDefaultFallsBackToDatabaseDB(t *testing.T) { + t.Setenv("FILEBROWSER_DATABASE", "") + + Config = SetDefaults(false) + Config.Server.DatabaseV2.MigrateFrom = MigrateFromDefault + + if err := ResolveDatabasePaths(); err != nil { + t.Fatalf("ResolveDatabasePaths: %v", err) + } + if Config.Server.DatabaseV2.MigrateFrom != "database.db" { + t.Fatalf("migrateFrom = %q, want database.db", Config.Server.DatabaseV2.MigrateFrom) + } +} + +func TestResolveDatabasePaths_emptyPathUsesEnvDefault(t *testing.T) { + want := filepath.Join(t.TempDir(), "custom.sqlite") + t.Setenv("FILEBROWSER_DATABASE_PATH", want) + t.Setenv("FILEBROWSER_DATABASE", "") + + Config = SetDefaults(false) + Config.Server.DatabaseV2.Path = "" + Config.Server.DatabaseV2.MigrateFrom = "" + + if err := ResolveDatabasePaths(); err != nil { + t.Fatalf("ResolveDatabasePaths: %v", err) + } + if Config.Server.DatabaseV2.Path != want { + t.Fatalf("path = %q, want %q", Config.Server.DatabaseV2.Path, want) + } +} diff --git a/backend/pkg/settings/enforced_user.go b/backend/pkg/settings/enforced_user.go new file mode 100644 index 0000000000..9849ac01b9 --- /dev/null +++ b/backend/pkg/settings/enforced_user.go @@ -0,0 +1,110 @@ +package settings + +import ( + "encoding/json" + "reflect" + "strings" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// AuthManagedEnforcementPaths are default paths owned by authentication (adminGroup, +// AdminUsername) rather than the user-defaults template. Enforcement must not block +// or overwrite auth-granted admin privileges. +var AuthManagedEnforcementPaths = map[string]struct{}{ + "account.permissions.admin": {}, +} + +// 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 { + if u == nil || u.Username == "" || u.Username == users.AnonymousUserName { + return false + } + return !u.Permissions.Admin +} + +func withoutAuthManagedEnforcementPaths(paths map[string]struct{}) map[string]struct{} { + if len(paths) == 0 { + return paths + } + out := make(map[string]struct{}, len(paths)) + for path := range paths { + if _, authManaged := AuthManagedEnforcementPaths[path]; authManaged { + continue + } + out[path] = struct{}{} + } + return out +} + +// EnforcedPathSet returns dot-paths with enforcement enabled. +func EnforcedPathSet(e UserDefaultsEnforcement) map[string]struct{} { + var paths []string + collectEnforcedPaths(reflect.ValueOf(e), "", &paths) + out := make(map[string]struct{}, len(paths)) + for _, p := range paths { + out[p] = struct{}{} + } + return out +} + +// EnforcedFieldPaths returns dot-paths for enforced settings (settings API / future Profile UI). +func EnforcedFieldPaths(e UserDefaultsEnforcement) []string { + return collectEnforcedPathsList(reflect.ValueOf(e), "") +} + +func collectEnforcedPathsList(v reflect.Value, prefix string) []string { + var paths []string + collectEnforcedPaths(v, prefix, &paths) + return paths +} + +func collectEnforcedPaths(v reflect.Value, prefix string, out *[]string) { + t := v.Type() + for i := 0; i < v.NumField(); i++ { + field := t.Field(i) + if !field.IsExported() { + continue + } + jsonTag := field.Tag.Get("json") + name := strings.Split(jsonTag, ",")[0] + if name == "" || name == "-" { + name = strings.ToLower(field.Name[:1]) + field.Name[1:] + } + path := name + if prefix != "" { + path = prefix + "." + name + } + fv := v.Field(i) + switch fv.Kind() { + case reflect.Bool: + if fv.Bool() { + *out = append(*out, path) + } + case reflect.Struct: + collectEnforcedPaths(fv, path, out) + } + } +} + +// MergeEnforcedPatchJSON merges a partial JSON patch into base enforcement. +func MergeEnforcedPatchJSON(base UserDefaultsEnforcement, patchJSON []byte) (UserDefaultsEnforcement, error) { + baseBytes, err := json.Marshal(base) + if err != nil { + return UserDefaultsEnforcement{}, err + } + mergedBytes, err := mergeUserDefaultsJSON(baseBytes, patchJSON) + if err != nil { + return UserDefaultsEnforcement{}, err + } + var merged UserDefaultsEnforcement + if err := json.Unmarshal(mergedBytes, &merged); err != nil { + return UserDefaultsEnforcement{}, err + } + return merged, nil +} + +func MergeEnforcedPatchJSONBytes(baseJSON, patchJSON []byte) ([]byte, error) { + return mergeUserDefaultsJSON(baseJSON, patchJSON) +} diff --git a/backend/pkg/settings/enforced_user_test.go b/backend/pkg/settings/enforced_user_test.go new file mode 100644 index 0000000000..164ac64028 --- /dev/null +++ b/backend/pkg/settings/enforced_user_test.go @@ -0,0 +1,222 @@ +package settings + +import ( + "errors" + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func TestEnforcementAppliesToUser(t *testing.T) { + admin := &users.User{ + FrontendUser: users.FrontendUser{Username: "admin"}, + } + admin.Permissions.Admin = true + + tests := []struct { + name string + u *users.User + want bool + }{ + {name: "nil user", u: nil, want: false}, + {name: "empty username", u: &users.User{FrontendUser: users.FrontendUser{Username: ""}}, want: false}, + {name: "anonymous", u: &users.User{FrontendUser: users.FrontendUser{Username: users.AnonymousUserName}}, want: false}, + {name: "regular user", u: &users.User{FrontendUser: users.FrontendUser{Username: "alice"}}, want: true}, + {name: "admin", u: admin, want: false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := EnforcementAppliesToUser(tc.u); got != tc.want { + t.Fatalf("EnforcementAppliesToUser() = %v, want %v", got, tc.want) + } + }) + } +} + +func TestValidateUserAgainstEnforcedDefaults_skipsAuthManagedAdmin(t *testing.T) { + u := &users.User{ + FrontendUser: users.FrontendUser{Username: "admin-from-oidc"}, + } + u.Permissions.Admin = true + defaults := UserDefaults{Account: UserDefaultsAccount{Permissions: UserDefaultsAccountPermissions{Admin: false}}} + enforced := UserDefaultsEnforcement{ + Account: UserDefaultsAccountEnforcement{ + Permissions: UserDefaultsAccountPermissionsEnforcement{Admin: true}, + }, + } + if err := ValidateUserAgainstEnforcedDefaults(u, defaults, enforced); err != nil { + t.Fatalf("auth-granted admin should not be blocked by enforced defaults: %v", err) + } +} + +func TestValidateUserAgainstEnforcedDefaults_rejectsMismatch(t *testing.T) { + u := &users.User{ + FrontendUser: users.FrontendUser{Username: "demo"}, + } + u.ShowHidden = false + defaults := UserDefaults{Listing: UserDefaultsListing{ShowHidden: true}} + enforced := UserDefaultsEnforcement{Listing: UserDefaultsListingEnforcement{ShowHidden: true}} + err := ValidateUserAgainstEnforcedDefaults(u, defaults, enforced) + if err == nil { + t.Fatal("expected mismatch error") + } + var mismatch ErrEnforcedUserValueMismatch + if !errors.As(err, &mismatch) { + t.Fatalf("expected ErrEnforcedUserValueMismatch, got %T", err) + } + u.ShowHidden = true + if err := ValidateUserAgainstEnforcedDefaults(u, defaults, enforced); err != nil { + t.Fatalf("expected match, got %v", err) + } +} + +func TestValidateUserAgainstEnforcedDefaults_skipsAdmin(t *testing.T) { + u := &users.User{ + FrontendUser: users.FrontendUser{Username: "admin"}, + } + u.Permissions.Admin = true + u.ShowHidden = false + defaults := UserDefaults{Listing: UserDefaultsListing{ShowHidden: true}} + enforced := UserDefaultsEnforcement{Listing: UserDefaultsListingEnforcement{ShowHidden: true}} + if err := ValidateUserAgainstEnforcedDefaults(u, defaults, enforced); err != nil { + t.Fatalf("admin should bypass enforced value validation: %v", err) + } +} + +func TestApplyEnforcedDefaultsFrom_onlyEnforcedSubset(t *testing.T) { + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "alice", + NonAdminEditable: users.NonAdminEditable{ + ShowHidden: false, + DarkMode: false, + }, + }, + } + defaults := UserDefaults{ + Listing: UserDefaultsListing{ShowHidden: true}, + } + enforced := UserDefaultsEnforcement{ + Listing: UserDefaultsListingEnforcement{ShowHidden: true}, + } + ApplyEnforcedDefaultsFrom(u, defaults, enforced) + if !u.ShowHidden { + t.Fatal("expected enforced ShowHidden true") + } + if u.DarkMode { + t.Fatal("expected non-enforced DarkMode unchanged") + } +} + +func TestSyncEnforcedDefaultsOntoUser_detectsChange(t *testing.T) { + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "alice", + NonAdminEditable: users.NonAdminEditable{ShowHidden: false}, + }, + } + defaults := UserDefaults{Listing: UserDefaultsListing{ShowHidden: true}} + enforced := UserDefaultsEnforcement{Listing: UserDefaultsListingEnforcement{ShowHidden: true}} + if !SyncEnforcedDefaultsOntoUser(u, defaults, enforced) { + t.Fatal("expected sync to report change") + } + if !u.ShowHidden { + t.Fatal("expected ShowHidden updated") + } + if SyncEnforcedDefaultsOntoUser(u, defaults, enforced) { + t.Fatal("expected no change when already synced") + } +} + +func TestEnforcedFieldPaths(t *testing.T) { + paths := EnforcedFieldPaths(UserDefaultsEnforcement{ + Listing: UserDefaultsListingEnforcement{ShowHidden: true}, + UI: UserDefaultsUIEnforcement{DarkMode: true}, + }) + if len(paths) != 2 { + t.Fatalf("expected 2 paths, got %v", paths) + } +} + +func TestProfileRoundTrip_expandCollapse(t *testing.T) { + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "alice", + NonAdminEditable: users.NonAdminEditable{ + ShowHidden: true, + DarkMode: true, + ShowToolsInSidebar: true, + Preview: users.Preview{ + Image: true, + DisableHideSidebar: true, + }, + }, + DisableSettings: true, + }, + } + p := ProfileFromUser(u) + var u2 users.User + u2.Username = "alice" + ExpandProfileIntoUser(&u2, p) + if !u2.ShowHidden || !u2.DarkMode || !u2.DisableSettings { + t.Fatal("round trip lost fields") + } +} + +func TestEnforcedPaths_mergeFromDefaultsProfile(t *testing.T) { + allTrue := UserDefaultsEnforcement{ + Listing: UserDefaultsListingEnforcement{ShowHidden: true}, + } + paths := EnforcedPathSet(allTrue) + patch, err := profilePatchForPaths(ProfileFromUserDefaults(UserDefaults{ + Listing: UserDefaultsListing{ShowHidden: true}, + }), paths) + if err != nil { + t.Fatal(err) + } + if !patch.Listing.ShowHidden { + t.Fatal("expected patch to carry showHidden") + } +} + +func TestValidateSelfUserUpdateNotEnforced_blocksEnforcedField(t *testing.T) { + t.Parallel() + enforced := UserDefaultsEnforcement{ + Listing: UserDefaultsListingEnforcement{DateFormat: true}, + } + regular := &users.User{FrontendUser: users.FrontendUser{Username: "alice"}} + err := ValidateSelfUserUpdateNotEnforced([]string{"dateFormat"}, enforced, regular) + if err == nil { + t.Fatal("expected error for enforced dateFormat") + } + var locked ErrEnforcedUserField + if !errors.As(err, &locked) { + t.Fatalf("expected ErrEnforcedUserField, got %T", err) + } + if locked.Field != "dateFormat" { + t.Fatalf("field: got %q", locked.Field) + } +} + +func TestValidateSelfUserUpdateNotEnforced_allowsNonEnforced(t *testing.T) { + t.Parallel() + enforced := UserDefaultsEnforcement{ + Listing: UserDefaultsListingEnforcement{DateFormat: true}, + } + regular := &users.User{FrontendUser: users.FrontendUser{Username: "alice"}} + if err := ValidateSelfUserUpdateNotEnforced([]string{"showHidden"}, enforced, regular); err != nil { + t.Fatalf("unexpected: %v", err) + } +} + +func TestValidateSelfUserUpdateNotEnforced_skipsAdmin(t *testing.T) { + t.Parallel() + enforced := UserDefaultsEnforcement{ + Listing: UserDefaultsListingEnforcement{DateFormat: true}, + } + admin := &users.User{FrontendUser: users.FrontendUser{Username: "admin"}} + admin.Permissions.Admin = true + if err := ValidateSelfUserUpdateNotEnforced([]string{"dateFormat"}, enforced, admin); err != nil { + t.Fatalf("admin should bypass enforcement validation: %v", err) + } +} diff --git a/backend/pkg/settings/enforcement_structs.go b/backend/pkg/settings/enforcement_structs.go new file mode 100644 index 0000000000..6651a3fa40 --- /dev/null +++ b/backend/pkg/settings/enforcement_structs.go @@ -0,0 +1,88 @@ +package settings + +// UserDefaultsEnforcement marks which default fields are enforced for all users (policy mask). +type UserDefaultsEnforcement struct { + Sidebar UserDefaultsSidebarEnforcement `json:"sidebar,omitempty"` + Listing UserDefaultsListingEnforcement `json:"listing,omitempty"` + Preview UserDefaultsPreviewEnforcement `json:"preview,omitempty"` + FileViewer UserDefaultsFileViewerEnforcement `json:"fileViewer,omitempty"` + Search UserDefaultsSearchEnforcement `json:"search,omitempty"` + UI UserDefaultsUIEnforcement `json:"ui,omitempty"` + FileLoading UserDefaultsFileLoadingEnforcement `json:"fileLoading,omitempty"` + Account UserDefaultsAccountEnforcement `json:"account,omitempty"` +} + +type UserDefaultsSidebarEnforcement struct { + DisableQuickToggles bool `json:"disableQuickToggles,omitempty"` + HideFileActions bool `json:"hideFileActions,omitempty"` + DisableHideOnPreview bool `json:"disableHideOnPreview,omitempty"` + Sticky bool `json:"sticky,omitempty"` + HideFiles bool `json:"hideFiles,omitempty"` + ShowTools bool `json:"showTools,omitempty"` +} + +type UserDefaultsListingEnforcement struct { + DeleteWithoutConfirming bool `json:"deleteWithoutConfirming,omitempty"` + DateFormat bool `json:"dateFormat,omitempty"` + ShowHidden bool `json:"showHidden,omitempty"` + QuickDownload bool `json:"quickDownload,omitempty"` + ShowSelectMultiple bool `json:"showSelectMultiple,omitempty"` + SingleClick bool `json:"singleClick,omitempty"` + HideFileExt bool `json:"hideFileExt,omitempty"` + ShowCopyPath bool `json:"showCopyPath,omitempty"` + DeleteAfterArchive bool `json:"deleteAfterArchive,omitempty"` + ViewMode bool `json:"viewMode,omitempty"` + GallerySize bool `json:"gallerySize,omitempty"` +} + +type UserDefaultsPreviewEnforcement struct { + Image bool `json:"image,omitempty"` + Video bool `json:"video,omitempty"` + Audio bool `json:"audio,omitempty"` + MotionVideoPreview bool `json:"motionVideoPreview,omitempty"` + Office bool `json:"office,omitempty"` + PopUp bool `json:"popup,omitempty"` + DisablePreviewExt bool `json:"disablePreviewExt,omitempty"` + Folder bool `json:"folder,omitempty"` + Models bool `json:"models,omitempty"` +} + +type UserDefaultsFileViewerEnforcement struct { + EditorQuickSave bool `json:"editorQuickSave,omitempty"` + AutoplayMedia bool `json:"autoplayMedia,omitempty"` + DisableViewingExt bool `json:"disableViewingExt,omitempty"` + DisableOnlyOfficeExt bool `json:"disableOnlyOfficeExt,omitempty"` + PreferEditorForMarkdown bool `json:"preferEditorForMarkdown,omitempty"` + DebugOffice bool `json:"debugOffice,omitempty"` +} + +type UserDefaultsSearchEnforcement struct { + DisableOptions bool `json:"disableOptions,omitempty"` +} + +type UserDefaultsUIEnforcement struct { + DarkMode bool `json:"darkMode,omitempty"` + ThemeColor bool `json:"themeColor,omitempty"` + CustomTheme bool `json:"customTheme,omitempty"` + Locale bool `json:"locale,omitempty"` +} + +type UserDefaultsFileLoadingEnforcement struct { + MaxConcurrent bool `json:"maxConcurrentUpload,omitempty"` + UploadChunkSize bool `json:"uploadChunkSizeMb,omitempty"` + DownloadChunkSize bool `json:"downloadChunkSizeMb,omitempty"` +} + +type UserDefaultsAccountEnforcement struct { + LockPassword bool `json:"lockPassword,omitempty"` + DisableSettings bool `json:"disableSettings,omitempty"` + DisableUpdateNotifications bool `json:"disableUpdateNotifications,omitempty"` + Permissions UserDefaultsAccountPermissionsEnforcement `json:"permissions,omitempty"` +} + +type UserDefaultsAccountPermissionsEnforcement struct { + Admin bool `json:"admin,omitempty"` + Api bool `json:"api,omitempty"` + Share bool `json:"share,omitempty"` + Realtime bool `json:"realtime,omitempty"` +} diff --git a/backend/common/settings/functions.go b/backend/pkg/settings/functions.go similarity index 86% rename from backend/common/settings/functions.go rename to backend/pkg/settings/functions.go index 2e4ab106f5..fb7f297a4d 100644 --- a/backend/common/settings/functions.go +++ b/backend/pkg/settings/functions.go @@ -1,8 +1,9 @@ package settings import ( - "github.com/gtsteffaniak/filebrowser/backend/database/users" - "github.com/gtsteffaniak/go-logger/logger" + "fmt" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" ) // InitializeUserResolvers sets up the global resolvers and config providers in the users package @@ -12,8 +13,7 @@ func InitializeUserResolvers() { users.SetSourceNameResolver(func(sourceName string) (string, error) { source, ok := Config.Server.NameToSource[sourceName] if !ok { - logger.Debug("Could not get scope from source name: ", sourceName) - return "", nil + return "", fmt.Errorf("source name not found: %s", sourceName) } return source.Path, nil }) @@ -53,7 +53,7 @@ func InitializeUserResolvers() { } return sources }, - GetDefaultScopes: func() []users.SourceScope { + GetDefaultScopes: func() []users.BackendScope { return Config.UserDefaults.DefaultScopes }, }) diff --git a/backend/common/settings/generator.go b/backend/pkg/settings/generator.go similarity index 93% rename from backend/common/settings/generator.go rename to backend/pkg/settings/generator.go index ecdbf5f387..ccfcd00287 100644 --- a/backend/common/settings/generator.go +++ b/backend/pkg/settings/generator.go @@ -13,6 +13,7 @@ import ( "reflect" "sort" "strings" + "sync" "golang.org/x/tools/go/packages" "gopkg.in/yaml.v3" @@ -27,6 +28,45 @@ type SecretFieldsMap map[string]map[string]bool // DeprecatedFieldsMap[typeName][fieldName] = true if field is deprecated type DeprecatedFieldsMap map[string]map[string]bool +var ( + collectCommentsCacheMu sync.RWMutex + collectCommentsCache = map[string]collectCommentsCacheEntry{} +) + +type collectCommentsCacheEntry struct { + comments CommentsMap + secrets SecretFieldsMap + deprecated DeprecatedFieldsMap +} + +func cloneCommentsMap(src CommentsMap) CommentsMap { + if src == nil { + return nil + } + out := make(CommentsMap, len(src)) + for typeName, fieldMap := range src { + out[typeName] = make(map[string]string, len(fieldMap)) + for fieldName, comment := range fieldMap { + out[typeName][fieldName] = comment + } + } + return out +} + +func cloneBoolFieldMap(src map[string]map[string]bool) map[string]map[string]bool { + if src == nil { + return nil + } + out := make(map[string]map[string]bool, len(src)) + for typeName, fieldMap := range src { + out[typeName] = make(map[string]bool, len(fieldMap)) + for fieldName, v := range fieldMap { + out[typeName][fieldName] = v + } + } + return out +} + // getStringStyle determines whether a string should be quoted in YAML func getStringStyle(value string) yaml.Style { // Always quote all strings for consistency @@ -41,42 +81,38 @@ func CollectComments(srcPath string) (CommentsMap, error) { // CollectCommentsAndSecrets parses all Go source and returns comments, secrets, and deprecated field mappings func CollectCommentsAndSecrets(srcPath string) (CommentsMap, SecretFieldsMap, DeprecatedFieldsMap, error) { - // Determine directories to parse - include settings and users packages dir := srcPath - if filepath.IsAbs(srcPath) { - // If it's an absolute path to a file, get the directory + if fi, err := os.Stat(srcPath); err == nil && !fi.IsDir() { dir = filepath.Dir(srcPath) } + settingsDir, err := filepath.Abs(dir) + if err != nil { + return nil, nil, nil, err + } - // List of directories to parse for comments + collectCommentsCacheMu.RLock() + if cached, ok := collectCommentsCache[settingsDir]; ok && shouldCacheCollectComments(settingsDir) { + collectCommentsCacheMu.RUnlock() + return cloneCommentsMap(cached.comments), cloneBoolFieldMap(cached.secrets), cloneBoolFieldMap(cached.deprecated), nil + } + collectCommentsCacheMu.RUnlock() + + // settings lives at backend/pkg/settings; users at backend/internal/database/users dirsToparse := []string{ - dir, // settings package - } - - // Add users package directory - // From common/settings, go up to backend root, then into database/users - var usersDir string - if filepath.IsAbs(dir) { - // If absolute path, calculate relative to it - usersDir = filepath.Join(filepath.Dir(filepath.Dir(dir)), "database/users") - } else { - // If relative path like "common/settings" or ".", calculate from current working directory - usersDir = "database/users" - } - if absUsersDir, err := filepath.Abs(usersDir); err == nil { - dirsToparse = append(dirsToparse, absUsersDir) + settingsDir, + filepath.Join(settingsDir, "..", "..", "internal", "database", "users"), } comments := make(CommentsMap) secrets := make(SecretFieldsMap) deprecated := make(DeprecatedFieldsMap) - // Parse each directory for _, parseDir := range dirsToparse { + if _, err := os.Stat(parseDir); err != nil { + continue + } dirComments, dirSecrets, dirDeprecated, err := parseDirectoryComments(parseDir) if err != nil { - // Log error but continue with other directories - fmt.Printf("Warning: failed to parse directory %s: %v\n", parseDir, err) continue } @@ -109,7 +145,26 @@ func CollectCommentsAndSecrets(srcPath string) (CommentsMap, SecretFieldsMap, De } } - return comments, secrets, deprecated, nil + entry := collectCommentsCacheEntry{ + comments: cloneCommentsMap(comments), + secrets: cloneBoolFieldMap(secrets), + deprecated: cloneBoolFieldMap(deprecated), + } + collectCommentsCacheMu.Lock() + if shouldCacheCollectComments(settingsDir) { + collectCommentsCache[settingsDir] = entry + } + collectCommentsCacheMu.Unlock() + + return cloneCommentsMap(comments), cloneBoolFieldMap(secrets), cloneBoolFieldMap(deprecated), nil +} + +// shouldCacheCollectComments avoids caching parses of ephemeral test fixture dirs under os.TempDir(). +func shouldCacheCollectComments(settingsDir string) bool { + if _, err := os.Stat(filepath.Join(settingsDir, "structs.go")); err == nil { + return true + } + return !strings.HasPrefix(settingsDir, os.TempDir()) } // parseDirectoryComments parses a single directory for comments, secrets, and deprecated fields. @@ -118,6 +173,9 @@ func parseDirectoryComments(dir string) (CommentsMap, SecretFieldsMap, Deprecate if err != nil { return nil, nil, nil, err } + if _, err = os.Stat(absDir); err != nil { + return nil, nil, nil, err + } var files []*ast.File cfg := &packages.Config{ @@ -493,10 +551,10 @@ func parseDefaultsFromEmbeddedYaml(embeddedYaml string) (*Settings, error) { // readEmbeddedYaml attempts to read the embedded config.generated.yaml file func readEmbeddedYaml() (string, error) { // Try to read from the relative path that should work when the binary includes embedded files - embeddedContent, err := os.ReadFile("http/dist/config.generated.yaml") + embeddedContent, err := os.ReadFile("internal/web/dist/config.generated.yaml") if err != nil { // Try alternative path - embeddedContent, err = os.ReadFile("backend/http/dist/config.generated.yaml") + embeddedContent, err = os.ReadFile("backend/internal/web/dist/config.generated.yaml") if err != nil { // Try current directory path embeddedContent, err = os.ReadFile("dist/config.generated.yaml") @@ -886,7 +944,7 @@ func GenerateYaml() { // Generate YAML with comments enabled, full config, and deprecated fields filtered // Use multi-directory comment parsing to get comments from all packages - yamlContent, err := GenerateConfigYamlWithSource(&Config, true, true, true, "common/settings") + yamlContent, err := GenerateConfigYamlWithSource(&Config, true, true, true, "pkg/settings") if err != nil { fmt.Fprintf(os.Stderr, "error generating YAML: %v\n", err) os.Exit(1) @@ -903,9 +961,9 @@ func GenerateYaml() { func GenerateConfigYaml(config *Settings, showComments bool, showFull bool, filterDeprecated bool) (string, error) { // Try different source paths to handle both runtime and test scenarios sourcePaths := []string{ - ".", // When running tests from settings directory - "../common/settings", // When running from backend directory - "common/settings", // Alternative path + ".", // When running tests from settings directory + "../pkg/settings", // When running from backend directory + "pkg/settings", // Alternative path } for _, sourcePath := range sourcePaths { diff --git a/backend/common/settings/generator_test.go b/backend/pkg/settings/generator_test.go similarity index 86% rename from backend/common/settings/generator_test.go rename to backend/pkg/settings/generator_test.go index 03aeeb6475..3fd0672772 100644 --- a/backend/common/settings/generator_test.go +++ b/backend/pkg/settings/generator_test.go @@ -2,6 +2,7 @@ package settings import ( "os" + "path/filepath" "regexp" "strings" "testing" @@ -24,23 +25,14 @@ type TestNested struct { NestedDeprecated string `json:"nestedDeprecated"` // deprecated: nested deprecated field } -// Helper to create test source files for comment parsing +// Helper to create test source files for comment parsing (isolated dir per test for go/packages). func createTestSourceFile(t *testing.T, content string) (string, func()) { - tmpFile, err := os.CreateTemp("", "test_*.go") - if err != nil { + dir := t.TempDir() + path := filepath.Join(dir, "fixture.go") + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { t.Fatal(err) } - - if _, err := tmpFile.WriteString(content); err != nil { - t.Fatal(err) - } - tmpFile.Close() - - cleanup := func() { - os.Remove(tmpFile.Name()) - } - - return tmpFile.Name(), cleanup + return path, func() {} } func TestGenerateConfigYaml_StringQuoting(t *testing.T) { @@ -68,7 +60,9 @@ type Auth struct { // Create real Settings with string values to test quoting settings := &Settings{ UserDefaults: UserDefaults{ - Locale: "en-US", + UI: UserDefaultsUI{ + Locale: "en-US", + }, }, Auth: Auth{ AdminUsername: "admin", @@ -212,8 +206,10 @@ type UserDefaults struct { trueVal := true config := &Settings{ UserDefaults: UserDefaults{ - DarkMode: &trueVal, // This matches default - Locale: "es", // This differs from default ("en") + UI: UserDefaultsUI{ + DarkMode: &trueVal, + Locale: "es", + }, }, } @@ -249,7 +245,9 @@ func TestGenerateConfigYaml_CommentsOnOff(t *testing.T) { // Use the actual settings source directory since comments work there config := &Settings{ UserDefaults: UserDefaults{ - Locale: "en", + UI: UserDefaultsUI{ + Locale: "en", + }, }, } @@ -287,9 +285,13 @@ func TestGenerateConfigYaml_IntegrationTest(t *testing.T) { trueVal := true config := &Settings{ UserDefaults: UserDefaults{ - Locale: "es", // Non-default - DarkMode: &trueVal, // Default - DisableOfficePreviewExt: ".docx .xlsx", // This is deprecated + UI: UserDefaultsUI{ + Locale: "es", + DarkMode: &trueVal, + }, + FileViewer: UserDefaultsFileViewer{ + DisableOnlyOfficeExt: ".docx .xlsx", + }, }, Auth: Auth{ Key: "secret123", // This is secret @@ -314,7 +316,7 @@ func TestGenerateConfigYaml_IntegrationTest(t *testing.T) { showFull: true, filterDeprecated: false, expectSecret: true, // secrets should be hidden - expectDeprecated: true, // deprecated should be shown + expectDeprecated: false, expectFull: true, // all fields shown expectComments: false, // no comments }, @@ -440,8 +442,10 @@ func TestGenerateConfigYaml_EdgeCases(t *testing.T) { name: "only_defaults", config: &Settings{ UserDefaults: UserDefaults{ - DarkMode: boolPtr(true), // default value - Locale: "en", // default value + UI: UserDefaultsUI{ + DarkMode: boolPtr(true), // default value + Locale: "en", // default value + }, }, }, desc: "Config with only default values", @@ -450,28 +454,42 @@ func TestGenerateConfigYaml_EdgeCases(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - // Test all combinations - for _, showComments := range []bool{false, true} { - for _, showFull := range []bool{false, true} { - for _, filterDeprecated := range []bool{false, true} { - yamlOutput, err := GenerateConfigYaml(tt.config, showComments, showFull, filterDeprecated) - if err != nil { - t.Fatalf("GenerateConfigYaml failed for %s (comments=%v, full=%v, filterDeprecated=%v): %v", - tt.desc, showComments, showFull, filterDeprecated, err) - } - - // Basic validation - should produce valid YAML structure - if yamlOutput == "" { - t.Errorf("Generated empty YAML for %s", tt.desc) - } - - // Should not contain obvious error messages (but allow "error" in log levels etc) - if strings.Contains(yamlOutput, "Error:") || strings.Contains(yamlOutput, "ERROR:") { - t.Errorf("YAML contains error for %s", tt.desc) - } - } + // Spot-check flag combinations (full cartesian product is slow without comment-parse cache) + cases := []struct { + showComments, showFull, filterDeprecated bool + }{ + {false, true, false}, + {true, true, true}, + {false, false, true}, + } + if testing.Short() { + cases = cases[:1] + } + for _, tc := range cases { + yamlOutput, err := GenerateConfigYaml(tt.config, tc.showComments, tc.showFull, tc.filterDeprecated) + if err != nil { + t.Fatalf("GenerateConfigYaml failed for %s (comments=%v, full=%v, filterDeprecated=%v): %v", + tt.desc, tc.showComments, tc.showFull, tc.filterDeprecated, err) + } + if yamlOutput == "" { + t.Errorf("Generated empty YAML for %s", tt.desc) + } + if strings.Contains(yamlOutput, "Error:") || strings.Contains(yamlOutput, "ERROR:") { + t.Errorf("YAML contains error for %s", tt.desc) } } }) } } + +func TestGenerateConfigYaml_defaultPermissionsDocumentsView(t *testing.T) { + cfg := SetDefaults(true) + cfg.Server.Sources = []*Source{{Path: ".", Config: SourceConfig{}}} + out, err := GenerateConfigYamlWithSource(&cfg, true, true, true, ".") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, "defaultPermissions:") || !strings.Contains(out, "view:") { + t.Fatalf("expected defaultPermissions to include view, got excerpt around block") + } +} diff --git a/backend/pkg/settings/http_listen.go b/backend/pkg/settings/http_listen.go new file mode 100644 index 0000000000..170643b8d2 --- /dev/null +++ b/backend/pkg/settings/http_listen.go @@ -0,0 +1,24 @@ +package settings + +import ( + "fmt" + "net" + "strconv" +) + +// HTTPListenAddr returns a TCP listen address suitable for net.Listen. +// IPv6 addresses are bracketed via net.JoinHostPort (e.g. [::1]:8080). +func HTTPListenAddr(listen string, port int) string { + if listen == "" { + listen = "0.0.0.0" + } + return net.JoinHostPort(listen, strconv.Itoa(port)) +} + +// ValidateHttpConfig checks HTTP settings that would otherwise fatal during setup. +func ValidateHttpConfig(h Http) error { + if h.Socket != "" && (h.TLSCert != "" || h.TLSKey != "") { + return fmt.Errorf("http.socket cannot be used with tlsCert or tlsKey") + } + return nil +} diff --git a/backend/pkg/settings/http_listen_test.go b/backend/pkg/settings/http_listen_test.go new file mode 100644 index 0000000000..da374c39fa --- /dev/null +++ b/backend/pkg/settings/http_listen_test.go @@ -0,0 +1,59 @@ +package settings + +import ( + "net" + "testing" +) + +func TestHTTPListenAddr(t *testing.T) { + const testPort = 38473 + tests := []struct { + name string + listen string + want string + }{ + {name: "ipv4 wildcard", listen: "0.0.0.0", want: "0.0.0.0:38473"}, + {name: "ipv4 loopback", listen: "127.0.0.1", want: "127.0.0.1:38473"}, + {name: "ipv6 loopback", listen: "::1", want: "[::1]:38473"}, + {name: "ipv6 unspecified", listen: "::", want: "[::]:38473"}, + {name: "empty listen defaults", listen: "", want: "0.0.0.0:38473"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got := HTTPListenAddr(tc.listen, testPort) + if got != tc.want { + t.Fatalf("HTTPListenAddr(%q, %d) = %q, want %q", tc.listen, testPort, got, tc.want) + } + ln, err := net.Listen("tcp", got) + if err != nil { + t.Fatalf("net.Listen(%q): %v", got, err) + } + _ = ln.Close() + }) + } +} + +func TestValidateHttpConfig_rejectsSocketWithTLS(t *testing.T) { + err := ValidateHttpConfig(Http{ + Socket: "/var/run/filebrowser.sock", + TLSCert: "/etc/ssl/cert.pem", + }) + if err == nil { + t.Fatal("expected error when socket is combined with tlsCert") + } + + err = ValidateHttpConfig(Http{ + Socket: "/var/run/filebrowser.sock", + TLSKey: "/etc/ssl/key.pem", + }) + if err == nil { + t.Fatal("expected error when socket is combined with tlsKey") + } + + if err := ValidateHttpConfig(Http{Socket: "/var/run/filebrowser.sock"}); err != nil { + t.Fatalf("socket-only config should be valid: %v", err) + } + if err := ValidateHttpConfig(Http{TLSCert: "cert.pem", TLSKey: "key.pem"}); err != nil { + t.Fatalf("tls-only config should be valid: %v", err) + } +} diff --git a/backend/common/settings/invalidConfig.yaml b/backend/pkg/settings/invalidConfig.yaml similarity index 100% rename from backend/common/settings/invalidConfig.yaml rename to backend/pkg/settings/invalidConfig.yaml diff --git a/backend/common/settings/multiconfig_test.go b/backend/pkg/settings/multiconfig_test.go similarity index 78% rename from backend/common/settings/multiconfig_test.go rename to backend/pkg/settings/multiconfig_test.go index 67ec29ee66..695480ca53 100644 --- a/backend/common/settings/multiconfig_test.go +++ b/backend/pkg/settings/multiconfig_test.go @@ -37,9 +37,10 @@ simple_auth: &simple_auth // Create main config file that references the anchors mainConfig := ` -server: +http: port: 9000 baseURL: "/test/" +server: minSearchLength: 2 sources: *simple_sources logging: *simple_logging @@ -52,9 +53,11 @@ frontend: name: "Test FileBrowser" userDefaults: - darkMode: true - viewMode: "grid" - locale: "en" + ui: + darkMode: true + locale: "en" + listing: + viewMode: "grid" ` mainPath := filepath.Join(testDir, "config.yaml") if err := os.WriteFile(mainPath, []byte(mainConfig), 0644); err != nil { @@ -69,12 +72,12 @@ userDefaults: } // Verify that values from different files were loaded correctly - if Config.Server.Port != 9000 { - t.Errorf("Expected server port 9000, got %d", Config.Server.Port) + if Config.Http.Port != 9000 { + t.Errorf("Expected HTTP port 9000, got %d", Config.Http.Port) } - if Config.Server.BaseURL != "/test/" { - t.Errorf("Expected baseURL '/test/', got '%s'", Config.Server.BaseURL) + if Config.Http.BaseURL != "/test/" { + t.Errorf("Expected baseURL '/test/', got '%s'", Config.Http.BaseURL) } if Config.Server.MinSearchLength != 2 { @@ -101,8 +104,8 @@ userDefaults: t.Errorf("Expected frontend name 'Test FileBrowser', got '%s'", Config.Frontend.Name) } - if Config.UserDefaults.ViewMode != "grid" { - t.Errorf("Expected view mode 'grid', got '%s'", Config.UserDefaults.ViewMode) + if Config.UserDefaults.Listing.ViewMode != "grid" { + t.Errorf("Expected view mode 'grid', got '%s'", Config.UserDefaults.Listing.ViewMode) } } @@ -112,9 +115,10 @@ func TestMultiConfigFallback(t *testing.T) { // Create a simple config file (no anchors) simpleConfig := ` -server: +http: port: 8080 baseURL: "/" +server: sources: - path: "/srv" @@ -137,8 +141,11 @@ frontend: } // Verify values were loaded correctly - if Config.Server.Port != 8080 { - t.Errorf("Expected server port 8080, got %d", Config.Server.Port) + if Config.Http.Port != 8080 { + t.Errorf("Expected HTTP port 8080, got %d", Config.Http.Port) + } + if Config.Http.BaseURL != "/" { + t.Errorf("Expected HTTP baseURL '/', got '%s'", Config.Http.BaseURL) } if Config.Frontend.Name != "Simple FileBrowser" { @@ -161,7 +168,6 @@ base_logging: &base_logging # Base permissions base_permissions: &base_permissions - modify: false share: false admin: false api: false @@ -174,8 +180,9 @@ base_permissions: &base_permissions // Create main config that uses references mainConfig := ` -server: +http: port: 8080 +server: sources: - path: "/srv" logging: *base_logging @@ -184,10 +191,13 @@ auth: tokenExpirationHours: 2 userDefaults: - darkMode: true - locale: "en" - viewMode: "normal" - permissions: *base_permissions + ui: + darkMode: true + locale: "en" + listing: + viewMode: "normal" + account: + permissions: *base_permissions frontend: name: "Nested Reference Test" @@ -205,6 +215,10 @@ frontend: } // Verify nested references work + if Config.Http.Port != 8080 { + t.Errorf("Expected HTTP port 8080, got %d", Config.Http.Port) + } + if len(Config.Server.Logging) == 0 { t.Error("Expected logging configuration to be loaded") } @@ -214,20 +228,24 @@ frontend: } // Verify user defaults - if Config.UserDefaults.DarkMode == nil || !*Config.UserDefaults.DarkMode { - t.Errorf("Expected dark mode true, got %v", Config.UserDefaults.DarkMode) + if Config.UserDefaults.UI.DarkMode == nil || !*Config.UserDefaults.UI.DarkMode { + t.Errorf("Expected dark mode true, got %v", Config.UserDefaults.UI.DarkMode) } - if Config.UserDefaults.Locale != "en" { - t.Errorf("Expected locale 'en', got '%s'", Config.UserDefaults.Locale) + if Config.UserDefaults.UI.Locale != "en" { + t.Errorf("Expected locale 'en', got '%s'", Config.UserDefaults.UI.Locale) } - // Verify permissions were loaded from anchor - if Config.UserDefaults.Permissions.Modify != false { - t.Errorf("Expected modify permission false (from base), got %v", Config.UserDefaults.Permissions.Modify) + if Config.UserDefaults.Listing.ViewMode != "normal" { + t.Errorf("Expected viewMode 'normal', got '%s'", Config.UserDefaults.Listing.ViewMode) } - if Config.UserDefaults.Permissions.Share != false { - t.Errorf("Expected share permission false (from base), got %v", Config.UserDefaults.Permissions.Share) + // Verify permissions were loaded from anchor into account.permissions + if Config.UserDefaults.Account.Permissions.Admin { + t.Errorf("Expected admin permission false (from base), got %v", Config.UserDefaults.Account.Permissions.Admin) + } + + if Config.UserDefaults.Account.Permissions.Share { + t.Errorf("Expected share permission false (from base), got %v", Config.UserDefaults.Account.Permissions.Share) } } diff --git a/backend/pkg/settings/settings.go b/backend/pkg/settings/settings.go new file mode 100644 index 0000000000..74221f469d --- /dev/null +++ b/backend/pkg/settings/settings.go @@ -0,0 +1,140 @@ +//go:generate go run ./tools/yaml.go -input=pkg/settings/settings.go -output=config.generated.yaml +package settings + +import ( + "crypto/rand" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// boolPtr returns a pointer to a bool value +func boolPtr(b bool) *bool { + return &b +} + +// boolValueOrDefault returns the value of a bool pointer, or the default if nil +func boolValueOrDefault(ptr *bool, defaultValue bool) bool { + if ptr != nil { + return *ptr + } + return defaultValue +} + +// ConvertPermissionsToUsers converts account permission defaults to users.Permissions (global only). +func ConvertPermissionsToUsers(p UserDefaultsAccountPermissions) users.Permissions { + return users.Permissions{ + Api: p.Api, + Admin: p.Admin, + Share: p.Share, + Realtime: p.Realtime, + } +} + +const DefaultUsersHomeBasePath = "/users" + +// AuthMethod describes an authentication method. +type AuthMethod string + +// GenerateKey generates a key of 512 bits. +func GenerateKey() ([]byte, error) { + b := make([]byte, 64) + _, err := rand.Read(b) + // Note that err == nil only if we read len(b) bytes. + if err != nil { + return nil, err + } + + return b, nil +} + +func GetSettingsConfig(nameType string, Value string) string { + return nameType + Value +} + +func AdminPerms() users.Permissions { + return users.Permissions{ + Share: true, + Admin: true, + Api: true, + Realtime: false, + } +} + +// AdminSourceFilePermissions returns full per-source file permissions for admin users. +func AdminSourceFilePermissions() users.SourceFilePermissions { + return users.SourceFilePermissions{ + View: true, + Download: true, + Modify: true, + Delete: true, + Create: true, + } +} + +// ApplyUserDefaults applies Config.UserDefaults to a user (tests and legacy callers). +func ApplyUserDefaults(u *users.User) { + ApplyUserDefaultsFrom(u, Config.UserDefaults) +} + +// ApplyUserDefaultsFrom applies the given defaults template to a user. +// Keep this in sync with [UserDefaults]: every user-facing field there should be copied +// here (except DefaultScopes, which is wired through source config rather than this helper). +func ApplyUserDefaultsFrom(u *users.User, d UserDefaults) { + ApplyFullProfileFromDefaults(u, d) + + if u.Username == "anonymous" { + return + } + + // Global permissions (admin, api, share, realtime) + u.Permissions.Api = d.Account.Permissions.Api + u.Permissions.Admin = d.Account.Permissions.Admin + u.Permissions.Share = d.Account.Permissions.Share + u.Permissions.Realtime = d.Account.Permissions.Realtime + + sourceDefaults := DefaultSourceFilePermissions() + + if len(u.BackendScopes) == 0 { + for _, source := range Config.Server.Sources { + if source.Config.DefaultEnabled { + u.BackendScopes = append(u.BackendScopes, users.BackendScope{ + Path: source.Path, + Scope: source.Config.DefaultUserScope, + }) + if len(u.SidebarLinks) == 0 { + u.SidebarLinks = append(u.SidebarLinks, users.SidebarLink{ + Name: source.Name, + Category: "source", + Target: "/", + Icon: "", + SourceName: source.Path, + }) + } + } + } + } + + if u.BackendSourcePermissions == nil { + u.BackendSourcePermissions = make(map[string]users.SourceFilePermissions) + } + for i, scope := range u.BackendScopes { + if _, ok := u.BackendSourcePermissions[scope.Path]; !ok { + perms := sourceDefaults + if u.Permissions.Admin { + perms = AdminSourceFilePermissions() + } + u.BackendScopes[i].Permissions = perms + u.BackendSourcePermissions[scope.Path] = perms + } else if u.BackendScopes[i].Permissions.IsUnset() { + u.BackendScopes[i].Permissions = u.BackendSourcePermissions[scope.Path] + } + } + + ExpandBackendScopesForCreateUserDir(u) + + if u.LoginMethod == "" && d.Account.LoginMethod != "" { + u.LoginMethod = users.LoginMethod(d.Account.LoginMethod) + } + + u.Version = users.CurrentUserMigrationVersion +} diff --git a/backend/pkg/settings/source_access.go b/backend/pkg/settings/source_access.go new file mode 100644 index 0000000000..99f871dbe3 --- /dev/null +++ b/backend/pkg/settings/source_access.go @@ -0,0 +1,129 @@ +package settings + +import ( + "encoding/json" + "fmt" + "sort" + "strings" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +const SourceDefaultsConfigLockMessage = "some source access defaults were set in the config file and cannot be changed here until an admin removes them from the config file" + +// BuiltinDefaultSourceFilePermissions is used when no source access defaults are configured. +func BuiltinDefaultSourceFilePermissions() users.SourceFilePermissions { + return users.SourceFilePermissions{ + View: true, + Download: true, + Modify: false, + Create: false, + Delete: false, + } +} + +// NormalizeSourceFilePermissions returns built-in defaults when all flags are unset. +func NormalizeSourceFilePermissions(p users.SourceFilePermissions) users.SourceFilePermissions { + if p.IsUnset() { + return BuiltinDefaultSourceFilePermissions() + } + return p +} + +// ApplySourceAccessDefaultsToAllSources copies the same template onto every configured source. +func ApplySourceAccessDefaultsToAllSources(perms users.SourceFilePermissions) { + p := users.MarkSourceFilePermissionsConfigured(NormalizeSourceFilePermissions(perms)) + for _, src := range Config.Server.Sources { + if src == nil { + continue + } + src.Config.DefaultPermissions = p + } +} + +// DefaultSourceFilePermissions returns the effective global source access defaults. +func DefaultSourceFilePermissions() users.SourceFilePermissions { + for _, src := range Config.Server.Sources { + if src == nil { + continue + } + if !src.Config.DefaultPermissions.IsUnset() { + return NormalizeSourceFilePermissions(src.Config.DefaultPermissions) + } + } + return BuiltinDefaultSourceFilePermissions() +} + +// ConfigSourceDefaultLockedPaths returns API lock paths for config-specified defaultPermissions flags. +func ConfigSourceDefaultLockedPaths() []string { + if len(Env.ConfigSourceDefaultPermissions) == 0 { + return nil + } + paths := make([]string, 0, len(Env.ConfigSourceDefaultPermissions)) + for flag := range Env.ConfigSourceDefaultPermissions { + paths = append(paths, "defaultPermissions."+flag) + } + sort.Strings(paths) + return paths +} + +// OverlayConfigSourceDefaults applies config-locked permission flags onto stored defaults. +func OverlayConfigSourceDefaults(stored users.SourceFilePermissions) users.SourceFilePermissions { + if len(Env.ConfigSourceDefaultPermissions) == 0 { + return stored + } + stored = NormalizeSourceFilePermissions(stored) + for flag, val := range Env.ConfigSourceDefaultPermissions { + setSourcePermissionFlag(&stored, flag, val) + } + return users.MarkSourceFilePermissionsConfigured(stored) +} + +func sourcePermissionsPatchWrapper(p users.SourceFilePermissions) map[string]interface{} { + return map[string]interface{}{ + "defaultPermissions": map[string]interface{}{ + "view": p.View, + "download": p.Download, + "modify": p.Modify, + "create": p.Create, + "delete": p.Delete, + }, + } +} + +// MergeSourceDefaultsPatchJSON merges a partial defaultPermissions patch into base permissions. +func MergeSourceDefaultsPatchJSON(base users.SourceFilePermissions, patchJSON []byte) (users.SourceFilePermissions, error) { + baseBytes, err := json.Marshal(sourcePermissionsPatchWrapper(base)) + if err != nil { + return users.SourceFilePermissions{}, fmt.Errorf("marshal base source defaults: %w", err) + } + mergedBytes, err := mergeUserDefaultsJSON(baseBytes, patchJSON) + if err != nil { + return users.SourceFilePermissions{}, err + } + var wrapper struct { + DefaultPermissions users.SourceFilePermissions `json:"defaultPermissions"` + } + if err := json.Unmarshal(mergedBytes, &wrapper); err != nil { + return users.SourceFilePermissions{}, fmt.Errorf("unmarshal merged source defaults: %w", err) + } + return NormalizeSourceFilePermissions(wrapper.DefaultPermissions), nil +} + +// ValidateSourceDefaultsPatchNotConfigLocked rejects patches touching config-locked permission flags. +func ValidateSourceDefaultsPatchNotConfigLocked(patchJSON []byte) error { + if len(Env.ConfigSourceDefaultPermissions) == 0 { + return nil + } + paths, err := CollectJSONPatchLeafPaths(patchJSON) + if err != nil { + return err + } + for _, path := range paths { + flag := strings.TrimPrefix(path, "defaultPermissions.") + if _, locked := Env.ConfigSourceDefaultPermissions[flag]; locked { + return fmt.Errorf("source default %q is locked from config file", path) + } + } + return nil +} diff --git a/backend/pkg/settings/source_access_config_test.go b/backend/pkg/settings/source_access_config_test.go new file mode 100644 index 0000000000..d5ee4018ec --- /dev/null +++ b/backend/pkg/settings/source_access_config_test.go @@ -0,0 +1,86 @@ +package settings + +import ( + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func TestOverlayConfigSourceDefaults(t *testing.T) { + prev := Env.ConfigSourceDefaultPermissions + t.Cleanup(func() { Env.ConfigSourceDefaultPermissions = prev }) + + Env.ConfigSourceDefaultPermissions = map[string]bool{"modify": false} + stored := users.SourceFilePermissions{View: true, Download: true, Modify: true, Create: true} + merged := OverlayConfigSourceDefaults(stored) + if merged.Modify { + t.Fatal("expected modify overlaid from config") + } + if !merged.Create { + t.Fatal("expected create unchanged") + } +} + +func TestOverlayConfigSourceDefaults_unsetStoredPartialConfig(t *testing.T) { + prev := Env.ConfigSourceDefaultPermissions + t.Cleanup(func() { Env.ConfigSourceDefaultPermissions = prev }) + + Env.ConfigSourceDefaultPermissions = map[string]bool{"modify": false} + merged := OverlayConfigSourceDefaults(users.SourceFilePermissions{}) + if !merged.View || !merged.Download { + t.Fatalf("expected built-in view/download preserved: %+v", merged) + } + if merged.Modify { + t.Fatal("expected modify false from config overlay") + } + if !merged.Configured { + t.Fatal("expected result marked configured") + } +} + +func TestValidateSourceDefaultsPatchNotConfigLocked(t *testing.T) { + prev := Env.ConfigSourceDefaultPermissions + t.Cleanup(func() { Env.ConfigSourceDefaultPermissions = prev }) + + Env.ConfigSourceDefaultPermissions = map[string]bool{"modify": false} + if err := ValidateSourceDefaultsPatchNotConfigLocked([]byte(`{"defaultPermissions":{"view":false}}`)); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if err := ValidateSourceDefaultsPatchNotConfigLocked([]byte(`{"defaultPermissions":{"modify":true}}`)); err == nil { + t.Fatal("expected config lock error") + } +} + +func TestConfigSourceDefaultLockedPaths(t *testing.T) { + prev := Env.ConfigSourceDefaultPermissions + t.Cleanup(func() { Env.ConfigSourceDefaultPermissions = prev }) + + Env.ConfigSourceDefaultPermissions = map[string]bool{"modify": false, "view": true} + paths := ConfigSourceDefaultLockedPaths() + if len(paths) != 2 { + t.Fatalf("paths=%v", paths) + } +} + +func TestAttachSourceDefaultPermissionsFromConfig(t *testing.T) { + Config.Server.Sources = []*Source{{Path: "/data", Config: SourceConfig{}}} + raw := map[string]interface{}{ + "server": map[string]interface{}{ + "sources": []interface{}{ + map[string]interface{}{ + "path": "/data", + "config": map[string]interface{}{ + "defaultPermissions": map[string]interface{}{ + "modify": false, + }, + }, + }, + }, + }, + } + attachSourceDefaultPermissionsFromConfig(raw) + got := Config.Server.Sources[0].Config.DefaultPermissionsFromConfig + if got["modify"] != false || len(got) != 1 { + t.Fatalf("DefaultPermissionsFromConfig: %+v", got) + } +} diff --git a/backend/pkg/settings/source_access_test.go b/backend/pkg/settings/source_access_test.go new file mode 100644 index 0000000000..3f54473da6 --- /dev/null +++ b/backend/pkg/settings/source_access_test.go @@ -0,0 +1,34 @@ +package settings_test + +import ( + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" + "github.com/gtsteffaniak/filebrowser/backend/pkg/settings" +) + +func TestNormalizeSourceFilePermissions_explicitDenyAllPreserved(t *testing.T) { + deny := users.DenyAllSourceFilePermissions() + got := settings.NormalizeSourceFilePermissions(deny) + if got.View || got.Download || got.Modify || got.Create || got.Delete { + t.Fatalf("deny-all should stay false: %+v", got) + } + if !got.Configured { + t.Fatal("expected configured marker on deny-all") + } +} + +func TestApplySourceAccessDefaultsToAllSources(t *testing.T) { + settings.Config = settings.SetDefaults(true) + settings.Config.Server.Sources = []*settings.Source{ + {Path: "/a", Name: "a"}, + {Path: "/b", Name: "b"}, + } + perms := users.SourceFilePermissions{View: true, Modify: true, Configured: true} + settings.ApplySourceAccessDefaultsToAllSources(perms) + for _, src := range settings.Config.Server.Sources { + if !src.Config.DefaultPermissions.View || !src.Config.DefaultPermissions.Modify { + t.Fatalf("source %s: %+v", src.Name, src.Config.DefaultPermissions) + } + } +} diff --git a/backend/pkg/settings/source_permission_enforcement.go b/backend/pkg/settings/source_permission_enforcement.go new file mode 100644 index 0000000000..39f640f9ca --- /dev/null +++ b/backend/pkg/settings/source_permission_enforcement.go @@ -0,0 +1,174 @@ +package settings + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// SourceFilePermissionsEnforcement marks which source file permission defaults are enforced for all users. +type SourceFilePermissionsEnforcement struct { + View bool `json:"view,omitempty"` + Download bool `json:"download,omitempty"` + Modify bool `json:"modify,omitempty"` + Create bool `json:"create,omitempty"` + Delete bool `json:"delete,omitempty"` +} + +type sourcePermissionField struct { + name string + field func(*users.SourceFilePermissions) *bool + enforced func(SourceFilePermissionsEnforcement) bool +} + +var sourcePermissionFields = []sourcePermissionField{ + {"view", func(p *users.SourceFilePermissions) *bool { return &p.View }, func(e SourceFilePermissionsEnforcement) bool { return e.View }}, + {"download", func(p *users.SourceFilePermissions) *bool { return &p.Download }, func(e SourceFilePermissionsEnforcement) bool { return e.Download }}, + {"modify", func(p *users.SourceFilePermissions) *bool { return &p.Modify }, func(e SourceFilePermissionsEnforcement) bool { return e.Modify }}, + {"create", func(p *users.SourceFilePermissions) *bool { return &p.Create }, func(e SourceFilePermissionsEnforcement) bool { return e.Create }}, + {"delete", func(p *users.SourceFilePermissions) *bool { return &p.Delete }, func(e SourceFilePermissionsEnforcement) bool { return e.Delete }}, +} + +// EnforcedSourcePermissionFlags returns permission flag names with enforcement enabled. +func EnforcedSourcePermissionFlags(e SourceFilePermissionsEnforcement) map[string]struct{} { + out := make(map[string]struct{}) + for _, f := range sourcePermissionFields { + if f.enforced(e) { + out[f.name] = struct{}{} + } + } + return out +} + +func sourcePermissionValue(perms users.SourceFilePermissions, flag string) bool { + for _, f := range sourcePermissionFields { + if f.name == flag { + return *f.field(&perms) + } + } + return false +} + +func applyEnforcedSourcePermissionFlag(perms *users.SourceFilePermissions, flag string, def users.SourceFilePermissions) { + for _, f := range sourcePermissionFields { + if f.name == flag { + *f.field(perms) = *f.field(&def) + return + } + } +} + +func setSourcePermissionFlag(perms *users.SourceFilePermissions, flag string, value bool) { + for _, f := range sourcePermissionFields { + if f.name == flag { + *f.field(perms) = value + return + } + } +} + +// MergeSourceEnforcedPatchJSON merges a partial JSON patch into base source permission enforcement. +func MergeSourceEnforcedPatchJSON(base SourceFilePermissionsEnforcement, patchJSON []byte) (SourceFilePermissionsEnforcement, error) { + baseBytes, err := json.Marshal(base) + if err != nil { + return SourceFilePermissionsEnforcement{}, err + } + mergedBytes, err := mergeUserDefaultsJSON(baseBytes, patchJSON) + if err != nil { + return SourceFilePermissionsEnforcement{}, err + } + var merged SourceFilePermissionsEnforcement + if err := json.Unmarshal(mergedBytes, &merged); err != nil { + return SourceFilePermissionsEnforcement{}, err + } + return merged, nil +} + +// ApplyEnforcedSourcePermissionsFrom sets enforced permission bits on every scope from defaults. +func ApplyEnforcedSourcePermissionsFrom(u *users.User, defaults users.SourceFilePermissions, enforced SourceFilePermissionsEnforcement) { + if u == nil || u.Username == users.AnonymousUserName || !EnforcementAppliesToUser(u) { + return + } + flags := EnforcedSourcePermissionFlags(enforced) + if len(flags) == 0 { + return + } + normalized := NormalizeSourceFilePermissions(defaults) + for i := range u.BackendScopes { + for flag := range flags { + applyEnforcedSourcePermissionFlag(&u.BackendScopes[i].Permissions, flag, normalized) + } + u.BackendScopes[i].Permissions = users.MarkSourceFilePermissionsConfigured(u.BackendScopes[i].Permissions) + } + users.SyncBackendSourcePermissionsMap(u) +} + +// SyncEnforcedSourcePermissionsOntoUser applies enforced defaults onto scope permissions. Returns true if changed. +func SyncEnforcedSourcePermissionsOntoUser(u *users.User, defaults users.SourceFilePermissions, enforced SourceFilePermissionsEnforcement) bool { + if u == nil || u.Username == users.AnonymousUserName || !EnforcementAppliesToUser(u) { + return false + } + flags := EnforcedSourcePermissionFlags(enforced) + if len(flags) == 0 { + return false + } + normalized := NormalizeSourceFilePermissions(defaults) + changed := false + for i := range u.BackendScopes { + before := u.BackendScopes[i].Permissions + for flag := range flags { + applyEnforcedSourcePermissionFlag(&u.BackendScopes[i].Permissions, flag, normalized) + } + u.BackendScopes[i].Permissions = users.MarkSourceFilePermissionsConfigured(u.BackendScopes[i].Permissions) + if u.BackendScopes[i].Permissions != before { + changed = true + } + } + if changed { + users.SyncBackendSourcePermissionsMap(u) + } + return changed +} + +// ValidateUserScopePermissionsAgainstEnforced rejects users whose enforced scope permissions differ from defaults. +func ValidateUserScopePermissionsAgainstEnforced(u *users.User, defaults users.SourceFilePermissions, enforced SourceFilePermissionsEnforcement) error { + if u == nil || u.Username == "" || u.Username == users.AnonymousUserName || !EnforcementAppliesToUser(u) { + return nil + } + flags := EnforcedSourcePermissionFlags(enforced) + if len(flags) == 0 { + return nil + } + normalized := NormalizeSourceFilePermissions(defaults) + for _, scope := range u.BackendScopes { + for flag := range flags { + expected := sourcePermissionValue(normalized, flag) + actual := sourcePermissionValue(scope.Permissions, flag) + if expected != actual { + return ErrEnforcedUserValueMismatch{Path: fmt.Sprintf("scopes.%s.%s", scope.Path, flag)} + } + } + } + return nil +} + +// ValidateSelfUserUpdateScopesNotEnforced rejects self-service scope updates when any permission is enforced. +func ValidateSelfUserUpdateScopesNotEnforced(which []string, enforced SourceFilePermissionsEnforcement, actor *users.User) error { + if !EnforcementAppliesToUser(actor) { + return nil + } + if len(EnforcedSourcePermissionFlags(enforced)) == 0 { + return nil + } + for _, field := range which { + f := strings.TrimSpace(field) + if strings.EqualFold(f, "scopes") || + strings.EqualFold(f, "sourcePermissions") || + strings.EqualFold(f, "backendScopes") { + return ErrEnforcedUserField{Path: "scopes"} + } + } + return nil +} diff --git a/backend/pkg/settings/source_permission_enforcement_test.go b/backend/pkg/settings/source_permission_enforcement_test.go new file mode 100644 index 0000000000..df1c57238b --- /dev/null +++ b/backend/pkg/settings/source_permission_enforcement_test.go @@ -0,0 +1,93 @@ +package settings + +import ( + "testing" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +func TestSyncEnforcedSourcePermissionsOntoUser_setsCreate(t *testing.T) { + defaults := users.SourceFilePermissions{ + View: true, Download: true, Modify: false, Create: true, Delete: false, Configured: true, + } + enforced := SourceFilePermissionsEnforcement{Create: true} + u := &users.User{ + FrontendUser: users.FrontendUser{Username: "alice"}, + BackendScopes: []users.BackendScope{{ + Path: "/data", + Permissions: users.SourceFilePermissions{View: true, Download: true, Configured: true}, + }}, + } + if !SyncEnforcedSourcePermissionsOntoUser(u, defaults, enforced) { + t.Fatal("expected scope permissions to change") + } + if !u.BackendScopes[0].Permissions.Create { + t.Fatal("expected create true on scope after enforced sync") + } + if SyncEnforcedSourcePermissionsOntoUser(u, defaults, enforced) { + t.Fatal("expected no further changes when aligned") + } +} + +func TestSyncEnforcedSourcePermissionsOntoUser_skipsAdmin(t *testing.T) { + defaults := users.SourceFilePermissions{Create: true, Configured: true} + enforced := SourceFilePermissionsEnforcement{Create: true} + u := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "admin", + Permissions: users.Permissions{Admin: true}, + }, + BackendScopes: []users.BackendScope{{ + Path: "/data", + Permissions: users.SourceFilePermissions{Configured: true}, + }}, + } + if SyncEnforcedSourcePermissionsOntoUser(u, defaults, enforced) { + t.Fatal("expected enforced source sync to skip admin users") + } +} + +func TestValidateUserScopePermissionsAgainstEnforced_rejectsMismatch(t *testing.T) { + defaults := users.SourceFilePermissions{Create: true, Configured: true} + enforced := SourceFilePermissionsEnforcement{Create: true} + u := &users.User{ + FrontendUser: users.FrontendUser{Username: "alice"}, + BackendScopes: []users.BackendScope{{ + Path: "/data", + Permissions: users.SourceFilePermissions{Create: false, Configured: true}, + }}, + } + if err := ValidateUserScopePermissionsAgainstEnforced(u, defaults, enforced); err == nil { + t.Fatal("expected validation error for mismatched create permission") + } +} + +func TestValidateSelfUserUpdateScopesNotEnforced_blocksScopesPatch(t *testing.T) { + enforced := SourceFilePermissionsEnforcement{Create: true} + actor := &users.User{FrontendUser: users.FrontendUser{Username: "alice"}} + if err := ValidateSelfUserUpdateScopesNotEnforced([]string{"scopes"}, enforced, actor); err == nil { + t.Fatal("expected self scope update to be blocked when create is enforced") + } +} + +func TestValidateSelfUserUpdateScopesNotEnforced_skipsAdmin(t *testing.T) { + enforced := SourceFilePermissionsEnforcement{Create: true} + admin := &users.User{ + FrontendUser: users.FrontendUser{ + Username: "admin", + Permissions: users.Permissions{Admin: true}, + }, + } + if err := ValidateSelfUserUpdateScopesNotEnforced([]string{"scopes"}, enforced, admin); err != nil { + t.Fatalf("expected admin self scope update to be allowed, got %v", err) + } +} + +func TestValidateSelfUserUpdateScopesNotEnforced_caseInsensitive(t *testing.T) { + enforced := SourceFilePermissionsEnforcement{Create: true} + actor := &users.User{FrontendUser: users.FrontendUser{Username: "alice"}} + if err := ValidateSelfUserUpdateScopesNotEnforced([]string{"Scopes"}, enforced, actor); err == nil { + t.Fatal("expected mixed-case scope field to be blocked") + } +} + diff --git a/backend/common/settings/storage.go b/backend/pkg/settings/storage.go similarity index 95% rename from backend/common/settings/storage.go rename to backend/pkg/settings/storage.go index 5461b53742..c4d5b75d5f 100644 --- a/backend/common/settings/storage.go +++ b/backend/pkg/settings/storage.go @@ -1,7 +1,7 @@ package settings import ( - "github.com/gtsteffaniak/filebrowser/backend/common/errors" + "github.com/gtsteffaniak/filebrowser/backend/internal/errors" ) // StorageBackend is a settings storage backend. diff --git a/backend/common/settings/structs.go b/backend/pkg/settings/structs.go similarity index 62% rename from backend/common/settings/structs.go rename to backend/pkg/settings/structs.go index de18d6452d..b3384088db 100644 --- a/backend/common/settings/structs.go +++ b/backend/pkg/settings/structs.go @@ -1,7 +1,7 @@ package settings import ( - "github.com/gtsteffaniak/filebrowser/backend/database/users" + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" ) type AllowedMethods string @@ -18,61 +18,77 @@ type Settings struct { Server Server `json:"server"` Auth Auth `json:"auth"` Frontend Frontend `json:"frontend"` - UserDefaults UserDefaults `json:"userDefaults"` + UserDefaults UserDefaults `json:"userDefaults"` // optional signup/CLI defaults; per-user values are managed in the UI Integrations Integrations `json:"integrations"` Http Http `json:"http"` } -type Http struct { - TrustedHeadersArray []string `json:"trustedHeaders"` // list of headers to trust, useful when behind a reverse proxy. - DisableRateLimit bool `json:"disableRateLimit"` // turns off built-in auth route rate limiting and failed-login lockout (default false). - // internal map of trusted headers - TrustedHeaders map[string]bool `json:"-"` +type Http struct { + Socket string `json:"socket"` // socket to listen on - eg. /var/run/filebrowser.sock + TLSKey string `json:"tlsKey"` // path to TLS key + TLSCert string `json:"tlsCert"` // path to TLS cert + Port int `json:"port"` // port to listen on + ListenAddress string `json:"listen"` // address to listen on (default: 0.0.0.0) + BaseURL string `json:"baseURL"` // base URL for the server, the subpath that the server is running on. + ExternalUrl string `json:"externalUrl"` // used by share links if set (eg. http://mydomain.com) + InternalUrl string `json:"internalUrl"` // used by integrations if set, this is the base domain that an integration service will use to communicate with filebrowser (eg. http://localhost:8080) + DisableWebDAV bool `json:"disableWebDAV"` // disable webdav support (default: false) + TrustProxyHeaders bool `json:"trustProxyHeaders"` // honor X-Forwarded-* and X-Real-IP from a reverse proxy (default: false) + DisableRateLimit bool `json:"disableRateLimit"` // turns off built-in auth route rate limiting and failed-login lockout (default false). } type Environment struct { - IsPlaywright bool `json:"-"` - IsDevMode bool `json:"-"` - IsFirstLoad bool `json:"-"` // used internally to track if this is the first load of the application - MuPdfAvailable bool `json:"-"` // used internally if compiled with mupdf support - EmbeddedFs bool `json:"-"` // used internally if compiled with embedded fs support - FFmpegPath string `json:"-"` - FFprobePath string `json:"-"` - LoginIconPath string `json:"-"` // resolved login icon path (filesystem or embedded) - LoginIconIsCustom bool `json:"-"` // true if login icon is from custom filesystem path - LoginIconEmbeddedPath string `json:"-"` // embedded asset path for default icon - FaviconPath string `json:"-"` // resolved favicon path (filesystem or embedded) - FaviconIsCustom bool `json:"-"` // true if favicon is from custom filesystem path - FaviconEmbeddedPath string `json:"-"` // embedded asset path for default favicon + IsPlaywright bool `json:"-"` + IsDevMode bool `json:"-"` + IsFirstLoad bool `json:"-"` // used internally to track if this is the first load of the application + ConfigUserDefaultsSpecified bool `json:"-"` // true when the config file contained a userDefaults section + ConfigUserDefaultsSpecifiedPaths []string `json:"-"` // dot-paths explicitly set under userDefaults in config + // ConfigSourceDefaultPermissions maps permission flags explicitly set in config defaultPermissions (e.g. view -> true). + ConfigSourceDefaultPermissions map[string]bool `json:"-"` + MuPdfAvailable bool `json:"-"` // used internally if compiled with mupdf support + EmbeddedFs bool `json:"-"` // used internally if compiled with embedded fs support + FFmpegPath string `json:"-"` + FFprobePath string `json:"-"` + FFmpegAvailable bool `json:"-"` + LoginIconPath string `json:"-"` // resolved login icon path (filesystem or embedded) + LoginIconIsCustom bool `json:"-"` // true if login icon is from custom filesystem path + LoginIconEmbeddedPath string `json:"-"` // embedded asset path for default icon + FaviconPath string `json:"-"` // resolved favicon path (filesystem or embedded) + FaviconIsCustom bool `json:"-"` // true if favicon is from custom filesystem path + FaviconEmbeddedPath string `json:"-"` // embedded asset path for default favicon } type Server struct { MinSearchLength int `json:"minSearchLength" yaml:"minSearchLength"` // minimum length of search query to begin searching (default: 3) DisableUpdateCheck bool `json:"disableUpdateCheck"` // disables backend update check service NumImageProcessors int `json:"numImageProcessors"` // number of concurrent image processing jobs used to create previews, default is 4. - Socket string `json:"socket"` // socket to listen on - eg. /var/run/filebrowser.sock - TLSKey string `json:"tlsKey"` // path to TLS key - TLSCert string `json:"tlsCert"` // path to TLS cert DisablePreviews bool `json:"disablePreviews"` // disable all previews thumbnails, simple icons will be used DisableResize bool `json:"disablePreviewResize"` // disable resizing of previews for faster loading over slow connections DisableTypeDetectionByHeader bool `json:"disableTypeDetectionByHeader"` // disable type detection by header, useful if filesystem is slow. - Port int `json:"port"` // port to listen on - ListenAddress string `json:"listen"` // address to listen on (default: 0.0.0.0) - BaseURL string `json:"baseURL"` // base URL for the server, the subpath that the server is running on. Logging []LogConfig `json:"logging" yaml:"logging"` - Database string `json:"database"` // path to the database file Sources []*Source `json:"sources" validate:"required,dive"` - ExternalUrl string `json:"externalUrl"` // used by share links if set (eg. http://mydomain.com) - InternalUrl string `json:"internalUrl"` // used by integrations if set, this is the base domain that an integration service will use to communicate with filebrowser (eg. http://localhost:8080) CacheDir string `json:"cacheDir"` // path to the cache directory, used for thumbnails and other cached files CacheDirCleanup bool `json:"cacheDirCleanup"` // whether to automatically cleanup the cache directory. Note: docker must also mount a persistent volume to persist the cache (default: false) MaxArchiveSizeGB int64 `json:"maxArchiveSize"` // maximum archive/unarchive size in GB. 0 means no limit. (default: 20) Filesystem Filesystem `json:"filesystem"` // filesystem settings IndexSqlConfig IndexSqlConfig `json:"indexSqlConfig"` // Index database SQL configuration - DisableWebDAV bool `json:"disableWebDAV"` // disable webdav support (default: false) // not exposed to config SourceMap map[string]*Source `json:"-" validate:"omitempty"` // uses realpath as key NameToSource map[string]*Source `json:"-" validate:"omitempty"` // uses name as key + DatabaseV2 Database `json:"database"` // SQLite database configuration +} + +type ActivityConfig struct { + Disabled bool `json:"disabled"` // disable semantic activity audit logging (default: false) + RetentionDays int `json:"retentionDays"` // purge activity rows older than this many days (default 30) + FlushIntervalSeconds int `json:"flushIntervalSeconds"` // buffer flush interval in seconds (default 10) + MaxBufferSize int `json:"maxBufferSize"` // max in-memory buffer before immediate flush (default 10000) +} + +type Database struct { + Path string `json:"path"` // path to SQLite database file + MigrateFrom string `json:"migrateFrom"` // path to legacy database file for migration (optional) + Activity ActivityConfig `json:"activity"` // activity audit logging configuration } type Filesystem struct { @@ -117,7 +133,7 @@ type Media struct { Convert FfmpegConvert `json:"convert"` // config for ffmpeg conversion settings Debug bool `json:"debug"` // output ffmpeg stdout for media integration -- careful can produces lots of output! ExtractEmbeddedSubtitles bool `json:"extractEmbeddedSubtitles"` // extract embedded subtitles from media files - ExiftoolPath string `json:"exiftoolPath"` // path to exiftool executable + HardwareAcceleration bool `json:"hardwareAcceleration"` // enable hardware acceleration for ffmpeg if available } type FfmpegConvert struct { @@ -209,28 +225,23 @@ type Source struct { } type SourceConfig struct { - DenyByDefault bool `json:"denyByDefault,omitempty"` // deny access unless an "allow" access rule was specifically created. - Private bool `json:"private"` // designate as source as private -- currently just means no sharing permitted. - ReadOnly bool `json:"readOnly,omitempty"` // read-only source, changes from the UI, webdav, and API will be disabled. - Disabled bool `json:"disabled,omitempty"` // disable the source, this is useful so you don't need to remove it from the config file - IndexingInterval uint32 `json:"indexingIntervalMinutes,omitempty"` // deprecated: create a rule with indexingIntervalMinutes to set the indexing interval for this source - Conditionals ConditionalFilter `json:"conditionals"` // deprecated: use source.rules instead - Rules []ConditionalRule `json:"rules"` // list of item rules to apply to specific paths - DefaultUserScope string `json:"defaultUserScope"` // defaults to root of index "/" should match folders under path - DefaultEnabled bool `json:"defaultEnabled"` // should be added as a default source for new users? - CreateUserDir bool `json:"createUserDir"` // create a user directory for each user under defaultUserScope + username - UseLogicalSize bool `json:"useLogicalSize"` // calculate sizes based on logical size instead of disk utilization (du -sh), folders will be 0 bytes when empty. + DenyByDefault bool `json:"denyByDefault,omitempty"` // deny access unless an "allow" access rule was specifically created. + Private bool `json:"private"` // designate as source as private -- currently just means no sharing permitted. + ReadOnly bool `json:"readOnly,omitempty"` // read-only source, changes from the UI, webdav, and API will be disabled. + Disabled bool `json:"disabled,omitempty"` // disable the source, this is useful so you don't need to remove it from the config file + Rules []ConditionalRule `json:"rules"` // list of item rules to apply to specific paths + DefaultUserScope string `json:"defaultUserScope"` // defaults to root of index "/" should match folders under path + DefaultEnabled bool `json:"defaultEnabled"` // should be added as a default source for new users? + CreateUserDir bool `json:"createUserDir"` // create a user directory for each user under defaultUserScope + username + UseLogicalSize bool `json:"useLogicalSize"` // calculate sizes based on logical size instead of disk utilization (du -sh), folders will be 0 bytes when empty. + // DefaultPermissions is the template for new user scopes on this source (also synced globally via Access settings). + DefaultPermissions users.SourceFilePermissions `json:"defaultPermissions,omitempty" yaml:"defaultPermissions,omitempty"` + // DefaultPermissionsFromConfig holds permission flags explicitly set under defaultPermissions in config YAML. + DefaultPermissionsFromConfig map[string]bool `json:"-"` // hidden but used internally - optimized map lookups for conditional rules ResolvedRules ResolvedRulesConfig `json:"-"` } -type ConditionalFilter struct { - Hidden bool `json:"hidden"` // deprecated: use ignoreHidden instead. eg, FolderPath: "/" and ignoreHidden: true will exclude hidden files and folders under the root folder. - IgnoreHidden bool `json:"ignoreHidden"` // deprecated: use ignoreHidden instead. eg, FolderPath: "/" and ignoreHidden: true will exclude hidden files and folders under the root folder. - ZeroSizeFolders bool `json:"ignoreZeroSizeFolders"` // deprecated: use ignoreZeroSizeFolders instead. eg, FolderPath: "/" and ignoreZeroSizeFolders: true will ignore folders with 0 size under the root folder. - ItemRules []ConditionalRule `json:"rules"` // list of item rules to apply to specific paths -} - type ConditionalRule struct { NeverWatchPath string `json:"neverWatchPath"` // index the folder in the first pass to get included in search, but never re-indexed. IncludeRootItem string `json:"includeRootItem"` // include only these items at root folder level @@ -240,8 +251,6 @@ type ConditionalRule struct { FolderEndsWith string `json:"folderEndsWith"` // (global) exclude folders that end with these suffixes. Eg. ".thumbnails" or ".git" FolderPath string `json:"folderPath"` // (global) exclude folders that match this path. Eg. "/path/to/folder" or "/path/to/folder/subfolder" FilePath string `json:"filePath"` // (global) exclude files that match this path. Eg. "/path/to/file.txt" or "/path/to/file.txt/subfile.txt" - FileNames string `json:"fileNames"` // deprecated: exclude files that match these names. Eg. "file.txt" or "test.csv" - FolderNames string `json:"folderNames"` // deprecated: exclude folders that match these names. Eg. "folder" or "subfolder" FileName string `json:"fileName"` // (global) exclude files that match these names. Eg. "file.txt" or "test.csv" FolderName string `json:"folderName"` // (global) exclude folders that match these names. Eg. "folder" or "subfolder" @@ -251,8 +260,8 @@ type ConditionalRule struct { IgnoreSymlinks bool `json:"ignoreSymlinks"` // Excludes symbolic links } -// ConditionalMaps provides O(1) lookup performance for conditional rules -// Maps are built from ConditionalFilter during initialization +// ResolvedRulesConfig provides O(1) lookup performance for conditional rules. +// Maps are built from Rules during initialization. type ResolvedRulesConfig struct { // Exact match maps - O(1) lookup (only for names, not StartsWith/EndsWith) FileNames map[string]ConditionalRule // key: file name @@ -316,20 +325,14 @@ type ExternalLink struct { Url string `json:"url" validate:"required"` // the url to link to } -// UserDefaultsPermissions holds permission settings with pointer types for defaults -type UserDefaultsPermissions struct { - Api bool `json:"api"` // deprecated: use account.permissions.api instead. allow api access - Admin bool `json:"admin"` // deprecated: use account.permissions.admin instead. allow admin access - Modify bool `json:"modify"` // deprecated: use account.permissions.modify instead. allow modifying files - Share bool `json:"share"` // deprecated: use account.permissions.share instead. allow sharing files - Realtime bool `json:"realtime"` // deprecated: use account.permissions.realtime instead. allow realtime updates - Delete bool `json:"delete"` // deprecated: use account.permissions.delete instead. allow deleting files - Create bool `json:"create"` // deprecated: use account.permissions.create instead. allow creating or uploading files - Download *bool `json:"download"` // deprecated: use account.permissions.download instead. allow downloading files +// UserDefaultsAccountPermissions holds global permission settings (not per-source file operations). +type UserDefaultsAccountPermissions struct { + Api bool `json:"api"` // allow api access + Admin bool `json:"admin"` // allow admin access + Share bool `json:"share"` // allow sharing files + Realtime bool `json:"realtime"` // allow realtime updates } -// New organized structures for UserDefaults - // UserDefaultsSidebar holds sidebar-related settings type UserDefaultsSidebar struct { DisableQuickToggles bool `json:"disableQuickToggles"` // disable the quick toggles in the sidebar @@ -367,10 +370,6 @@ type UserDefaultsPreview struct { HighQuality *bool `json:"highQuality"` // high quality preview thumbnails Folder *bool `json:"folder"` // show thumbnails for folders that have previewable contents Models *bool `json:"models"` // show live thumbnails for 3D models files - // deprecated fields - DisableHideSidebar bool `json:"disableHideSidebar"` // deprecated: use sidebar.disableHideOnPreview instead. disable the hide sidebar preview for previews and editors - DefaultMediaPlayer bool `json:"defaultMediaPlayer"` // deprecated: use fileViewer.defaultMediaPlayer instead. disable the styled feature-rich media player for browser default - AutoplayMedia bool `json:"autoplayMedia"` // deprecated: use fileViewer.autoplayMedia instead. autoplay media files in preview } // UserDefaultsFileViewer holds file viewer/editor settings @@ -381,7 +380,6 @@ type UserDefaultsFileViewer struct { DisableOnlyOfficeExt string `json:"disableOnlyOfficeExt"` // list of file extensions to disable onlyoffice editor for PreferEditorForMarkdown bool `json:"preferEditorForMarkdown"` // prefer editor first for markdown files instead of the Markdown Viewer DebugOffice bool `json:"debugOffice"` // debug onlyoffice editor - DefaultMediaPlayer bool `json:"defaultMediaPlayer"` // disable the styled feature-rich media player for browser default } // UserDefaultsSearch holds search-related settings @@ -407,63 +405,15 @@ type UserDefaultsAccount struct { DisableUpdateNotifications bool `json:"disableUpdateNotifications"` // disable update notifications banner for admin users } -// UserDefaultsAccountPermissions holds permission settings -type UserDefaultsAccountPermissions struct { - Api bool `json:"api"` // allow api access - Admin bool `json:"admin"` // allow admin access - Modify bool `json:"modify"` // allow modifying files - Share bool `json:"share"` // allow sharing files - Realtime bool `json:"realtime"` // allow realtime updates - Delete bool `json:"delete"` // allow deleting files - Create bool `json:"create"` // allow creating or uploading files - Download *bool `json:"download"` // allow downloading files -} - // UserDefaults is a type that holds the default values for some fields on User. type UserDefaults struct { - // New organized structure - Sidebar UserDefaultsSidebar `json:"sidebar,omitempty"` - Listing UserDefaultsListing `json:"listing,omitempty"` - Preview UserDefaultsPreview `json:"preview,omitempty"` - FileViewer UserDefaultsFileViewer `json:"fileViewer,omitempty"` - Search UserDefaultsSearch `json:"search,omitempty"` - UI UserDefaultsUI `json:"ui,omitempty"` - FileLoading users.FileLoading `json:"fileLoading,omitempty"` - Account UserDefaultsAccount `json:"account,omitempty"` - - // Deprecated fields - kept for backwards compatibility - EditorQuickSave bool `json:"editorQuickSave,omitempty"` // deprecated: use fileViewer.editorQuickSave instead - HideSidebarFileActions bool `json:"hideSidebarFileActions,omitempty"` // deprecated: use sidebar.hideSidebarFileActions instead - DisableQuickToggles bool `json:"disableQuickToggles,omitempty"` // deprecated: use sidebar.disableQuickToggles instead - DisableSearchOptions bool `json:"disableSearchOptions,omitempty"` // deprecated: use search.disableOptions instead - StickySidebar bool `json:"stickySidebar,omitempty"` // deprecated: use sidebar.stickySidebar instead - HideFilesInTree bool `json:"hideFilesInTree,omitempty"` // deprecated: use sidebar.hideFilesInTree instead - DarkMode *bool `json:"darkMode,omitempty"` // deprecated: use sidebar.darkMode instead - Locale string `json:"locale,omitempty"` // deprecated: use ui.locale instead - ViewMode string `json:"viewMode,omitempty"` // deprecated: use sidebar.viewMode instead - SingleClick bool `json:"singleClick,omitempty"` // deprecated: use sidebar.singleClick instead - ShowHidden bool `json:"showHidden,omitempty"` // deprecated: use listing.showHidden instead - HideFileExt string `json:"hideFileExt,omitempty"` // deprecated: use listing.hideFileExt instead - DateFormat bool `json:"dateFormat,omitempty"` // deprecated: use listing.dateFormat instead - GallerySize int `json:"gallerySize,omitempty"` // deprecated: use sidebar.gallerySize instead - ThemeColor string `json:"themeColor,omitempty"` // deprecated: use ui.themeColor instead - QuickDownload bool `json:"quickDownload,omitempty"` // deprecated: use listing.quickDownload instead - DisablePreviewExt string `json:"disablePreviewExt,omitempty"` // deprecated: use preview.disablePreviewExt instead - DisableViewingExt string `json:"disableViewingExt,omitempty"` // deprecated: use fileViewer.disableViewingExt instead - LockPassword bool `json:"lockPassword,omitempty"` // deprecated: use account.lockPassword instead - DisableSettings bool `json:"disableSettings,omitempty"` // deprecated: use account.disableSettings instead - DefaultScopes []users.SourceScope `json:"-"` - Permissions UserDefaultsPermissions `json:"permissions,omitempty"` // deprecated: use account.permissions instead - LoginMethod string `json:"loginMethod,omitempty"` // deprecated: use account.loginMethod instead - DisableUpdateNotifications bool `json:"disableUpdateNotifications,omitempty"` // deprecated: use account.disableUpdateNotifications instead - DeleteWithoutConfirming bool `json:"deleteWithoutConfirming,omitempty"` // deprecated: use listing.deleteWithoutConfirming instead - DeleteAfterArchive bool `json:"deleteAfterArchive,omitempty"` // deprecated: use listing.deleteAfterArchive instead - DisableOfficePreviewExt string `json:"disableOfficePreviewExt,omitempty"` // deprecated: use disablePreviewExt instead - DisableOnlyOfficeExt string `json:"disableOnlyOfficeExt,omitempty"` // deprecated: use fileViewer.disableOnlyOfficeExt instead - CustomTheme string `json:"customTheme,omitempty"` // deprecated: use ui.customTheme instead - ShowSelectMultiple bool `json:"showSelectMultiple,omitempty"` // deprecated: use listing.showSelectMultiple instead - ShowToolsInSidebar *bool `json:"showToolsInSidebar,omitempty"` // deprecated: use sidebar.showToolsInSidebar instead - DebugOffice bool `json:"debugOffice,omitempty"` // deprecated: use fileViewer.debugOffice instead - PreferEditorForMarkdown bool `json:"preferEditorForMarkdown,omitempty"` // deprecated: use fileViewer.preferEditorForMarkdown instead - ShowCopyPath bool `json:"showCopyPath,omitempty"` // deprecated: use listing.showCopyPath instead + Sidebar UserDefaultsSidebar `json:"sidebar,omitempty"` + Listing UserDefaultsListing `json:"listing,omitempty"` + Preview UserDefaultsPreview `json:"preview,omitempty"` + FileViewer UserDefaultsFileViewer `json:"fileViewer,omitempty"` + Search UserDefaultsSearch `json:"search,omitempty"` + UI UserDefaultsUI `json:"ui,omitempty"` + FileLoading users.FileLoading `json:"fileLoading,omitempty"` + Account UserDefaultsAccount `json:"account,omitempty"` + DefaultScopes []users.BackendScope `json:"-"` } diff --git a/backend/common/settings/styling.go b/backend/pkg/settings/styling.go similarity index 100% rename from backend/common/settings/styling.go rename to backend/pkg/settings/styling.go diff --git a/backend/pkg/settings/user_defaults_config_lock.go b/backend/pkg/settings/user_defaults_config_lock.go new file mode 100644 index 0000000000..1d26414752 --- /dev/null +++ b/backend/pkg/settings/user_defaults_config_lock.go @@ -0,0 +1,16 @@ +package settings + +import "fmt" + +// UserDefaultsConfigLockMessage explains partial config locking in the admin UI. +const UserDefaultsConfigLockMessage = "some user defaults were set in the config file and cannot be changed here until an admin removes them from the config file" + +// UserDefaultsFieldConfigLockMessage formats a single-path lock error. +func UserDefaultsFieldConfigLockMessage(path string) string { + return fmt.Sprintf("user default %q is locked from config file", path) +} + +// UserDefaultsLockedFromConfig reports whether any userDefaults paths were set in config. +func UserDefaultsLockedFromConfig() bool { + return len(Env.ConfigUserDefaultsSpecifiedPaths) > 0 +} diff --git a/backend/pkg/settings/user_defaults_config_paths.go b/backend/pkg/settings/user_defaults_config_paths.go new file mode 100644 index 0000000000..d6546bfec6 --- /dev/null +++ b/backend/pkg/settings/user_defaults_config_paths.go @@ -0,0 +1,193 @@ +package settings + +import ( + "encoding/json" + "fmt" + "reflect" + "strings" +) + +// CollectMapLeafPaths returns dot-paths for explicitly set leaves in a nested map. +func CollectMapLeafPaths(raw map[string]interface{}, prefix string) []string { + if raw == nil { + return nil + } + var paths []string + collectMapLeafPaths(raw, prefix, &paths) + return paths +} + +func collectMapLeafPaths(raw map[string]interface{}, prefix string, out *[]string) { + for key, val := range raw { + path := key + if prefix != "" { + path = prefix + "." + key + } + child, ok := val.(map[string]interface{}) + if ok && len(child) > 0 { + collectMapLeafPaths(child, path, out) + continue + } + if ok && len(child) == 0 { + *out = append(*out, path) + continue + } + *out = append(*out, path) + } +} + +// ConfigSpecifiedUserDefaultPaths returns dot-paths explicitly set in config userDefaults. +func ConfigSpecifiedUserDefaultPaths() []string { + if len(Env.ConfigUserDefaultsSpecifiedPaths) == 0 { + return nil + } + out := make([]string, len(Env.ConfigUserDefaultsSpecifiedPaths)) + copy(out, Env.ConfigUserDefaultsSpecifiedPaths) + return out +} + +// ConfigSpecifiedUserDefaultPathSet returns a set of config-specified user default paths. +func ConfigSpecifiedUserDefaultPathSet() map[string]struct{} { + paths := Env.ConfigUserDefaultsSpecifiedPaths + out := make(map[string]struct{}, len(paths)) + for _, p := range paths { + out[p] = struct{}{} + } + return out +} + +// IsUserDefaultLockedFromConfig reports whether path was explicitly set in config userDefaults. +func IsUserDefaultLockedFromConfig(path string) bool { + _, ok := ConfigSpecifiedUserDefaultPathSet()[path] + return ok +} + +// ApplyEnforcementFromPaths sets enforcement flags for config-specified paths. +func ApplyEnforcementFromPaths(enforced *UserDefaultsEnforcement, paths []string) { + if enforced == nil || len(paths) == 0 { + return + } + pathSet := make(map[string]struct{}, len(paths)) + for _, p := range paths { + pathSet[p] = struct{}{} + } + for path := range pathSet { + _ = setEnforcementBoolAtPath(enforced, path, true) + } +} + +func setEnforcementBoolAtPath(enforced *UserDefaultsEnforcement, path string, value bool) error { + if !value { + return nil + } + parts := strings.Split(path, ".") + v := reflect.ValueOf(enforced).Elem() + for i, part := range parts { + if v.Kind() != reflect.Struct { + return fmt.Errorf("invalid enforcement path %q", path) + } + fieldIdx, ok := structFieldIndexByJSONTag(v, part) + if !ok { + return fmt.Errorf("unknown enforcement path %q", path) + } + v = v.Field(fieldIdx) + if i == len(parts)-1 { + if v.Kind() != reflect.Bool { + return fmt.Errorf("enforcement path %q is not a bool field", path) + } + v.SetBool(true) + return nil + } + } + return fmt.Errorf("invalid enforcement path %q", path) +} + +func structFieldIndexByJSONTag(v reflect.Value, name string) (int, bool) { + t := v.Type() + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + if !field.IsExported() { + continue + } + jsonTag := field.Tag.Get("json") + tagName := strings.Split(jsonTag, ",")[0] + if tagName == "" || tagName == "-" { + tagName = strings.ToLower(field.Name[:1]) + field.Name[1:] + } + if tagName == name { + return i, true + } + } + return 0, false +} + +// CollectJSONPatchLeafPaths returns dot-paths updated by a JSON patch object. +func CollectJSONPatchLeafPaths(patchJSON []byte) ([]string, error) { + if len(patchJSON) == 0 || string(patchJSON) == "{}" || string(patchJSON) == "null" { + return nil, fmt.Errorf("empty user defaults patch") + } + var raw map[string]interface{} + if err := json.Unmarshal(patchJSON, &raw); err != nil { + return nil, fmt.Errorf("invalid patch JSON: %w", err) + } + return CollectMapLeafPaths(raw, ""), nil +} + +// UserDefaultsPatchJSONForPaths builds a partial JSON patch containing only the given dot-paths from source. +func UserDefaultsPatchJSONForPaths(source UserDefaults, paths []string) ([]byte, error) { + if len(paths) == 0 { + return []byte("{}"), nil + } + pathSet := make(map[string]struct{}, len(paths)) + for _, path := range paths { + pathSet[path] = struct{}{} + } + srcBytes, err := json.Marshal(source) + if err != nil { + return nil, fmt.Errorf("marshal user defaults: %w", err) + } + var srcMap map[string]interface{} + if err := json.Unmarshal(srcBytes, &srcMap); err != nil { + return nil, fmt.Errorf("unmarshal user defaults map: %w", err) + } + patchMap := make(map[string]interface{}) + for path := range pathSet { + if val, ok := valueAtJSONPath(srcMap, path); ok { + setAtJSONPath(patchMap, path, val) + } + } + return json.Marshal(patchMap) +} + +// ApplyConfigSpecifiedPathsToUserDefaults overlays config userDefaults onto stored values for config paths. +func ApplyConfigSpecifiedPathsToUserDefaults(stored, config UserDefaults) (UserDefaults, error) { + paths := ConfigSpecifiedUserDefaultPaths() + if len(paths) == 0 { + return stored, nil + } + patchJSON, err := UserDefaultsPatchJSONForPaths(config, paths) + if err != nil { + return UserDefaults{}, err + } + if len(patchJSON) == 0 || string(patchJSON) == "{}" || string(patchJSON) == "null" { + return stored, nil + } + return MergeUserDefaultsPatchJSON(stored, patchJSON) +} + +// ValidateUserDefaultsPatchNotConfigLocked rejects patches touching config-locked paths. +func ValidateUserDefaultsPatchNotConfigLocked(patchJSON []byte) error { + if !Env.ConfigUserDefaultsSpecified { + return nil + } + paths, err := CollectJSONPatchLeafPaths(patchJSON) + if err != nil { + return err + } + for _, path := range paths { + if IsUserDefaultLockedFromConfig(path) { + return fmt.Errorf("user default %q is locked from config file", path) + } + } + return nil +} diff --git a/backend/pkg/settings/user_defaults_config_test.go b/backend/pkg/settings/user_defaults_config_test.go new file mode 100644 index 0000000000..ffd1b8d66c --- /dev/null +++ b/backend/pkg/settings/user_defaults_config_test.go @@ -0,0 +1,247 @@ +package settings + +import "testing" + +func TestCollectMapLeafPaths_nestedUserDefaults(t *testing.T) { + raw := map[string]interface{}{ + "listing": map[string]interface{}{ + "showHidden": true, + "viewMode": "grid", + }, + "account": map[string]interface{}{ + "permissions": map[string]interface{}{ + "share": true, + }, + }, + } + paths := CollectMapLeafPaths(raw, "") + want := map[string]struct{}{ + "listing.showHidden": {}, + "listing.viewMode": {}, + "account.permissions.share": {}, + } + if len(paths) != len(want) { + t.Fatalf("paths=%v want %d leaves", paths, len(want)) + } + for _, p := range paths { + if _, ok := want[p]; !ok { + t.Fatalf("unexpected path %q in %v", p, paths) + } + } +} + +func TestApplyEnforcementFromPaths(t *testing.T) { + var enforced UserDefaultsEnforcement + ApplyEnforcementFromPaths(&enforced, []string{ + "listing.showHidden", + "account.permissions.share", + }) + if !enforced.Listing.ShowHidden { + t.Fatal("expected listing.showHidden enforced") + } + if !enforced.Account.Permissions.Share { + t.Fatal("expected account.permissions.share enforced") + } + if enforced.Listing.SingleClick { + t.Fatal("unexpected listing.singleClick enforced") + } +} + +func TestValidateUserDefaultsPatchNotConfigLocked(t *testing.T) { + Env.ConfigUserDefaultsSpecified = true + Env.ConfigUserDefaultsSpecifiedPaths = []string{"listing.showHidden"} + t.Cleanup(func() { + Env.ConfigUserDefaultsSpecified = false + Env.ConfigUserDefaultsSpecifiedPaths = nil + }) + + if err := ValidateUserDefaultsPatchNotConfigLocked([]byte(`{"listing":{"singleClick":true}}`)); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if err := ValidateUserDefaultsPatchNotConfigLocked([]byte(`{"listing":{"showHidden":false}}`)); err == nil { + t.Fatal("expected config lock error") + } +} + +func TestMergeEnforcedPatchAllowsConfigLockedValuePath(t *testing.T) { + merged, err := MergeEnforcedPatchJSON(UserDefaultsEnforcement{}, []byte(`{"listing":{"showHidden":true}}`)) + if err != nil { + t.Fatalf("merge enforced patch: %v", err) + } + if !merged.Listing.ShowHidden { + t.Fatal("expected listing.showHidden enforcement true") + } +} + +func TestIsUserDefaultLockedFromConfig(t *testing.T) { + Env.ConfigUserDefaultsSpecifiedPaths = []string{"ui.darkMode"} + t.Cleanup(func() { + Env.ConfigUserDefaultsSpecifiedPaths = nil + }) + if !IsUserDefaultLockedFromConfig("ui.darkMode") { + t.Fatal("expected ui.darkMode locked") + } + if IsUserDefaultLockedFromConfig("ui.locale") { + t.Fatal("expected ui.locale unlocked") + } +} + +func TestApplyConfigSpecifiedPathsToUserDefaults_overlaysConfigLeaves(t *testing.T) { + prevSpecified := Env.ConfigUserDefaultsSpecified + prevPaths := Env.ConfigUserDefaultsSpecifiedPaths + t.Cleanup(func() { + Env.ConfigUserDefaultsSpecified = prevSpecified + Env.ConfigUserDefaultsSpecifiedPaths = prevPaths + }) + + Env.ConfigUserDefaultsSpecified = true + Env.ConfigUserDefaultsSpecifiedPaths = []string{"account.permissions.share"} + + stored := UserDefaults{ + Account: UserDefaultsAccount{ + Permissions: UserDefaultsAccountPermissions{ + Share: false, + Api: true, + }, + LockPassword: true, + }, + Listing: UserDefaultsListing{ + ShowHidden: false, + }, + } + config := UserDefaults{ + Account: UserDefaultsAccount{ + Permissions: UserDefaultsAccountPermissions{ + Share: true, + }, + }, + } + + merged, err := ApplyConfigSpecifiedPathsToUserDefaults(stored, config) + if err != nil { + t.Fatalf("ApplyConfigSpecifiedPathsToUserDefaults: %v", err) + } + if !merged.Account.Permissions.Share { + t.Fatal("expected share permission from config") + } + if !merged.Account.Permissions.Api { + t.Fatal("expected api permission preserved from stored defaults") + } + if !merged.Account.LockPassword { + t.Fatal("expected lockPassword preserved from stored defaults") + } + if merged.Listing.ShowHidden { + t.Fatal("expected unrelated listing defaults preserved") + } +} + +func TestUserDefaultsPatchJSONForPaths_extractsNestedLeaves(t *testing.T) { + source := UserDefaults{ + Account: UserDefaultsAccount{ + Permissions: UserDefaultsAccountPermissions{ + Share: true, + }, + }, + } + patchJSON, err := UserDefaultsPatchJSONForPaths(source, []string{"account.permissions.share"}) + if err != nil { + t.Fatalf("UserDefaultsPatchJSONForPaths: %v", err) + } + merged, err := MergeUserDefaultsPatchJSON(UserDefaults{ + Account: UserDefaultsAccount{ + Permissions: UserDefaultsAccountPermissions{Share: false}, + }, + }, patchJSON) + if err != nil { + t.Fatalf("MergeUserDefaultsPatchJSON: %v", err) + } + if !merged.Account.Permissions.Share { + t.Fatal("expected share true after patch merge") + } +} + +func TestUserDefaultsLockedFromConfig(t *testing.T) { + prevSpecified := Env.ConfigUserDefaultsSpecified + prevPaths := Env.ConfigUserDefaultsSpecifiedPaths + t.Cleanup(func() { + Env.ConfigUserDefaultsSpecified = prevSpecified + Env.ConfigUserDefaultsSpecifiedPaths = prevPaths + }) + + Env.ConfigUserDefaultsSpecified = false + Env.ConfigUserDefaultsSpecifiedPaths = nil + if UserDefaultsLockedFromConfig() { + t.Fatal("expected unlocked when config has no userDefaults paths") + } + Env.ConfigUserDefaultsSpecified = true + Env.ConfigUserDefaultsSpecifiedPaths = []string{"listing.showHidden"} + if !UserDefaultsLockedFromConfig() { + t.Fatal("expected locked when config specifies userDefaults paths") + } + if UserDefaultsConfigLockMessage == "" { + t.Fatal("expected non-empty lock message") + } +} + +func TestUserDefaultsFieldConfigLockMessage(t *testing.T) { + got := UserDefaultsFieldConfigLockMessage("listing.showHidden") + want := `user default "listing.showHidden" is locked from config file` + if got != want { + t.Fatalf("message = %q, want %q", got, want) + } +} + +func TestMergeUserDefaultsPatchJSON_listingOverridePreservesDefaultPreview(t *testing.T) { + base := UserDefaults{ + Listing: UserDefaultsListing{ + QuickDownload: true, + ShowHidden: false, + }, + Preview: UserDefaultsPreview{ + Image: boolPtr(true), + }, + } + patchJSON := []byte(`{"listing":{"showHidden":true}}`) + merged, err := MergeUserDefaultsPatchJSON(base, patchJSON) + if err != nil { + t.Fatalf("MergeUserDefaultsPatchJSON: %v", err) + } + if !merged.Listing.ShowHidden { + t.Fatalf("expected ShowHidden true after merge") + } + if !merged.Listing.QuickDownload { + t.Fatalf("expected QuickDownload preserved from base") + } + if merged.Preview.Image == nil || !*merged.Preview.Image { + t.Fatalf("expected preview.image preserved from base") + } +} + +func TestValidateSinglePropertyUserDefaultsPatch(t *testing.T) { + t.Parallel() + cases := []struct { + name string + patch string + wantErr bool + }{ + {"one bool", `{"listing":{"showHidden":true}}`, false}, + {"one string", `{"listing":{"hideFileExt":".exe"}}`, false}, + {"enforced shape", `{"account":{"lockPassword":true}}`, false}, + {"two fields", `{"listing":{"showHidden":true,"singleClick":true}}`, true}, + {"two sections", `{"listing":{"showHidden":true},"sidebar":{"sticky":true}}`, true}, + {"empty", `{}`, true}, + } + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + err := ValidateSinglePropertyUserDefaultsPatch([]byte(tc.patch)) + if tc.wantErr && err == nil { + t.Fatal("expected error") + } + if !tc.wantErr && err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) + } +} diff --git a/backend/pkg/settings/user_defaults_merge.go b/backend/pkg/settings/user_defaults_merge.go new file mode 100644 index 0000000000..b186ead1c2 --- /dev/null +++ b/backend/pkg/settings/user_defaults_merge.go @@ -0,0 +1,128 @@ +package settings + +import ( + "encoding/json" + "fmt" +) + +// MergeUserDefaults returns a copy of base with patch merged on top (JSON deep merge). +// Both values are treated as complete documents (e.g. loaded from the database). +func MergeUserDefaults(base, patch UserDefaults) (UserDefaults, error) { + baseBytes, err := json.Marshal(base) + if err != nil { + return UserDefaults{}, fmt.Errorf("marshal base user defaults: %w", err) + } + patchBytes, err := json.Marshal(patch) + if err != nil { + return UserDefaults{}, fmt.Errorf("marshal patch user defaults: %w", err) + } + mergedBytes, err := mergeUserDefaultsJSON(baseBytes, patchBytes) + if err != nil { + return UserDefaults{}, err + } + var merged UserDefaults + if err := json.Unmarshal(mergedBytes, &merged); err != nil { + return UserDefaults{}, fmt.Errorf("unmarshal merged user defaults: %w", err) + } + return merged, nil +} + +// MergeUserDefaultsPatchJSONBytes merges patchJSON into baseJSON (both JSON objects). +func MergeUserDefaultsPatchJSONBytes(baseJSON, patchJSON []byte) ([]byte, error) { + return mergeUserDefaultsJSON(baseJSON, patchJSON) +} + +// MergeUserDefaultsPatchJSON merges a partial JSON patch into base user defaults. +func MergeUserDefaultsPatchJSON(base UserDefaults, patchJSON []byte) (UserDefaults, error) { + baseBytes, err := json.Marshal(base) + if err != nil { + return UserDefaults{}, fmt.Errorf("marshal base user defaults: %w", err) + } + mergedBytes, err := mergeUserDefaultsJSON(baseBytes, patchJSON) + if err != nil { + return UserDefaults{}, err + } + var merged UserDefaults + if err := json.Unmarshal(mergedBytes, &merged); err != nil { + return UserDefaults{}, fmt.Errorf("unmarshal merged user defaults: %w", err) + } + return merged, nil +} + +func mergeUserDefaultsJSON(baseJSON, patchJSON []byte) ([]byte, error) { + var baseMap map[string]interface{} + if err := json.Unmarshal(baseJSON, &baseMap); err != nil { + return nil, fmt.Errorf("unmarshal base map: %w", err) + } + if baseMap == nil { + baseMap = make(map[string]interface{}) + } + var patchMap map[string]interface{} + if err := json.Unmarshal(patchJSON, &patchMap); err != nil { + return nil, fmt.Errorf("unmarshal patch map: %w", err) + } + if patchMap == nil { + out, err := json.Marshal(baseMap) + if err != nil { + return nil, fmt.Errorf("marshal merged map: %w", err) + } + return out, nil + } + mergeJSONMaps(baseMap, patchMap) + out, err := json.Marshal(baseMap) + if err != nil { + return nil, fmt.Errorf("marshal merged map: %w", err) + } + return out, nil +} + +func mergeJSONMaps(base, patch map[string]interface{}) { + for key, patchVal := range patch { + baseVal, ok := base[key] + if !ok { + base[key] = patchVal + continue + } + baseMap, baseOk := baseVal.(map[string]interface{}) + patchMap, patchOk := patchVal.(map[string]interface{}) + if baseOk && patchOk { + mergeJSONMaps(baseMap, patchMap) + base[key] = baseMap + continue + } + base[key] = patchVal + } +} + +// CountJSONPatchLeaves counts scalar (and non-object) leaves in a JSON patch object. +func CountJSONPatchLeaves(v interface{}) int { + if v == nil { + return 0 + } + switch t := v.(type) { + case map[string]interface{}: + n := 0 + for _, child := range t { + n += CountJSONPatchLeaves(child) + } + return n + default: + return 1 + } +} + +// ValidateSinglePropertyUserDefaultsPatch rejects patches that change more than one leaf value. +func ValidateSinglePropertyUserDefaultsPatch(patchJSON []byte) error { + if len(patchJSON) == 0 || string(patchJSON) == "{}" || string(patchJSON) == "null" { + return fmt.Errorf("empty user defaults patch") + } + var v interface{} + if err := json.Unmarshal(patchJSON, &v); err != nil { + return fmt.Errorf("invalid patch JSON: %w", err) + } + n := CountJSONPatchLeaves(v) + if n != 1 { + return fmt.Errorf("patch must update exactly one property (got %d)", n) + } + return nil +} diff --git a/backend/pkg/settings/user_enforcement_fields.go b/backend/pkg/settings/user_enforcement_fields.go new file mode 100644 index 0000000000..b3fb10b9a4 --- /dev/null +++ b/backend/pkg/settings/user_enforcement_fields.go @@ -0,0 +1,148 @@ +package settings + +import ( + "strings" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// userJSONFieldEnforcementPaths maps flat user JSON field names (PATCH which / data keys) +// to user-defaults enforcement dot-paths (see UserDefaultsEnforcement). +var userJSONFieldEnforcementPaths = map[string]string{ + "disableQuickToggles": "sidebar.disableQuickToggles", + "hideSidebarFileActions": "sidebar.hideFileActions", + "stickySidebar": "sidebar.sticky", + "hideFilesInTree": "sidebar.hideFiles", + "showToolsInSidebar": "sidebar.showTools", + "deleteWithoutConfirming": "listing.deleteWithoutConfirming", + "dateFormat": "listing.dateFormat", + "showHidden": "listing.showHidden", + "quickDownload": "listing.quickDownload", + "showSelectMultiple": "listing.showSelectMultiple", + "singleClick": "listing.singleClick", + "hideFileExt": "listing.hideFileExt", + "showCopyPath": "listing.showCopyPath", + "deleteAfterArchive": "listing.deleteAfterArchive", + "viewMode": "listing.viewMode", + "gallerySize": "listing.gallerySize", + "disablePreviewExt": "preview.disablePreviewExt", + "disableSearchOptions": "search.disableOptions", + "editorQuickSave": "fileViewer.editorQuickSave", + "preferEditorForMarkdown": "fileViewer.preferEditorForMarkdown", + "debugOffice": "fileViewer.debugOffice", + "disableViewingExt": "fileViewer.disableViewingExt", + "disableOnlyOfficeExt": "fileViewer.disableOnlyOfficeExt", + "disableOfficePreviewExt": "fileViewer.disableOnlyOfficeExt", + "darkMode": "ui.darkMode", + "themeColor": "ui.themeColor", + "customTheme": "ui.customTheme", + "locale": "ui.locale", + "lockPassword": "account.lockPassword", + "disableSettings": "account.disableSettings", + "disableUpdateNotifications": "account.disableUpdateNotifications", +} + +var previewJSONSubfields = map[string]string{ + "image": "preview.image", + "video": "preview.video", + "audio": "preview.audio", + "motionVideoPreview": "preview.motionVideoPreview", + "office": "preview.office", + "popup": "preview.popup", + "folder": "preview.folder", + "models": "preview.models", + "autoplayMedia": "fileViewer.autoplayMedia", + "disableHideSidebar": "sidebar.disableHideOnPreview", +} + +var fileLoadingJSONSubfields = map[string]string{ + "maxConcurrentUpload": "fileLoading.maxConcurrentUpload", + "uploadChunkSizeMb": "fileLoading.uploadChunkSizeMb", + "downloadChunkSizeMb": "fileLoading.downloadChunkSizeMb", +} + +// EnforcedPathsTouchedByUserJSONField returns enforcement paths a user JSON field name may affect. +func EnforcedPathsTouchedByUserJSONField(jsonField string) []string { + jsonField = strings.TrimSpace(jsonField) + if jsonField == "" { + return nil + } + if path, ok := userJSONFieldEnforcementPaths[jsonField]; ok { + return []string{path} + } + switch jsonField { + case "preview": + out := make([]string, 0, len(previewJSONSubfields)) + for _, p := range previewJSONSubfields { + out = append(out, p) + } + return out + case "fileLoading": + out := make([]string, 0, len(fileLoadingJSONSubfields)) + for _, p := range fileLoadingJSONSubfields { + out = append(out, p) + } + return out + case "permissions", "Permissions": + return []string{ + "account.permissions.admin", + "account.permissions.api", + "account.permissions.share", + "account.permissions.realtime", + } + default: + if path, ok := previewJSONSubfields[jsonField]; ok { + return []string{path} + } + if path, ok := fileLoadingJSONSubfields[jsonField]; ok { + return []string{path} + } + } + return nil +} + +// ErrEnforcedUserField is returned when a self-service user update touches an enforced default. +type ErrEnforcedUserField struct { + Field string + Path string +} + +func (e ErrEnforcedUserField) Error() string { + if e.Field != "" { + return "setting is enforced by administrator: " + e.Field + } + return "setting is enforced by administrator: " + e.Path +} + +// ValidateSelfUserUpdateNotEnforced rejects PATCH fields that are locked by user-defaults enforcement. +func ValidateSelfUserUpdateNotEnforced(which []string, enforced UserDefaultsEnforcement, u *users.User) error { + if !EnforcementAppliesToUser(u) { + return nil + } + paths := EnforcedPathSet(enforced) + if len(paths) == 0 { + return nil + } + for _, jsonField := range which { + jsonField = strings.TrimSpace(jsonField) + if jsonField == "" || strings.EqualFold(jsonField, "password") { + continue + } + for _, path := range EnforcedPathsTouchedByUserJSONField(jsonField) { + if _, ok := paths[path]; ok { + return ErrEnforcedUserField{Field: jsonField, Path: path} + } + } + } + return nil +} + +// UserJSONFieldsForEnforcedSync lists top-level user JSON keys that enforced-default sync may modify. +func UserJSONFieldsForEnforcedSync() []string { + out := make([]string, 0, len(userJSONFieldEnforcementPaths)+3) + for k := range userJSONFieldEnforcementPaths { + out = append(out, k) + } + out = append(out, "preview", "fileLoading", "permissions") + return out +} diff --git a/backend/pkg/settings/user_profile.go b/backend/pkg/settings/user_profile.go new file mode 100644 index 0000000000..ff6d27c2b4 --- /dev/null +++ b/backend/pkg/settings/user_profile.go @@ -0,0 +1,35 @@ +package settings + +import ( + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// UserProfile is the nested profile document stored in SQLite user_data.profile +// and aligned with admin UserDefaults sections. +type UserProfile struct { + Sidebar UserDefaultsSidebar `json:"sidebar,omitempty"` + Listing UserDefaultsListing `json:"listing,omitempty"` + Preview UserDefaultsPreview `json:"preview,omitempty"` + FileViewer UserDefaultsFileViewer `json:"fileViewer,omitempty"` + Search UserDefaultsSearch `json:"search,omitempty"` + UI UserDefaultsUI `json:"ui,omitempty"` + FileLoading users.FileLoading `json:"fileLoading,omitempty"` + Account UserDefaultsAccount `json:"account,omitempty"` +} + +// ProfileStorageVersion is the user.Version value after nested profile JSON is persisted. +const ProfileStorageVersion = 5 + +// ProfileFromUserDefaults extracts the profile sections from a defaults template. +func ProfileFromUserDefaults(d UserDefaults) UserProfile { + return UserProfile{ + Sidebar: d.Sidebar, + Listing: d.Listing, + Preview: d.Preview, + FileViewer: d.FileViewer, + Search: d.Search, + UI: d.UI, + FileLoading: d.FileLoading, + Account: d.Account, + } +} diff --git a/backend/pkg/settings/user_profile_merge.go b/backend/pkg/settings/user_profile_merge.go new file mode 100644 index 0000000000..d17f38b164 --- /dev/null +++ b/backend/pkg/settings/user_profile_merge.go @@ -0,0 +1,186 @@ +package settings + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// ApplyFullProfileFromDefaults replaces u profile fields from defaults template. +func ApplyFullProfileFromDefaults(u *users.User, d UserDefaults) { + if u == nil || u.Username == "anonymous" { + return + } + ExpandProfileIntoUser(u, ProfileFromUserDefaults(d)) +} + +// ErrEnforcedUserValueMismatch is returned when a user profile field differs from the enforced default value. +type ErrEnforcedUserValueMismatch struct { + Path string +} + +func (e ErrEnforcedUserValueMismatch) Error() string { + return "user value does not match enforced default: " + e.Path +} + +// ValidateUserAgainstEnforcedDefaults rejects users whose enforced fields differ from universal defaults. +func ValidateUserAgainstEnforcedDefaults(u *users.User, defaults UserDefaults, enforced UserDefaultsEnforcement) error { + if !EnforcementAppliesToUser(u) { + return nil + } + paths := withoutAuthManagedEnforcementPaths(EnforcedPathSet(enforced)) + if len(paths) == 0 || u == nil || u.Username == "" || u.Username == users.AnonymousUserName { + return nil + } + userBytes, err := json.Marshal(ProfileFromUser(u)) + if err != nil { + return fmt.Errorf("marshal user profile: %w", err) + } + defBytes, err := json.Marshal(ProfileFromUserDefaults(defaults)) + if err != nil { + return fmt.Errorf("marshal default profile: %w", err) + } + var userMap, defMap map[string]interface{} + if err := json.Unmarshal(userBytes, &userMap); err != nil { + return fmt.Errorf("parse user profile: %w", err) + } + if err := json.Unmarshal(defBytes, &defMap); err != nil { + return fmt.Errorf("parse default profile: %w", err) + } + for path := range paths { + expected, ok := valueAtJSONPath(defMap, path) + if !ok { + continue + } + actual, ok := valueAtJSONPath(userMap, path) + if !ok || !jsonValuesEqual(expected, actual) { + return ErrEnforcedUserValueMismatch{Path: path} + } + } + return nil +} + +func jsonValuesEqual(a, b interface{}) bool { + ab, errA := json.Marshal(a) + bb, errB := json.Marshal(b) + if errA != nil || errB != nil { + return false + } + return string(ab) == string(bb) +} + +// ApplyEnforcedDefaultsFrom merges enforced default paths from d onto u's profile. +func ApplyEnforcedDefaultsFrom(u *users.User, d UserDefaults, e UserDefaultsEnforcement) { + if !EnforcementAppliesToUser(u) { + return + } + if u == nil || u.Username == "anonymous" { + return + } + paths := withoutAuthManagedEnforcementPaths(EnforcedPathSet(e)) + if len(paths) == 0 { + return + } + currentBytes, err := ProfileJSONFromUser(u) + if err != nil { + return + } + patchBytes, err := profilePatchJSONForPaths(ProfileFromUserDefaults(d), paths) + if err != nil { + return + } + mergedBytes, err := mergeUserDefaultsJSON(currentBytes, patchBytes) + if err != nil { + return + } + _ = ApplyProfileToUser(u, mergedBytes) +} + +// SyncEnforcedDefaultsOntoUser applies enforced defaults onto u. Returns true if profile changed. +func SyncEnforcedDefaultsOntoUser(u *users.User, d UserDefaults, e UserDefaultsEnforcement) bool { + if !EnforcementAppliesToUser(u) { + return false + } + if u == nil || u.Username == "anonymous" { + return false + } + if len(EnforcedPathSet(e)) == 0 { + return false + } + before, err := ProfileJSONFromUser(u) + if err != nil { + return false + } + ApplyEnforcedDefaultsFrom(u, d, e) + after, err := ProfileJSONFromUser(u) + if err != nil { + return false + } + return string(before) != string(after) +} + +func profilePatchJSONForPaths(source UserProfile, paths map[string]struct{}) ([]byte, error) { + srcBytes, err := json.Marshal(source) + if err != nil { + return nil, err + } + var srcMap map[string]interface{} + if err := json.Unmarshal(srcBytes, &srcMap); err != nil { + return nil, err + } + patchMap := make(map[string]interface{}) + for path := range paths { + if val, ok := valueAtJSONPath(srcMap, path); ok { + setAtJSONPath(patchMap, path, val) + } + } + return json.Marshal(patchMap) +} + +func profilePatchForPaths(source UserProfile, paths map[string]struct{}) (UserProfile, error) { + patchBytes, err := profilePatchJSONForPaths(source, paths) + if err != nil { + return UserProfile{}, err + } + var patch UserProfile + if err := json.Unmarshal(patchBytes, &patch); err != nil { + return UserProfile{}, fmt.Errorf("unmarshal profile patch: %w", err) + } + return patch, nil +} + +func valueAtJSONPath(root map[string]interface{}, path string) (interface{}, bool) { + parts := strings.Split(path, ".") + var cur interface{} = root + for _, part := range parts { + m, ok := cur.(map[string]interface{}) + if !ok { + return nil, false + } + val, exists := m[part] + if !exists { + return nil, false + } + cur = val + } + return cur, true +} + +func setAtJSONPath(root map[string]interface{}, path string, value interface{}) { + parts := strings.Split(path, ".") + cur := root + for i, part := range parts { + if i == len(parts)-1 { + cur[part] = value + return + } + next, ok := cur[part].(map[string]interface{}) + if !ok { + next = make(map[string]interface{}) + cur[part] = next + } + cur = next + } +} diff --git a/backend/pkg/settings/user_profile_projection.go b/backend/pkg/settings/user_profile_projection.go new file mode 100644 index 0000000000..2aa3a7dd12 --- /dev/null +++ b/backend/pkg/settings/user_profile_projection.go @@ -0,0 +1,160 @@ +package settings + +import ( + "encoding/json" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// ProfileFromUser builds nested profile from runtime user fields (flat + Preview). +func ProfileFromUser(u *users.User) UserProfile { + if u == nil { + return UserProfile{} + } + return UserProfile{ + Sidebar: UserDefaultsSidebar{ + DisableQuickToggles: u.DisableQuickToggles, + HideFileActions: u.HideSidebarFileActions, + DisableHideOnPreview: u.Preview.DisableHideSidebar, + Sticky: u.StickySidebar, + HideFiles: u.HideFilesInTree, + ShowTools: boolPtr(u.ShowToolsInSidebar), + }, + Listing: UserDefaultsListing{ + DeleteWithoutConfirming: u.DeleteWithoutConfirming, + DateFormat: u.DateFormat, + ShowHidden: u.ShowHidden, + QuickDownload: u.QuickDownload, + ShowSelectMultiple: u.ShowSelectMultiple, + SingleClick: u.SingleClick, + HideFileExt: u.HideFileExt, + ShowCopyPath: u.ShowCopyPath, + DeleteAfterArchive: u.DeleteAfterArchive, + ViewMode: u.ViewMode, + GallerySize: u.GallerySize, + }, + Preview: UserDefaultsPreview{ + Image: boolPtr(u.Preview.Image), + Video: boolPtr(u.Preview.Video), + Audio: boolPtr(u.Preview.Audio), + MotionVideoPreview: boolPtr(u.Preview.MotionVideoPreview), + Office: boolPtr(u.Preview.Office), + PopUp: boolPtr(u.Preview.PopUp), + Folder: boolPtr(u.Preview.Folder), + Models: boolPtr(u.Preview.Models), + DisablePreviewExt: u.DisablePreviewExt, + }, + FileViewer: UserDefaultsFileViewer{ + AutoplayMedia: boolPtr(u.Preview.AutoplayMedia), + EditorQuickSave: u.EditorQuickSave, + DisableViewingExt: u.DisableViewingExt, + DisableOnlyOfficeExt: u.DisableOnlyOfficeExt, + PreferEditorForMarkdown: u.PreferEditorForMarkdown, + DebugOffice: u.DebugOffice, + }, + Search: UserDefaultsSearch{ + DisableOptions: u.DisableSearchOptions, + }, + UI: UserDefaultsUI{ + DarkMode: boolPtr(u.DarkMode), + ThemeColor: u.ThemeColor, + CustomTheme: u.CustomTheme, + Locale: u.Locale, + }, + FileLoading: u.FileLoading, + Account: UserDefaultsAccount{ + LockPassword: u.LockPassword, + DisableSettings: u.DisableSettings, + DisableUpdateNotifications: u.DisableUpdateNotifications, + Permissions: UserDefaultsAccountPermissions{ + Api: u.Permissions.Api, + Admin: u.Permissions.Admin, + Share: u.Permissions.Share, + Realtime: u.Permissions.Realtime, + }, + }, + } +} + +// ExpandProfileIntoUser copies nested profile values onto u (flat API/runtime fields). +func ExpandProfileIntoUser(u *users.User, p UserProfile) { + if u == nil { + return + } + u.DisableSettings = p.Account.DisableSettings + u.LockPassword = p.Account.LockPassword + u.DisableUpdateNotifications = p.Account.DisableUpdateNotifications + u.Permissions.Api = p.Account.Permissions.Api + u.Permissions.Admin = p.Account.Permissions.Admin + u.Permissions.Share = p.Account.Permissions.Share + u.Permissions.Realtime = p.Account.Permissions.Realtime + + u.DisableQuickToggles = p.Sidebar.DisableQuickToggles + u.HideSidebarFileActions = p.Sidebar.HideFileActions + u.StickySidebar = p.Sidebar.Sticky + u.HideFilesInTree = p.Sidebar.HideFiles + u.ShowToolsInSidebar = boolValueOrDefault(p.Sidebar.ShowTools, true) + + u.DeleteWithoutConfirming = p.Listing.DeleteWithoutConfirming + u.DateFormat = p.Listing.DateFormat + u.ShowHidden = p.Listing.ShowHidden + u.QuickDownload = p.Listing.QuickDownload + u.ShowSelectMultiple = p.Listing.ShowSelectMultiple + u.SingleClick = p.Listing.SingleClick + u.HideFileExt = p.Listing.HideFileExt + u.ShowCopyPath = p.Listing.ShowCopyPath + u.DeleteAfterArchive = p.Listing.DeleteAfterArchive + u.ViewMode = p.Listing.ViewMode + u.GallerySize = p.Listing.GallerySize + + u.Preview.DisableHideSidebar = p.Sidebar.DisableHideOnPreview + u.Preview.Image = boolValueOrDefault(p.Preview.Image, true) + u.Preview.Video = boolValueOrDefault(p.Preview.Video, true) + u.Preview.Audio = boolValueOrDefault(p.Preview.Audio, true) + u.Preview.MotionVideoPreview = boolValueOrDefault(p.Preview.MotionVideoPreview, true) + u.Preview.Office = boolValueOrDefault(p.Preview.Office, true) + u.Preview.PopUp = boolValueOrDefault(p.Preview.PopUp, true) + u.Preview.Folder = boolValueOrDefault(p.Preview.Folder, true) + u.Preview.Models = boolValueOrDefault(p.Preview.Models, true) + u.DisablePreviewExt = p.Preview.DisablePreviewExt + + u.EditorQuickSave = p.FileViewer.EditorQuickSave + u.Preview.AutoplayMedia = boolValueOrDefault(p.FileViewer.AutoplayMedia, true) + u.DisableViewingExt = p.FileViewer.DisableViewingExt + u.DisableOnlyOfficeExt = p.FileViewer.DisableOnlyOfficeExt + u.DisableOfficePreviewExt = p.FileViewer.DisableOnlyOfficeExt + u.PreferEditorForMarkdown = p.FileViewer.PreferEditorForMarkdown + u.DebugOffice = p.FileViewer.DebugOffice + + u.DisableSearchOptions = p.Search.DisableOptions + + u.DarkMode = boolValueOrDefault(p.UI.DarkMode, true) + u.ThemeColor = p.UI.ThemeColor + u.CustomTheme = p.UI.CustomTheme + u.Locale = p.UI.Locale + + u.FileLoading = p.FileLoading +} + +// ProfileFromLegacyUser converts a Bolt/flat user into nested profile (one-time migration). +func ProfileFromLegacyUser(u *users.User) UserProfile { + return ProfileFromUser(u) +} + +// ApplyProfileToUser unmarshals profile JSON and expands onto u. +func ApplyProfileToUser(u *users.User, profileJSON []byte) error { + if u == nil || len(profileJSON) == 0 { + return nil + } + var p UserProfile + if err := json.Unmarshal(profileJSON, &p); err != nil { + return err + } + ExpandProfileIntoUser(u, p) + return nil +} + +// ProfileJSONFromUser returns JSON for SQLite user_data.profile. +func ProfileJSONFromUser(u *users.User) ([]byte, error) { + return json.Marshal(ProfileFromUser(u)) +} diff --git a/backend/pkg/settings/user_scopes.go b/backend/pkg/settings/user_scopes.go new file mode 100644 index 0000000000..7846bbe487 --- /dev/null +++ b/backend/pkg/settings/user_scopes.go @@ -0,0 +1,49 @@ +package settings + +import ( + "strings" + + "github.com/gtsteffaniak/filebrowser/backend/internal/database/users" +) + +// ExpandBackendScopesForCreateUserDir appends the username to each default scope when the +// source has createUserDir enabled. Must run before persisting a new user so JWT/proxy/OIDC +// auto-create stores the personal folder scope, not only the source root. +func ExpandBackendScopesForCreateUserDir(u *users.User) { + if u == nil || u.Username == "" || u.Username == users.AnonymousUserName { + return + } + cleanedUserName := users.CleanUsername(u.Username) + if cleanedUserName == "" || cleanedUserName == "-" || cleanedUserName == "." { + return + } + for i, scope := range u.BackendScopes { + source, ok := Config.Server.SourceMap[scope.Path] + if !ok { + continue + } + if source.Config.CreateUserDir && scopeBaseName(scope.Scope) != cleanedUserName { + u.BackendScopes[i].Scope = joinUnixScopePath(scope.Scope, cleanedUserName) + } + } +} + +func scopeBaseName(scope string) string { + scope = strings.TrimSuffix(scope, "/") + if scope == "" || scope == "/" { + return "/" + } + i := strings.LastIndex(scope, "/") + if i < 0 { + return scope + } + return scope[i+1:] +} + +func joinUnixScopePath(base, elem string) string { + base = strings.TrimSuffix(base, "/") + if base == "" || base == "/" { + return "/" + strings.TrimPrefix(elem, "/") + } + return base + "/" + strings.TrimPrefix(elem, "/") +} diff --git a/backend/pkg/settings/validConfig.yaml b/backend/pkg/settings/validConfig.yaml new file mode 100644 index 0000000000..7172694f27 --- /dev/null +++ b/backend/pkg/settings/validConfig.yaml @@ -0,0 +1,34 @@ +http: + port: 80 + baseURL: "/" +server: + numImageProcessors: 4 + database: + path: "mydb.db" + sources: + - path: "." +integrations: + office: + url: "http://localhost:9052" + secret: 6H1H7GzUk2alRkNxAPav0W02g8JS5oUd +auth: + methods: + password: + enabled: true +frontend: + name: "" + disableUsedPercentage: true +userDefaults: + ui: + darkMode: true + locale: "" + listing: + singleClick: true + dateFormat: false + viewMode: "" + account: + disableSettings: false + permissions: + admin: true + share: true + api: true diff --git a/backend/common/settings/video_preview_test.go b/backend/pkg/settings/video_preview_test.go similarity index 77% rename from backend/common/settings/video_preview_test.go rename to backend/pkg/settings/video_preview_test.go index 41c466903b..b1983c8251 100644 --- a/backend/common/settings/video_preview_test.go +++ b/backend/pkg/settings/video_preview_test.go @@ -190,63 +190,6 @@ integrations: }) } -func TestVideoPreviewFormatCategories(t *testing.T) { - // Test that all video format categories are properly supported - t.Run("FormatCategories", func(t *testing.T) { - config := ` -server: - sources: - - path: "." -integrations: - office: - url: "http://localhost:8080" - secret: "test-secret" -` - testVideoPreviewConfig(t, config, func(t *testing.T, config *Settings) { - // Test format categories - categories := map[string][]VideoPreviewType{ - "Common Web Formats": {MP4VideoPreview, WebMVideoPreview, OGVVideoPreview}, - "Apple Formats": {MOVVideoPreview, M4VVideoPreview}, - "Microsoft Formats": {AVIVideoPreview, WMVVideoPreview, ASFVideoPreview}, - "Open Source": {MKVVideoPreview, FLVVideoPreview}, - "Mobile Formats": {ThreeGPVideoPreview, ThreeGP2VideoPreview}, - "Broadcast/Professional": {TSVideoPreview, M2TSVideoPreview}, - "Legacy Formats": {VOBVideoPreview, MPGVideoPreview, MPEGVideoPreview, F4VVideoPreview}, - } - - for category, formats := range categories { - t.Run(category, func(t *testing.T) { - for _, format := range formats { - if !*config.Integrations.Media.Convert.VideoPreview[format] { - t.Errorf("Expected %s (%s) to be enabled by default, but it was disabled", format, category) - } - } - }) - } - }) - }) -} - -func TestVideoPreviewFormatCount(t *testing.T) { - // Test that we have the expected number of video formats - t.Run("FormatCount", func(t *testing.T) { - expectedCount := 18 - actualCount := len(AllVideoPreviewTypes) - if actualCount != expectedCount { - t.Errorf("Expected %d video formats, but got %d", expectedCount, actualCount) - } - - // Test that all formats are unique - formatMap := make(map[VideoPreviewType]bool) - for _, format := range AllVideoPreviewTypes { - if formatMap[format] { - t.Errorf("Duplicate video format found: %s", format) - } - formatMap[format] = true - } - }) -} - func BenchmarkVideoPreviewSetup(b *testing.B) { config := ` server: diff --git a/backend/common/settings/yaml.go b/backend/pkg/settings/yaml.go similarity index 100% rename from backend/common/settings/yaml.go rename to backend/pkg/settings/yaml.go diff --git a/backend/preview/exiftool.go b/backend/preview/exiftool.go deleted file mode 100644 index ad23921d1d..0000000000 --- a/backend/preview/exiftool.go +++ /dev/null @@ -1,92 +0,0 @@ -package preview - -import ( - "context" - "os/exec" - "path/filepath" - "strings" - "time" - - "github.com/gtsteffaniak/filebrowser/backend/common/settings" - "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" -) - -// hasEmbeddedPreview reports whether we should try exiftool for an embedded -// preview. Only true for types that often have one and lack a cheap native decode -func hasEmbeddedPreview(fileType string, fileName string) bool { - ext := strings.ToLower(filepath.Ext(fileName)) - // Raw camera formats: we can't decode natively; exiftool is the main way to get a preview. - if iteminfo.IsRawImage(ext) { - return true - } - // HEIC/HEIF: often have embedded preview; we have FFmpeg fallback but exiftool can be faster. - if strings.HasPrefix(fileType, "image/hei") { - return true - } - return false -} - -// ExtractEmbeddedPreview runs exiftool on the given file to extract an embedded -// preview image (e.g. JpgFromRaw, PreviewImage, ThumbnailImage). Returns the first -// non-empty result, or nil if exiftool is unavailable or no embedded preview exists. -// fileType is the MIME type (e.g. "image/x-canon-cr2", "image/heic", "video/quicktime"). -func ExtractEmbeddedPreview(ctx context.Context, realPath, fileType string) ([]byte, error) { - if realPath == "" { - return nil, nil - } - path := settings.Config.Integrations.Media.ExiftoolPath - if path == "" { - return nil, nil - } - - ext := strings.ToLower(filepath.Ext(realPath)) - - // Tag order: raw often has JpgFromRaw/PreviewImage; HEIC/video use PreviewImage; JPEG has ThumbnailImage. - tags := []string{"PreviewImage", "JpgFromRaw", "ThumbnailImage"} - if iteminfo.IsRawImage(ext) { - tags = []string{"JpgFromRaw", "PreviewImage", "ThumbnailImage"} - } - - for _, tag := range tags { - out, err := runExiftoolTag(ctx, path, realPath, tag) - if err != nil { - continue - } - if len(out) > 0 { - return out, nil - } - } - return nil, nil -} - -// GetOrientation returns the EXIF orientation string for the file (e.g. "Rotate 90 CW", "Horizontal (normal)"). -// Uses exiftool -Orientation -s3. Returns empty string if exiftool is unavailable or orientation cannot be read. -func GetOrientation(ctx context.Context, realPath string) string { - if realPath == "" { - return "" - } - path := settings.Config.Integrations.Media.ExiftoolPath - if path == "" { - return "" - } - ctx, cancel := context.WithTimeout(ctx, 10*time.Second) - defer cancel() - cmd := exec.CommandContext(ctx, path, "-Orientation", "-s3", realPath) - out, err := cmd.CombinedOutput() - if err != nil { - return "" - } - return strings.TrimSpace(string(out)) -} - -func runExiftoolTag(ctx context.Context, exiftoolPath, realPath, tag string) ([]byte, error) { - ctx, cancel := context.WithTimeout(ctx, 30*time.Second) - defer cancel() - - cmd := exec.CommandContext(ctx, exiftoolPath, "-b", "-"+tag, realPath) - out, err := cmd.CombinedOutput() - if err != nil { - return nil, err - } - return out, nil -} diff --git a/backend/preview/heic_ffmpeg.go b/backend/preview/heic_ffmpeg.go deleted file mode 100644 index 584f92cb2e..0000000000 --- a/backend/preview/heic_ffmpeg.go +++ /dev/null @@ -1,84 +0,0 @@ -package preview - -import ( - "context" - "fmt" -) - -// convertHEICToJPEGWithFFmpeg converts a HEIC file to JPEG format using FFmpeg -// This function handles all FFmpeg-related logic and parameters -func (s *Service) convertHEICToJPEGWithFFmpeg(ctx context.Context, filePath string, previewSize string) ([]byte, error) { - // Check if FFmpeg service is available - if s.ffmpegService == nil { - return nil, fmt.Errorf("FFmpeg is not available") - } - - // Check if context is cancelled before starting - if ctx.Err() != nil { - return nil, ctx.Err() - } - - // Acquire FFmpeg service semaphore - if err := s.ffmpegService.Acquire(ctx); err != nil { - return nil, err - } - defer s.ffmpegService.Release() - - // Determine target dimensions and quality based on preview size - var width, height int - var quality string - switch previewSize { - case "large": - width, height = 640, 640 - quality = "2" // High quality for FFmpeg -q:v - case "original": - // For original size - no scaling, maximum quality - width, height = 0, 0 // Signal to not apply scaling - quality = "1" // Maximum quality for original - default: - width, height = 256, 256 - quality = "5" // Medium quality - } - - // Use tile-based conversion for correct full-resolution image reconstruction - return s.ffmpegService.ConvertHEICToJPEG(ctx, filePath, width, height, quality) -} - -// convertImageWithFFmpeg converts any image file (including problematic JPEGs) to resized JPEG using FFmpeg -// This is used as a fallback for JPEG files that Go's standard decoder can't handle (extended sequential, etc.) -func (s *Service) convertImageWithFFmpeg(ctx context.Context, filePath string, previewSize string) ([]byte, error) { - // Check if FFmpeg service is available - if s.ffmpegService == nil { - return nil, fmt.Errorf("FFmpeg is not available for JPEG fallback") - } - - // Check if context is cancelled before starting - if ctx.Err() != nil { - return nil, ctx.Err() - } - - // Acquire FFmpeg service semaphore - if err := s.ffmpegService.Acquire(ctx); err != nil { - return nil, err - } - defer s.ffmpegService.Release() - - // Determine target dimensions and quality based on preview size - var width, height int - var quality string - switch previewSize { - case "large": - width, height = 640, 640 - quality = "2" // High quality for FFmpeg -q:v - case "original": - // For original size - no scaling, maximum quality - width, height = 0, 0 // Signal to not apply scaling - quality = "1" // Maximum quality for original - default: - width, height = 256, 256 - quality = "5" // Medium quality - } - - // Use direct conversion which works for all image formats including problematic JPEGs - return s.ffmpegService.ConvertImageToJPEG(ctx, filePath, width, height, quality) -} diff --git a/backend/preview/testdata b/backend/preview/testdata deleted file mode 120000 index 55d8503d6a..0000000000 --- a/backend/preview/testdata +++ /dev/null @@ -1 +0,0 @@ -../../frontend/tests/playwright-files/myfolder/testdata/ \ No newline at end of file diff --git a/backend/swagger/docs/docs.go b/backend/swagger/docs/docs.go index b2bb85d0b4..750305a84c 100644 --- a/backend/swagger/docs/docs.go +++ b/backend/swagger/docs/docs.go @@ -449,7 +449,7 @@ const docTemplate = `{ "200": { "description": "Object containing a list of groups", "schema": { - "$ref": "#/definitions/http.GroupListResponse" + "$ref": "#/definitions/web.GroupListResponse" } }, "403": { @@ -750,7 +750,7 @@ const docTemplate = `{ "200": { "description": "OTP token is valid.", "schema": { - "$ref": "#/definitions/http.HttpResponse" + "$ref": "#/definitions/web.HttpResponse" } }, "401": { @@ -896,7 +896,7 @@ const docTemplate = `{ "200": { "description": "API token details", "schema": { - "$ref": "#/definitions/http.AuthTokenFrontend" + "$ref": "#/definitions/web.AuthTokenFrontend" } }, "404": { @@ -948,17 +948,22 @@ const docTemplate = `{ }, { "type": "string", - "description": "Permissions for the API token (comma-separated)", + "description": "Global permissions (comma-separated: admin, api, share, realtime). Send \\", "name": "permissions", - "in": "query", - "required": true + "in": "query" + }, + { + "type": "boolean", + "description": "When true, create a minimal token (standard JWT claims only). When false, create a customized token using permissions (may be empty).", + "name": "minimal", + "in": "query" } ], "responses": { "200": { "description": "Token created successfully, response contains json object with token", "schema": { - "$ref": "#/definitions/http.HttpResponse" + "$ref": "#/definitions/web.HttpResponse" } }, "400": { @@ -1024,7 +1029,7 @@ const docTemplate = `{ "200": { "description": "API token deleted successfully", "schema": { - "$ref": "#/definitions/http.HttpResponse" + "$ref": "#/definitions/web.HttpResponse" } }, "404": { @@ -1067,7 +1072,7 @@ const docTemplate = `{ "schema": { "type": "array", "items": { - "$ref": "#/definitions/http.AuthTokenFrontend" + "$ref": "#/definitions/web.AuthTokenFrontend" } } }, @@ -1314,7 +1319,7 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Resources" + "Media" ], "summary": "Get lyrics for an audio file", "parameters": [ @@ -1372,7 +1377,7 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Resources" + "Media" ], "summary": "Directory with media metadata", "parameters": [ @@ -1425,6 +1430,76 @@ const docTemplate = `{ } } }, + "/api/media/stream": { + "get": { + "description": "Returns raw file bytes for inline UI viewing in capped byte ranges. Requires a viewToken minted by GET /resources. Media files must use Range requests; full-file GET responses are rejected. Never counts toward download limits or activity.", + "consumes": [ + "application/json" + ], + "tags": [ + "Resources" + ], + "summary": "Stream content of a single media file for inline viewing", + "parameters": [ + { + "type": "string", + "description": "Source name for the file (required)", + "name": "source", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "File path", + "name": "file", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Opaque view grant token from file metadata", + "name": "viewToken", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "Raw file content (inline)", + "schema": { + "type": "file" + } + }, + "403": { + "description": "Missing or invalid view token", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "404": { + "description": "File not found", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "500": { + "description": "Internal server error", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } + }, "/api/media/subtitles": { "get": { "description": "Returns raw subtitle content from external files or embedded streams", @@ -1435,7 +1510,7 @@ const docTemplate = `{ "text/plain" ], "tags": [ - "Resources" + "Media" ], "summary": "Get subtitle content", "parameters": [ @@ -2024,7 +2099,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/http.MoveCopyRequest" + "$ref": "#/definitions/web.MoveCopyRequest" } } ], @@ -2032,13 +2107,13 @@ const docTemplate = `{ "200": { "description": "All operations completed successfully", "schema": { - "$ref": "#/definitions/http.MoveCopyResponse" + "$ref": "#/definitions/web.MoveCopyResponse" } }, "207": { "description": "Partial success - some operations succeeded, some failed", "schema": { - "$ref": "#/definitions/http.MoveCopyResponse" + "$ref": "#/definitions/web.MoveCopyResponse" } }, "400": { @@ -2071,7 +2146,7 @@ const docTemplate = `{ "500": { "description": "All operations failed", "schema": { - "$ref": "#/definitions/http.MoveCopyResponse" + "$ref": "#/definitions/web.MoveCopyResponse" } } } @@ -2097,7 +2172,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/http.archiveCreateRequest" + "$ref": "#/definitions/web.archiveCreateRequest" } } ], @@ -2181,7 +2256,7 @@ const docTemplate = `{ "schema": { "type": "array", "items": { - "$ref": "#/definitions/http.BulkDeleteItem" + "$ref": "#/definitions/web.BulkDeleteItem" } } } @@ -2190,13 +2265,13 @@ const docTemplate = `{ "200": { "description": "All resources deleted successfully", "schema": { - "$ref": "#/definitions/http.BulkDeleteResponse" + "$ref": "#/definitions/web.BulkDeleteResponse" } }, "207": { "description": "Partial success - some resources deleted, some failed", "schema": { - "$ref": "#/definitions/http.BulkDeleteResponse" + "$ref": "#/definitions/web.BulkDeleteResponse" } }, "400": { @@ -2466,7 +2541,7 @@ const docTemplate = `{ }, { "type": "string", - "description": "Preview size ('small' or 'large'). Default is based on server config.", + "description": "Preview size ('small' or 'large'). Default is based on server settings.Config.", "name": "size", "in": "query" } @@ -2555,7 +2630,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/http.unarchiveRequest" + "$ref": "#/definitions/web.unarchiveRequest" } } ], @@ -2617,6 +2692,128 @@ const docTemplate = `{ } } }, + "/api/resources/view": { + "get": { + "description": "Returns raw file bytes for inline UI viewing. Requires a viewToken minted by GET /resources. Never counts toward download limits or activity and does not require download permission.", + "consumes": [ + "application/json" + ], + "tags": [ + "Resources" + ], + "summary": "View content of a single non-media file inline", + "parameters": [ + { + "type": "string", + "description": "Source name for the file (required)", + "name": "source", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "File path", + "name": "file", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Opaque view grant token from file metadata", + "name": "viewToken", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "Raw file content (inline)", + "schema": { + "type": "file" + } + }, + "403": { + "description": "Missing or invalid view token", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "404": { + "description": "File not found", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "500": { + "description": "Internal server error", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } + }, + "/api/resources/view-token": { + "post": { + "description": "Mints or extends a source-scoped view token for inline viewing. Authenticated routes require a web session (not a named API token). Public share routes accept anonymous users when the share allows it.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Resources" + ], + "summary": "Refresh view token", + "parameters": [ + { + "type": "string", + "description": "Source name or share hash", + "name": "source", + "in": "query" + }, + { + "type": "string", + "description": "Share hash (public share routes)", + "name": "hash", + "in": "query" + }, + { + "type": "string", + "description": "Existing view token to extend", + "name": "viewToken", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.viewTokenResponse" + } + }, + "403": { + "description": "Missing permission or API token used", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } + }, "/api/settings": { "get": { "description": "Returns the current configuration settings for signup, user directories, rules, frontend.", @@ -2720,7 +2917,7 @@ const docTemplate = `{ "schema": { "type": "array", "items": { - "$ref": "#/definitions/share.Link" + "$ref": "#/definitions/share.ShareFrontend" } } }, @@ -2754,7 +2951,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/share.CreateBody" + "$ref": "#/definitions/share.SharePostBody" } } ], @@ -2762,7 +2959,7 @@ const docTemplate = `{ "200": { "description": "Created share link", "schema": { - "$ref": "#/definitions/share.Link" + "$ref": "#/definitions/share.ShareFrontend" } }, "400": { @@ -2865,7 +3062,7 @@ const docTemplate = `{ "200": { "description": "Updated share link", "schema": { - "$ref": "#/definitions/http.ShareResponse" + "$ref": "#/definitions/share.ShareFrontend" } }, "400": { @@ -2940,7 +3137,7 @@ const docTemplate = `{ "201": { "description": "Direct download link created", "schema": { - "$ref": "#/definitions/http.DirectDownloadResponse" + "$ref": "#/definitions/web.DirectDownloadResponse" } }, "400": { @@ -2992,7 +3189,7 @@ const docTemplate = `{ "schema": { "type": "array", "items": { - "$ref": "#/definitions/share.Link" + "$ref": "#/definitions/share.ShareFrontend" } } }, @@ -3008,7 +3205,7 @@ const docTemplate = `{ } } }, - "/api/tools/duplicateFinder": { + "/api/tools/duplicate-finder": { "get": { "description": "Finds duplicate files using multi-stage filtering: size → type → fuzzy filename → progressive checksums. Files must match on size, MIME type, and have 50%+ filename similarity before checksum verification. Large fuzzy groups (\u003e10 files) are skipped to avoid false positives. Checksums use 2-pass progressive verification (header → middle) for accuracy while minimizing disk I/O (~16KB read per file).", "consumes": [ @@ -3046,7 +3243,7 @@ const docTemplate = `{ "200": { "description": "List of duplicate file groups with metadata. Response includes 'incomplete' flag if processing stopped early due to resource limits.", "schema": { - "$ref": "#/definitions/http.duplicateResponse" + "$ref": "#/definitions/web.duplicateResponse" } }, "400": { @@ -3070,7 +3267,7 @@ const docTemplate = `{ } } }, - "/api/tools/fileWatcher": { + "/api/tools/file-watcher": { "get": { "description": "Returns the last N lines of a file", "consumes": [ @@ -3115,7 +3312,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/http.fileWatchResponse" + "$ref": "#/definitions/web.fileWatchResponse" } }, "400": { @@ -3157,7 +3354,7 @@ const docTemplate = `{ } } }, - "/api/tools/fileWatcher/sse": { + "/api/tools/file-watcher/sse": { "get": { "description": "Establishes an SSE connection to receive periodic file updates", "tags": [ @@ -3242,7 +3439,7 @@ const docTemplate = `{ "parameters": [ { "type": "string", - "description": "Filter prefix or full legacy search text (required when no terms are supplied)", + "description": "Filter prefix or full search text (required when no terms are supplied)", "name": "query", "in": "query" }, @@ -3256,12 +3453,6 @@ const docTemplate = `{ "name": "terms", "in": "query" }, - { - "type": "string", - "description": "Source name for the desired source (deprecated, use 'sources' instead)", - "name": "source", - "in": "query" - }, { "type": "string", "description": "Comma-separated source names when not using repeated scope=source:path", @@ -3274,7 +3465,7 @@ const docTemplate = `{ "type": "string" }, "collectionFormat": "csv", - "description": "Repeated: either 'sourceName:relativePath' per source, or legacy single path when one source", + "description": "Repeated: 'sourceName:relativePath' per source", "name": "scope", "in": "query" }, @@ -3296,18 +3487,6 @@ const docTemplate = `{ "name": "useWildcard", "in": "query" }, - { - "type": "boolean", - "description": "Deprecated: alias for useWildcard", - "name": "glob", - "in": "query" - }, - { - "type": "boolean", - "description": "Deprecated: alias for useWildcard", - "name": "useGlob", - "in": "query" - }, { "type": "string", "description": "Optional: 'and' to require all repeated 'terms' match; default is OR", @@ -3339,7 +3518,7 @@ const docTemplate = `{ }, "/api/users": { "get": { - "description": "Returns a user's details based on their ID, or all users if no id is provided.", + "description": "Returns all users (admins) or only the current user; with ?username=self, the logged-in user; with ?username=login, that user if permitted. Query id= is not supported.", "consumes": [ "application/json" ], @@ -3349,12 +3528,12 @@ const docTemplate = `{ "tags": [ "Users" ], - "summary": "Retrieve a user by ID", + "summary": "List users or get one by username", "parameters": [ { "type": "string", - "description": "User ID or 'self'", - "name": "id", + "description": "Login name, or 'self' for the current session user", + "name": "username", "in": "query" } ], @@ -3362,7 +3541,16 @@ const docTemplate = `{ "200": { "description": "User details or list of users", "schema": { - "$ref": "#/definitions/users.User" + "$ref": "#/definitions/users.FrontendUser" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } } }, "403": { @@ -3394,86 +3582,6 @@ const docTemplate = `{ } } }, - "put": { - "description": "Updates the details of a user identified by ID. When the authenticated actor uses password login, they must send their current password in the X-Password header unless the update only touches NonAdminEditable profile fields (not password). Full updates (which empty or \"all\") or any admin-only field require confirmation.", - "consumes": [ - "application/json" - ], - "tags": [ - "Users" - ], - "summary": "Update a user's details", - "parameters": [ - { - "type": "string", - "description": "user ID to update", - "name": "id", - "in": "query" - }, - { - "type": "string", - "description": "usename to update", - "name": "id", - "in": "query" - }, - { - "type": "string", - "description": "Actor's current password (URL-encoded); required for password-login actors when updating password, using which=all, or any field outside NonAdminEditable", - "name": "X-Password", - "in": "header" - }, - { - "description": "User data to update", - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/users.User" - } - } - ], - "responses": { - "204": { - "description": "No Content - User updated successfully" - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - }, - "401": { - "description": "Unauthorized - invalid or missing actor password when required", - "schema": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - }, - "403": { - "description": "Forbidden", - "schema": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - } - } - }, "post": { "description": "Adds a new user to the system. When the authenticated actor uses password login, they must send their current password in the X-Password header.", "consumes": [ @@ -3540,7 +3648,7 @@ const docTemplate = `{ } }, "delete": { - "description": "Deletes a user identified by their ID. When the authenticated actor uses password login, they must send their current password in the X-Password header.", + "description": "Deletes a user identified by login name.", "consumes": [ "application/json" ], @@ -3550,26 +3658,91 @@ const docTemplate = `{ "tags": [ "Users" ], - "summary": "Delete a user by ID", + "summary": "Delete a user by username", "parameters": [ { "type": "string", - "description": "User ID", - "name": "id", + "description": "Username", + "name": "username", "in": "query", "required": true - }, - { - "type": "string", - "description": "Actor's current password (URL-encoded); required for password-login actors", - "name": "X-Password", - "in": "header" } ], "responses": { "200": { "description": "User deleted successfully" }, + "403": { + "description": "Forbidden", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + }, + "patch": { + "description": "Updates the details of a user identified by ID. which must list the JSON field names to update. When the authenticated actor uses password login, they must send their current password in the X-Password header unless the update only touches NonAdminEditable profile fields (not password). Any admin-only field requires confirmation.", + "consumes": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Update a user's details", + "parameters": [ + { + "type": "string", + "description": "user ID to update", + "name": "id", + "in": "query" + }, + { + "type": "string", + "description": "usename to update", + "name": "id", + "in": "query" + }, + { + "type": "string", + "description": "Actor's current password (URL-encoded); required for password-login actors when updating password or any field outside NonAdminEditable", + "name": "X-Password", + "in": "header" + }, + { + "description": "User data to update", + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/users.User" + } + } + ], + "responses": { + "204": { + "description": "No Content - User updated successfully" + }, + "400": { + "description": "Bad Request", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, "401": { "description": "Unauthorized - invalid or missing actor password when required", "schema": { @@ -3600,7 +3773,7 @@ const docTemplate = `{ } } }, - "/api/users/pinnedItems": { + "/api/users/pinned-items": { "patch": { "description": "Patches one pinned item at a time. Defaults to add; pass ?action=remove to unpin.", "consumes": [ @@ -3626,7 +3799,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/http.pinnedItemPatchRequest" + "$ref": "#/definitions/web.pinnedItemPatchRequest" } } ], @@ -3664,33 +3837,13 @@ const docTemplate = `{ } } }, - "/health": { - "get": { - "description": "Returns the health status of the API.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "summary": "Health Check", - "responses": { - "200": { - "description": "successful health check response", - "schema": { - "$ref": "#/definitions/http.HttpResponse" - } - } - } - } - }, "/public/api/media/lyrics": { "get": { "produces": [ "application/json" ], "tags": [ - "Shares" + "Media" ], "summary": "Get lyrics for an audio file (public share)", "parameters": [ @@ -3743,7 +3896,7 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Shares" + "Media" ], "summary": "Directory with media metadata (public share)", "parameters": [ @@ -3777,6 +3930,79 @@ const docTemplate = `{ } } }, + "/public/api/media/stream": { + "get": { + "description": "Returns raw file bytes for inline UI viewing in capped byte ranges on a share link. Requires viewToken from GET /public/api/resources. Media files must use Range requests. Does not count toward download limits.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/octet-stream" + ], + "tags": [ + "Resources" + ], + "summary": "Stream a single media file from a public share for inline viewing", + "parameters": [ + { + "type": "string", + "description": "Share hash for authentication", + "name": "hash", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "File path within the share", + "name": "file", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Opaque view grant token from share file metadata", + "name": "viewToken", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "Raw file content (inline)", + "schema": { + "type": "file" + } + }, + "403": { + "description": "Missing or invalid view token", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "404": { + "description": "Share or file not found", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "500": { + "description": "Internal server error", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } + }, "/public/api/resources": { "get": { "description": "Returns metadata for files or directories accessible via a public share link. Browsing is disabled for upload-only shares.", @@ -3787,7 +4013,7 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Shares" + "Resources" ], "summary": "Get file/directory information from a public share", "parameters": [ @@ -3871,7 +4097,7 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Shares" + "Resources" ], "summary": "Update a file in a public share", "parameters": [ @@ -3956,7 +4182,7 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Shares" + "Resources" ], "summary": "Upload files to a public upload share", "parameters": [ @@ -4069,7 +4295,7 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Shares" + "Resources" ], "summary": "Move, copy, or rename resources in a public share", "parameters": [ @@ -4086,7 +4312,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/http.MoveCopyRequest" + "$ref": "#/definitions/web.MoveCopyRequest" } } ], @@ -4094,13 +4320,13 @@ const docTemplate = `{ "200": { "description": "All operations completed successfully", "schema": { - "$ref": "#/definitions/http.MoveCopyResponse" + "$ref": "#/definitions/web.MoveCopyResponse" } }, "207": { "description": "Partial success - some operations succeeded, some failed", "schema": { - "$ref": "#/definitions/http.MoveCopyResponse" + "$ref": "#/definitions/web.MoveCopyResponse" } }, "400": { @@ -4133,7 +4359,7 @@ const docTemplate = `{ "500": { "description": "Internal server error", "schema": { - "$ref": "#/definitions/http.MoveCopyResponse" + "$ref": "#/definitions/web.MoveCopyResponse" } } } @@ -4149,7 +4375,7 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Shares" + "Resources" ], "summary": "Bulk delete resources from public share", "parameters": [ @@ -4168,7 +4394,7 @@ const docTemplate = `{ "schema": { "type": "array", "items": { - "$ref": "#/definitions/http.BulkDeleteItem" + "$ref": "#/definitions/web.BulkDeleteItem" } } } @@ -4177,13 +4403,13 @@ const docTemplate = `{ "200": { "description": "All resources deleted successfully", "schema": { - "$ref": "#/definitions/http.BulkDeleteResponse" + "$ref": "#/definitions/web.BulkDeleteResponse" } }, "207": { "description": "Partial success - some resources deleted, some failed", "schema": { - "$ref": "#/definitions/http.BulkDeleteResponse" + "$ref": "#/definitions/web.BulkDeleteResponse" } }, "400": { @@ -4226,7 +4452,7 @@ const docTemplate = `{ "application/octet-stream" ], "tags": [ - "Shares" + "Resources" ], "summary": "Download files from a public share", "parameters": [ @@ -4326,7 +4552,7 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Shares" + "Resources" ], "summary": "Get directory items (public share)", "parameters": [ @@ -4397,7 +4623,7 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Shares" + "Resources" ], "summary": "Register graceful chunked upload pause (public share)", "parameters": [ @@ -4451,7 +4677,7 @@ const docTemplate = `{ "image/jpeg" ], "tags": [ - "Shares" + "Resources" ], "summary": "Get image/video preview from a public share", "parameters": [ @@ -4471,7 +4697,7 @@ const docTemplate = `{ }, { "type": "string", - "description": "Preview size: 'small' or 'large'. Default is based on server config.", + "description": "Preview size: 'small' or 'large'. Default is based on server settings.Config.", "name": "size", "in": "query" } @@ -4522,6 +4748,131 @@ const docTemplate = `{ } } }, + "/public/api/resources/view": { + "get": { + "description": "Returns raw file bytes for inline UI viewing on a share link. Requires viewToken from GET /public/api/resources. Does not count toward download limits.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/octet-stream" + ], + "tags": [ + "Resources" + ], + "summary": "View a single non-media file from a public share inline", + "parameters": [ + { + "type": "string", + "description": "Share hash for authentication", + "name": "hash", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "File path within the share", + "name": "file", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Opaque view grant token from share file metadata", + "name": "viewToken", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "Raw file content (inline)", + "schema": { + "type": "file" + } + }, + "403": { + "description": "Missing or invalid view token", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "404": { + "description": "Share or file not found", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "500": { + "description": "Internal server error", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } + }, + "/public/api/resources/view-token": { + "post": { + "description": "Mints or extends a source-scoped view token for inline viewing. Authenticated routes require a web session (not a named API token). Public share routes accept anonymous users when the share allows it.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Resources" + ], + "summary": "Refresh view token", + "parameters": [ + { + "type": "string", + "description": "Source name or share hash", + "name": "source", + "in": "query" + }, + { + "type": "string", + "description": "Share hash (public share routes)", + "name": "hash", + "in": "query" + }, + { + "type": "string", + "description": "Existing view token to extend", + "name": "viewToken", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.viewTokenResponse" + } + }, + "403": { + "description": "Missing permission or API token used", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } + }, "/public/api/share/image": { "get": { "description": "Returns a resizable preview (large size) for the banner or favicon file of a share", @@ -4616,7 +4967,7 @@ const docTemplate = `{ "200": { "description": "Share information", "schema": { - "$ref": "#/definitions/share.CommonShare" + "$ref": "#/definitions/share.Share" } }, "404": { @@ -4631,9 +4982,9 @@ const docTemplate = `{ } } }, - "/public/api/share/pinnedItems": { + "/public/api/share/pinned-items": { "patch": { - "description": "Patches one pinned item at a time for share owners. Defaults to add; pass ?action=remove to unpin.", + "description": "Patches one pinned item at a time on a share. Defaults to add; pass ?action=remove to unpin.", "consumes": [ "application/json" ], @@ -4641,7 +4992,7 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Shares" + "Share" ], "summary": "Add or remove a pinned item on a share", "parameters": [ @@ -4664,7 +5015,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/http.sharePinnedItemPatchRequest" + "$ref": "#/definitions/web.sharePinnedItemPatchRequest" } } ], @@ -4691,7 +5042,7 @@ const docTemplate = `{ } }, "404": { - "description": "Share not found", + "description": "Not Found", "schema": { "type": "object", "additionalProperties": { @@ -4730,520 +5081,6 @@ const docTemplate = `{ } } }, - "http.AuthTokenFrontend": { - "type": "object", - "properties": { - "Permissions": { - "$ref": "#/definitions/users.Permissions" - }, - "expiresAt": { - "type": "integer" - }, - "issuedAt": { - "type": "integer" - }, - "name": { - "type": "string" - }, - "token": { - "type": "string" - } - } - }, - "http.BulkDeleteItem": { - "type": "object", - "properties": { - "message": { - "type": "string" - }, - "path": { - "type": "string" - }, - "source": { - "type": "string" - } - } - }, - "http.BulkDeleteResponse": { - "type": "object", - "properties": { - "failed": { - "type": "array", - "items": { - "$ref": "#/definitions/http.BulkDeleteItem" - } - }, - "succeeded": { - "type": "array", - "items": { - "$ref": "#/definitions/http.BulkDeleteItem" - } - } - } - }, - "http.DirectDownloadResponse": { - "type": "object", - "properties": { - "hash": { - "type": "string" - }, - "shareUrl": { - "type": "string" - }, - "status": { - "type": "string" - }, - "url": { - "type": "string" - } - } - }, - "http.GroupListResponse": { - "type": "object", - "properties": { - "groups": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "http.HttpResponse": { - "type": "object", - "properties": { - "message": { - "type": "string" - }, - "status": { - "type": "integer" - }, - "token": { - "type": "string" - } - } - }, - "http.MoveCopyItem": { - "type": "object", - "properties": { - "fromPath": { - "type": "string" - }, - "fromSource": { - "type": "string" - }, - "message": { - "type": "string" - }, - "toPath": { - "type": "string" - }, - "toSource": { - "type": "string" - } - } - }, - "http.MoveCopyRequest": { - "type": "object", - "properties": { - "action": { - "description": "\"copy\", \"move\", or \"rename\"", - "type": "string" - }, - "items": { - "type": "array", - "items": { - "$ref": "#/definitions/http.MoveCopyItem" - } - }, - "overwrite": { - "description": "Overwrite if destination exists", - "type": "boolean" - }, - "rename": { - "description": "Auto-rename if destination exists", - "type": "boolean" - } - } - }, - "http.MoveCopyResponse": { - "type": "object", - "properties": { - "failed": { - "type": "array", - "items": { - "$ref": "#/definitions/http.MoveCopyItem" - } - }, - "succeeded": { - "type": "array", - "items": { - "$ref": "#/definitions/http.MoveCopyItem" - } - } - } - }, - "http.ShareResponse": { - "type": "object", - "properties": { - "allowCreate": { - "description": "allow creating files", - "type": "boolean" - }, - "allowDelete": { - "type": "boolean" - }, - "allowModify": { - "description": "allow modifying files", - "type": "boolean" - }, - "allowReplacements": { - "description": "allow replacements of files", - "type": "boolean" - }, - "allowedUsernames": { - "type": "array", - "items": { - "type": "string" - } - }, - "banner": { - "type": "string" - }, - "bannerUrl": { - "type": "string" - }, - "canEditShare": { - "type": "boolean" - }, - "description": { - "type": "string" - }, - "disableAnonymous": { - "type": "boolean" - }, - "disableDownload": { - "description": "don't allow downloading files", - "type": "boolean" - }, - "disableFileViewer": { - "description": "don't allow viewing files", - "type": "boolean" - }, - "disableLoginOption": { - "description": "disable login option in share (true = hide, false = show)", - "type": "boolean" - }, - "disableShareCard": { - "type": "boolean" - }, - "disableSidebar": { - "type": "boolean" - }, - "disableThumbnails": { - "type": "boolean" - }, - "downloadURL": { - "type": "string" - }, - "downloads": { - "type": "integer" - }, - "downloadsLimit": { - "type": "integer" - }, - "enableOnlyOffice": { - "type": "boolean" - }, - "enforceDarkLightMode": { - "description": "\"dark\" or \"light\"", - "type": "string" - }, - "expire": { - "type": "integer" - }, - "extractEmbeddedSubtitles": { - "description": "can be io intensive for large files and take 10-30 seconds.", - "type": "boolean" - }, - "favicon": { - "type": "string" - }, - "faviconUrl": { - "type": "string" - }, - "hasPassword": { - "type": "boolean" - }, - "hash": { - "type": "string" - }, - "hideFileExt": { - "description": "show hidden files based on extensions in shares", - "type": "string" - }, - "hideNavButtons": { - "type": "boolean" - }, - "keepAfterExpiration": { - "type": "boolean" - }, - "maxBandwidth": { - "type": "integer" - }, - "password_hash": { - "type": "string" - }, - "path": { - "type": "string" - }, - "pathExists": { - "type": "boolean" - }, - "perUserDownloadLimit": { - "type": "boolean" - }, - "pinnedItems": { - "$ref": "#/definitions/share.PinnedItems" - }, - "quickDownload": { - "type": "boolean" - }, - "shareTheme": { - "type": "string" - }, - "shareType": { - "description": "type of share: normal, upload, max", - "type": "string" - }, - "shareURL": { - "type": "string" - }, - "showHidden": { - "description": "show hidden files in share (true = show, false = hide)", - "type": "boolean" - }, - "sidebarLinks": { - "description": "customizable sidebar links", - "type": "array", - "items": { - "$ref": "#/definitions/users.SidebarLink" - } - }, - "source": { - "description": "Override embedded field to show source name", - "type": "string" - }, - "sourceURL": { - "type": "string" - }, - "themeColor": { - "type": "string" - }, - "title": { - "type": "string" - }, - "token": { - "description": "Token is a random value that will only be set when PasswordHash is set. It is\nURL-Safe and is used to download links in password-protected shares via a\nquery arg.", - "type": "string" - }, - "userDownloads": { - "description": "Track downloads per username", - "type": "object", - "additionalProperties": { - "type": "integer" - } - }, - "userID": { - "type": "integer" - }, - "username": { - "type": "string" - }, - "version": { - "type": "integer" - }, - "viewMode": { - "description": "default view mode for anonymous users: \"list\", \"compact\", \"normal\", \"gallery\"", - "type": "string" - } - } - }, - "http.archiveCreateRequest": { - "type": "object", - "properties": { - "compression": { - "description": "Gzip compression level for tar.gz only, 0-9; 0 = default; ignored for zip (optional). Example: 6", - "type": "integer" - }, - "deleteAfter": { - "description": "If true, delete the source files/directories after successful archive creation (optional; requires delete permission). Example: true", - "type": "boolean" - }, - "destination": { - "description": "Full path where the archive will be created; use .zip or .tar.gz extension (required). Example: \"/backups/my-archive.zip\"", - "type": "string" - }, - "format": { - "description": "Archive format: \"zip\" or \"tar.gz\" (optional; inferred from destination if omitted). Example: \"zip\"", - "type": "string" - }, - "fromSource": { - "description": "Source name where the paths to archive live (required). Example: \"default\"", - "type": "string" - }, - "paths": { - "description": "Paths of files or directories to add; directories are walked; access-denied entries skipped (required). Example: [\"/docs/file.txt\", \"/photos\"]", - "type": "array", - "items": { - "type": "string" - } - }, - "toSource": { - "description": "Source name where the archive file will be written (optional; default: fromSource). Example: \"backups\"", - "type": "string" - } - } - }, - "http.duplicateGroup": { - "type": "object", - "properties": { - "count": { - "type": "integer" - }, - "files": { - "type": "array", - "items": { - "$ref": "#/definitions/indexing.SearchResult" - } - }, - "size": { - "type": "integer" - } - } - }, - "http.duplicateResponse": { - "type": "object", - "properties": { - "groups": { - "type": "array", - "items": { - "$ref": "#/definitions/http.duplicateGroup" - } - }, - "incomplete": { - "type": "boolean" - }, - "reason": { - "type": "string" - } - } - }, - "http.fileWatchMetadata": { - "type": "object", - "properties": { - "modified": { - "description": "Modification time", - "type": "string" - }, - "name": { - "description": "File name", - "type": "string" - }, - "size": { - "description": "File size in bytes (for directories, total size of all files)", - "type": "integer" - }, - "type": { - "description": "MIME type", - "type": "string" - } - } - }, - "http.fileWatchResponse": { - "type": "object", - "properties": { - "contents": { - "description": "Text content for text files", - "type": "string" - }, - "isText": { - "description": "Whether the file is a text file", - "type": "boolean" - }, - "metadata": { - "description": "File metadata for non-text files", - "allOf": [ - { - "$ref": "#/definitions/http.fileWatchMetadata" - } - ] - } - } - }, - "http.pinnedItemPatchRequest": { - "type": "object", - "required": [ - "name", - "path", - "source" - ], - "properties": { - "name": { - "description": "item basename within path", - "type": "string" - }, - "path": { - "description": "scope-relative parent directory", - "type": "string" - }, - "source": { - "type": "string" - } - } - }, - "http.sharePinnedItemPatchRequest": { - "type": "object", - "required": [ - "name", - "path" - ], - "properties": { - "name": { - "description": "item basename within path", - "type": "string" - }, - "path": { - "description": "share-relative parent directory", - "type": "string" - } - } - }, - "http.unarchiveRequest": { - "type": "object", - "properties": { - "deleteAfter": { - "description": "If true, delete the archive file after successful extraction (optional; default: false). Example: true", - "type": "boolean" - }, - "destination": { - "description": "Directory path on toSource to extract into (required). Example: \"/projects/imported\"", - "type": "string" - }, - "fromSource": { - "description": "Source name where the archive file lives (required). Example: \"default\"", - "type": "string" - }, - "path": { - "description": "Path to the archive file on fromSource; .zip, .tar.gz, or .tgz (required). Example: \"/downloads/data.zip\"", - "type": "string" - }, - "toSource": { - "description": "Source name where contents will be extracted (optional; default: fromSource). Example: \"restored\"", - "type": "string" - } - } - }, "indexing.SearchResult": { "type": "object", "properties": { @@ -5364,6 +5201,10 @@ const docTemplate = `{ "type": { "description": "type of the file, either \"directory\" or a file mimetype", "type": "string" + }, + "viewToken": { + "description": "opaque token for inline viewing via /resources/view or /media/stream", + "type": "string" } } }, @@ -5405,6 +5246,10 @@ const docTemplate = `{ "type": { "description": "type of the file, either \"directory\" or a file mimetype", "type": "string" + }, + "viewToken": { + "description": "opaque token for inline viewing via /resources/view or /media/stream", + "type": "string" } } }, @@ -5522,6 +5367,14 @@ const docTemplate = `{ "description": "track artist", "type": "string" }, + "audioCodec": { + "description": "audio codec name (e.g. aac)", + "type": "string" + }, + "container": { + "description": "container/format name (e.g. mov,mp4,m4a,3gp,3g2,mj2)", + "type": "string" + }, "duration": { "description": "duration in seconds", "type": "integer" @@ -5549,12 +5402,37 @@ const docTemplate = `{ "description": "track number", "type": "integer" }, + "videoCodec": { + "description": "video codec name (e.g. h264)", + "type": "string" + }, "year": { "description": "release year", "type": "integer" } } }, + "settings.ActivityConfig": { + "type": "object", + "properties": { + "disabled": { + "description": "disable semantic activity audit logging (default: false)", + "type": "boolean" + }, + "flushIntervalSeconds": { + "description": "buffer flush interval in seconds (default 10)", + "type": "integer" + }, + "maxBufferSize": { + "description": "max in-memory buffer before immediate flush (default 10000)", + "type": "integer" + }, + "retentionDays": { + "description": "purge activity rows older than this many days (default 30)", + "type": "integer" + } + } + }, "settings.Auth": { "type": "object", "properties": { @@ -5583,30 +5461,6 @@ const docTemplate = `{ } } }, - "settings.ConditionalFilter": { - "type": "object", - "properties": { - "hidden": { - "description": "deprecated: use ignoreHidden instead. eg, FolderPath: \"/\" and ignoreHidden: true will exclude hidden files and folders under the root folder.", - "type": "boolean" - }, - "ignoreHidden": { - "description": "deprecated: use ignoreHidden instead. eg, FolderPath: \"/\" and ignoreHidden: true will exclude hidden files and folders under the root folder.", - "type": "boolean" - }, - "ignoreZeroSizeFolders": { - "description": "deprecated: use ignoreZeroSizeFolders instead. eg, FolderPath: \"/\" and ignoreZeroSizeFolders: true will ignore folders with 0 size under the root folder.", - "type": "boolean" - }, - "rules": { - "description": "list of item rules to apply to specific paths", - "type": "array", - "items": { - "$ref": "#/definitions/settings.ConditionalRule" - } - } - } - }, "settings.ConditionalRule": { "type": "object", "properties": { @@ -5618,10 +5472,6 @@ const docTemplate = `{ "description": "(global) exclude files that match these names. Eg. \"file.txt\" or \"test.csv\"", "type": "string" }, - "fileNames": { - "description": "deprecated: exclude files that match these names. Eg. \"file.txt\" or \"test.csv\"", - "type": "string" - }, "filePath": { "description": "(global) exclude files that match this path. Eg. \"/path/to/file.txt\" or \"/path/to/file.txt/subfile.txt\"", "type": "string" @@ -5638,10 +5488,6 @@ const docTemplate = `{ "description": "(global) exclude folders that match these names. Eg. \"folder\" or \"subfolder\"", "type": "string" }, - "folderNames": { - "description": "deprecated: exclude folders that match these names. Eg. \"folder\" or \"subfolder\"", - "type": "string" - }, "folderPath": { "description": "(global) exclude folders that match this path. Eg. \"/path/to/folder\" or \"/path/to/folder/subfolder\"", "type": "string" @@ -5689,6 +5535,27 @@ const docTemplate = `{ } } }, + "settings.Database": { + "type": "object", + "properties": { + "activity": { + "description": "activity audit logging configuration", + "allOf": [ + { + "$ref": "#/definitions/settings.ActivityConfig" + } + ] + }, + "migrateFrom": { + "description": "path to legacy database file for migration (optional)", + "type": "string" + }, + "path": { + "description": "path to SQLite database file", + "type": "string" + } + } + }, "settings.ExternalLink": { "type": "object", "required": [ @@ -5799,16 +5666,49 @@ const docTemplate = `{ "settings.Http": { "type": "object", "properties": { + "baseURL": { + "description": "base URL for the server, the subpath that the server is running on.", + "type": "string" + }, "disableRateLimit": { "description": "turns off built-in auth route rate limiting and failed-login lockout (default false).", "type": "boolean" }, - "trustedHeaders": { - "description": "list of headers to trust, useful when behind a reverse proxy.", - "type": "array", - "items": { - "type": "string" - } + "disableWebDAV": { + "description": "disable webdav support (default: false)", + "type": "boolean" + }, + "externalUrl": { + "description": "used by share links if set (eg. http://mydomain.com)", + "type": "string" + }, + "internalUrl": { + "description": "used by integrations if set, this is the base domain that an integration service will use to communicate with filebrowser (eg. http://localhost:8080)", + "type": "string" + }, + "listen": { + "description": "address to listen on (default: 0.0.0.0)", + "type": "string" + }, + "port": { + "description": "port to listen on", + "type": "integer" + }, + "socket": { + "description": "socket to listen on - eg. /var/run/filebrowser.sock", + "type": "string" + }, + "tlsCert": { + "description": "path to TLS cert", + "type": "string" + }, + "tlsKey": { + "description": "path to TLS key", + "type": "string" + }, + "trustProxyHeaders": { + "description": "honor X-Forwarded-* and X-Real-IP from a reverse proxy (default: false)", + "type": "boolean" } } }, @@ -6040,10 +5940,6 @@ const docTemplate = `{ "description": "output ffmpeg stdout for media integration -- careful can produces lots of output!", "type": "boolean" }, - "exiftoolPath": { - "description": "path to exiftool executable", - "type": "string" - }, "extractEmbeddedSubtitles": { "description": "extract embedded subtitles from media files", "type": "boolean" @@ -6051,6 +5947,10 @@ const docTemplate = `{ "ffmpegPath": { "description": "path to ffmpeg directory with ffmpeg and ffprobe (eg. /usr/local/bin)", "type": "string" + }, + "hardwareAcceleration": { + "description": "enable hardware acceleration for ffmpeg if available", + "type": "boolean" } } }, @@ -6260,10 +6160,6 @@ const docTemplate = `{ "sources" ], "properties": { - "baseURL": { - "description": "base URL for the server, the subpath that the server is running on.", - "type": "string" - }, "cacheDir": { "description": "path to the cache directory, used for thumbnails and other cached files", "type": "string" @@ -6273,8 +6169,12 @@ const docTemplate = `{ "type": "boolean" }, "database": { - "description": "path to the database file", - "type": "string" + "description": "SQLite database configuration", + "allOf": [ + { + "$ref": "#/definitions/settings.Database" + } + ] }, "disablePreviewResize": { "description": "disable resizing of previews for faster loading over slow connections", @@ -6292,14 +6192,6 @@ const docTemplate = `{ "description": "disables backend update check service", "type": "boolean" }, - "disableWebDAV": { - "description": "disable webdav support (default: false)", - "type": "boolean" - }, - "externalUrl": { - "description": "used by share links if set (eg. http://mydomain.com)", - "type": "string" - }, "filesystem": { "description": "filesystem settings", "allOf": [ @@ -6316,14 +6208,6 @@ const docTemplate = `{ } ] }, - "internalUrl": { - "description": "used by integrations if set, this is the base domain that an integration service will use to communicate with filebrowser (eg. http://localhost:8080)", - "type": "string" - }, - "listen": { - "description": "address to listen on (default: 0.0.0.0)", - "type": "string" - }, "logging": { "type": "array", "items": { @@ -6342,27 +6226,11 @@ const docTemplate = `{ "description": "number of concurrent image processing jobs used to create previews, default is 4.", "type": "integer" }, - "port": { - "description": "port to listen on", - "type": "integer" - }, - "socket": { - "description": "socket to listen on - eg. /var/run/filebrowser.sock", - "type": "string" - }, "sources": { "type": "array", "items": { "$ref": "#/definitions/settings.Source" } - }, - "tlsCert": { - "description": "path to TLS cert", - "type": "string" - }, - "tlsKey": { - "description": "path to TLS key", - "type": "string" } } }, @@ -6385,7 +6253,12 @@ const docTemplate = `{ "$ref": "#/definitions/settings.Server" }, "userDefaults": { - "$ref": "#/definitions/settings.UserDefaults" + "description": "optional signup/CLI defaults; per-user values are managed in the UI", + "allOf": [ + { + "$ref": "#/definitions/settings.UserDefaults" + } + ] } } }, @@ -6411,14 +6284,6 @@ const docTemplate = `{ "settings.SourceConfig": { "type": "object", "properties": { - "conditionals": { - "description": "deprecated: use source.rules instead", - "allOf": [ - { - "$ref": "#/definitions/settings.ConditionalFilter" - } - ] - }, "createUserDir": { "description": "create a user directory for each user under defaultUserScope + username", "type": "boolean" @@ -6427,6 +6292,14 @@ const docTemplate = `{ "description": "should be added as a default source for new users?", "type": "boolean" }, + "defaultPermissions": { + "description": "DefaultPermissions is the template for new user scopes on this source (also synced globally via Access settings).", + "allOf": [ + { + "$ref": "#/definitions/users.SourceFilePermissions" + } + ] + }, "defaultUserScope": { "description": "defaults to root of index \"/\" should match folders under path", "type": "string" @@ -6439,10 +6312,6 @@ const docTemplate = `{ "description": "disable the source, this is useful so you don't need to remove it from the config file", "type": "boolean" }, - "indexingIntervalMinutes": { - "description": "deprecated: create a rule with indexingIntervalMinutes to set the indexing interval for this source", - "type": "integer" - }, "private": { "description": "designate as source as private -- currently just means no sharing permitted.", "type": "boolean" @@ -6498,167 +6367,26 @@ const docTemplate = `{ "account": { "$ref": "#/definitions/settings.UserDefaultsAccount" }, - "customTheme": { - "description": "deprecated: use ui.customTheme instead", - "type": "string" - }, - "darkMode": { - "description": "deprecated: use sidebar.darkMode instead", - "type": "boolean" - }, - "dateFormat": { - "description": "deprecated: use listing.dateFormat instead", - "type": "boolean" - }, - "debugOffice": { - "description": "deprecated: use fileViewer.debugOffice instead", - "type": "boolean" - }, - "deleteAfterArchive": { - "description": "deprecated: use listing.deleteAfterArchive instead", - "type": "boolean" - }, - "deleteWithoutConfirming": { - "description": "deprecated: use listing.deleteWithoutConfirming instead", - "type": "boolean" - }, - "disableOfficePreviewExt": { - "description": "deprecated: use disablePreviewExt instead", - "type": "string" - }, - "disableOnlyOfficeExt": { - "description": "deprecated: use fileViewer.disableOnlyOfficeExt instead", - "type": "string" - }, - "disablePreviewExt": { - "description": "deprecated: use preview.disablePreviewExt instead", - "type": "string" - }, - "disableQuickToggles": { - "description": "deprecated: use sidebar.disableQuickToggles instead", - "type": "boolean" - }, - "disableSearchOptions": { - "description": "deprecated: use search.disableOptions instead", - "type": "boolean" - }, - "disableSettings": { - "description": "deprecated: use account.disableSettings instead", - "type": "boolean" - }, - "disableUpdateNotifications": { - "description": "deprecated: use account.disableUpdateNotifications instead", - "type": "boolean" - }, - "disableViewingExt": { - "description": "deprecated: use fileViewer.disableViewingExt instead", - "type": "string" - }, - "editorQuickSave": { - "description": "Deprecated fields - kept for backwards compatibility", - "type": "boolean" - }, "fileLoading": { "$ref": "#/definitions/users.FileLoading" }, "fileViewer": { "$ref": "#/definitions/settings.UserDefaultsFileViewer" }, - "gallerySize": { - "description": "deprecated: use sidebar.gallerySize instead", - "type": "integer" - }, - "hideFileExt": { - "description": "deprecated: use listing.hideFileExt instead", - "type": "string" - }, - "hideFilesInTree": { - "description": "deprecated: use sidebar.hideFilesInTree instead", - "type": "boolean" - }, - "hideSidebarFileActions": { - "description": "deprecated: use sidebar.hideSidebarFileActions instead", - "type": "boolean" - }, "listing": { "$ref": "#/definitions/settings.UserDefaultsListing" }, - "locale": { - "description": "deprecated: use ui.locale instead", - "type": "string" - }, - "lockPassword": { - "description": "deprecated: use account.lockPassword instead", - "type": "boolean" - }, - "loginMethod": { - "description": "deprecated: use account.loginMethod instead", - "type": "string" - }, - "permissions": { - "description": "deprecated: use account.permissions instead", - "allOf": [ - { - "$ref": "#/definitions/settings.UserDefaultsPermissions" - } - ] - }, - "preferEditorForMarkdown": { - "description": "deprecated: use fileViewer.preferEditorForMarkdown instead", - "type": "boolean" - }, "preview": { "$ref": "#/definitions/settings.UserDefaultsPreview" }, - "quickDownload": { - "description": "deprecated: use listing.quickDownload instead", - "type": "boolean" - }, "search": { "$ref": "#/definitions/settings.UserDefaultsSearch" }, - "showCopyPath": { - "description": "deprecated: use listing.showCopyPath instead", - "type": "boolean" - }, - "showHidden": { - "description": "deprecated: use listing.showHidden instead", - "type": "boolean" - }, - "showSelectMultiple": { - "description": "deprecated: use listing.showSelectMultiple instead", - "type": "boolean" - }, - "showToolsInSidebar": { - "description": "deprecated: use sidebar.showToolsInSidebar instead", - "type": "boolean" - }, "sidebar": { - "description": "New organized structure", - "allOf": [ - { - "$ref": "#/definitions/settings.UserDefaultsSidebar" - } - ] - }, - "singleClick": { - "description": "deprecated: use sidebar.singleClick instead", - "type": "boolean" - }, - "stickySidebar": { - "description": "deprecated: use sidebar.stickySidebar instead", - "type": "boolean" - }, - "themeColor": { - "description": "deprecated: use ui.themeColor instead", - "type": "string" + "$ref": "#/definitions/settings.UserDefaultsSidebar" }, "ui": { "$ref": "#/definitions/settings.UserDefaultsUI" - }, - "viewMode": { - "description": "deprecated: use sidebar.viewMode instead", - "type": "string" } } }, @@ -6697,22 +6425,6 @@ const docTemplate = `{ "description": "allow api access", "type": "boolean" }, - "create": { - "description": "allow creating or uploading files", - "type": "boolean" - }, - "delete": { - "description": "allow deleting files", - "type": "boolean" - }, - "download": { - "description": "allow downloading files", - "type": "boolean" - }, - "modify": { - "description": "allow modifying files", - "type": "boolean" - }, "realtime": { "description": "allow realtime updates", "type": "boolean" @@ -6734,10 +6446,6 @@ const docTemplate = `{ "description": "debug onlyoffice editor", "type": "boolean" }, - "defaultMediaPlayer": { - "description": "disable the styled feature-rich media player for browser default", - "type": "boolean" - }, "disableOnlyOfficeExt": { "description": "list of file extensions to disable onlyoffice editor for", "type": "string" @@ -6805,43 +6513,6 @@ const docTemplate = `{ } } }, - "settings.UserDefaultsPermissions": { - "type": "object", - "properties": { - "admin": { - "description": "deprecated: use account.permissions.admin instead. allow admin access", - "type": "boolean" - }, - "api": { - "description": "deprecated: use account.permissions.api instead. allow api access", - "type": "boolean" - }, - "create": { - "description": "deprecated: use account.permissions.create instead. allow creating or uploading files", - "type": "boolean" - }, - "delete": { - "description": "deprecated: use account.permissions.delete instead. allow deleting files", - "type": "boolean" - }, - "download": { - "description": "deprecated: use account.permissions.download instead. allow downloading files", - "type": "boolean" - }, - "modify": { - "description": "deprecated: use account.permissions.modify instead. allow modifying files", - "type": "boolean" - }, - "realtime": { - "description": "deprecated: use account.permissions.realtime instead. allow realtime updates", - "type": "boolean" - }, - "share": { - "description": "deprecated: use account.permissions.share instead. allow sharing files", - "type": "boolean" - } - } - }, "settings.UserDefaultsPreview": { "type": "object", "properties": { @@ -6849,18 +6520,6 @@ const docTemplate = `{ "description": "show thumbnails for audio files", "type": "boolean" }, - "autoplayMedia": { - "description": "deprecated: use fileViewer.autoplayMedia instead. autoplay media files in preview", - "type": "boolean" - }, - "defaultMediaPlayer": { - "description": "deprecated: use fileViewer.defaultMediaPlayer instead. disable the styled feature-rich media player for browser default", - "type": "boolean" - }, - "disableHideSidebar": { - "description": "deprecated fields", - "type": "boolean" - }, "disablePreviewExt": { "description": "comma separated list of file extensions to disable preview for", "type": "string" @@ -6958,170 +6617,28 @@ const docTemplate = `{ } } }, - "share.CommonShare": { + "share.PinnedItems": { "type": "object", - "properties": { - "allowCreate": { - "description": "allow creating files", - "type": "boolean" - }, - "allowDelete": { - "type": "boolean" - }, - "allowModify": { - "description": "allow modifying files", - "type": "boolean" - }, - "allowReplacements": { - "description": "allow replacements of files", - "type": "boolean" - }, - "allowedUsernames": { - "type": "array", - "items": { - "type": "string" - } - }, - "banner": { - "type": "string" - }, - "bannerUrl": { - "type": "string" - }, - "canEditShare": { - "type": "boolean" - }, - "description": { - "type": "string" - }, - "disableAnonymous": { - "type": "boolean" - }, - "disableDownload": { - "description": "don't allow downloading files", - "type": "boolean" - }, - "disableFileViewer": { - "description": "don't allow viewing files", - "type": "boolean" - }, - "disableLoginOption": { - "description": "disable login option in share (true = hide, false = show)", - "type": "boolean" - }, - "disableShareCard": { - "type": "boolean" - }, - "disableSidebar": { - "type": "boolean" - }, - "disableThumbnails": { - "type": "boolean" - }, - "downloadURL": { - "type": "string" - }, - "downloadsLimit": { - "type": "integer" - }, - "enableOnlyOffice": { - "type": "boolean" - }, - "enforceDarkLightMode": { - "description": "\"dark\" or \"light\"", - "type": "string" - }, - "extractEmbeddedSubtitles": { - "description": "can be io intensive for large files and take 10-30 seconds.", - "type": "boolean" - }, - "favicon": { - "type": "string" - }, - "faviconUrl": { - "type": "string" - }, - "hasPassword": { - "type": "boolean" - }, - "hideFileExt": { - "description": "show hidden files based on extensions in shares", - "type": "string" - }, - "hideNavButtons": { - "type": "boolean" - }, - "keepAfterExpiration": { - "type": "boolean" - }, - "maxBandwidth": { - "type": "integer" - }, - "path": { - "type": "string" - }, - "perUserDownloadLimit": { - "type": "boolean" - }, - "quickDownload": { - "type": "boolean" - }, - "shareTheme": { - "type": "string" - }, - "shareType": { - "description": "type of share: normal, upload, max", - "type": "string" - }, - "shareURL": { - "type": "string" - }, - "showHidden": { - "description": "show hidden files in share (true = show, false = hide)", - "type": "boolean" - }, - "sidebarLinks": { - "description": "customizable sidebar links", - "type": "array", - "items": { - "$ref": "#/definitions/users.SidebarLink" - } - }, - "source": { - "description": "backend source is path to maintain between name changes", - "type": "string" - }, - "sourceURL": { - "type": "string" - }, - "themeColor": { - "type": "string" - }, - "title": { - "type": "string" - }, - "viewMode": { - "description": "default view mode for anonymous users: \"list\", \"compact\", \"normal\", \"gallery\"", + "additionalProperties": { + "type": "array", + "items": { "type": "string" } } }, - "share.CreateBody": { + "share.Share": { "type": "object", "properties": { "allowCreate": { - "description": "allow creating files", "type": "boolean" }, "allowDelete": { "type": "boolean" }, "allowModify": { - "description": "allow modifying files", "type": "boolean" }, "allowReplacements": { - "description": "allow replacements of files", "type": "boolean" }, "allowedUsernames": { @@ -7146,175 +6663,12 @@ const docTemplate = `{ "type": "boolean" }, "disableDownload": { - "description": "don't allow downloading files", "type": "boolean" }, "disableFileViewer": { - "description": "don't allow viewing files", "type": "boolean" }, "disableLoginOption": { - "description": "disable login option in share (true = hide, false = show)", - "type": "boolean" - }, - "disableShareCard": { - "type": "boolean" - }, - "disableSidebar": { - "type": "boolean" - }, - "disableThumbnails": { - "type": "boolean" - }, - "downloadURL": { - "type": "string" - }, - "downloadsLimit": { - "type": "integer" - }, - "enableOnlyOffice": { - "type": "boolean" - }, - "enforceDarkLightMode": { - "description": "\"dark\" or \"light\"", - "type": "string" - }, - "expires": { - "type": "string" - }, - "extractEmbeddedSubtitles": { - "description": "can be io intensive for large files and take 10-30 seconds.", - "type": "boolean" - }, - "favicon": { - "type": "string" - }, - "faviconUrl": { - "type": "string" - }, - "hasPassword": { - "type": "boolean" - }, - "hash": { - "type": "string" - }, - "hideFileExt": { - "description": "show hidden files based on extensions in shares", - "type": "string" - }, - "hideNavButtons": { - "type": "boolean" - }, - "keepAfterExpiration": { - "type": "boolean" - }, - "maxBandwidth": { - "type": "integer" - }, - "password": { - "type": "string" - }, - "path": { - "type": "string" - }, - "perUserDownloadLimit": { - "type": "boolean" - }, - "quickDownload": { - "type": "boolean" - }, - "shareTheme": { - "type": "string" - }, - "shareType": { - "description": "type of share: normal, upload, max", - "type": "string" - }, - "shareURL": { - "type": "string" - }, - "showHidden": { - "description": "show hidden files in share (true = show, false = hide)", - "type": "boolean" - }, - "sidebarLinks": { - "description": "customizable sidebar links", - "type": "array", - "items": { - "$ref": "#/definitions/users.SidebarLink" - } - }, - "source": { - "description": "backend source is path to maintain between name changes", - "type": "string" - }, - "sourceURL": { - "type": "string" - }, - "themeColor": { - "type": "string" - }, - "title": { - "type": "string" - }, - "unit": { - "type": "string" - }, - "viewMode": { - "description": "default view mode for anonymous users: \"list\", \"compact\", \"normal\", \"gallery\"", - "type": "string" - } - } - }, - "share.Link": { - "type": "object", - "properties": { - "allowCreate": { - "description": "allow creating files", - "type": "boolean" - }, - "allowDelete": { - "type": "boolean" - }, - "allowModify": { - "description": "allow modifying files", - "type": "boolean" - }, - "allowReplacements": { - "description": "allow replacements of files", - "type": "boolean" - }, - "allowedUsernames": { - "type": "array", - "items": { - "type": "string" - } - }, - "banner": { - "type": "string" - }, - "bannerUrl": { - "type": "string" - }, - "canEditShare": { - "type": "boolean" - }, - "description": { - "type": "string" - }, - "disableAnonymous": { - "type": "boolean" - }, - "disableDownload": { - "description": "don't allow downloading files", - "type": "boolean" - }, - "disableFileViewer": { - "description": "don't allow viewing files", - "type": "boolean" - }, - "disableLoginOption": { - "description": "disable login option in share (true = hide, false = show)", "type": "boolean" }, "disableShareCard": { @@ -7346,7 +6700,6 @@ const docTemplate = `{ "type": "integer" }, "extractEmbeddedSubtitles": { - "description": "can be io intensive for large files and take 10-30 seconds.", "type": "boolean" }, "favicon": { @@ -7393,25 +6746,28 @@ const docTemplate = `{ "type": "string" }, "shareType": { - "description": "type of share: normal, upload, max", "type": "string" }, "shareURL": { "type": "string" }, "showHidden": { - "description": "show hidden files in share (true = show, false = hide)", "type": "boolean" }, "sidebarLinks": { - "description": "customizable sidebar links", "type": "array", "items": { "$ref": "#/definitions/users.SidebarLink" } }, + "singleFileShare": { + "type": "boolean" + }, "source": { - "description": "backend source is path to maintain between name changes", + "description": "source display name for API; backend path is Share.SourcePath", + "type": "string" + }, + "sourcePath": { "type": "string" }, "sourceURL": { @@ -7424,11 +6780,9 @@ const docTemplate = `{ "type": "string" }, "token": { - "description": "Token is a random value that will only be set when PasswordHash is set. It is\nURL-Safe and is used to download links in password-protected shares via a\nquery arg.", "type": "string" }, "userDownloads": { - "description": "Track downloads per username", "type": "object", "additionalProperties": { "type": "integer" @@ -7441,16 +6795,322 @@ const docTemplate = `{ "type": "integer" }, "viewMode": { - "description": "default view mode for anonymous users: \"list\", \"compact\", \"normal\", \"gallery\"", + "description": "default view mode for anonymous users", "type": "string" } } }, - "share.PinnedItems": { + "share.ShareFrontend": { "type": "object", - "additionalProperties": { - "type": "array", - "items": { + "properties": { + "allowCreate": { + "type": "boolean" + }, + "allowDelete": { + "type": "boolean" + }, + "allowModify": { + "type": "boolean" + }, + "allowReplacements": { + "type": "boolean" + }, + "allowedUsernames": { + "type": "array", + "items": { + "type": "string" + } + }, + "banner": { + "type": "string" + }, + "bannerUrl": { + "type": "string" + }, + "canEditShare": { + "type": "boolean" + }, + "description": { + "type": "string" + }, + "disableAnonymous": { + "type": "boolean" + }, + "disableDownload": { + "type": "boolean" + }, + "disableFileViewer": { + "type": "boolean" + }, + "disableLoginOption": { + "type": "boolean" + }, + "disableShareCard": { + "type": "boolean" + }, + "disableSidebar": { + "type": "boolean" + }, + "disableThumbnails": { + "type": "boolean" + }, + "downloadURL": { + "type": "string" + }, + "downloads": { + "type": "integer" + }, + "downloadsLimit": { + "type": "integer" + }, + "enableOnlyOffice": { + "type": "boolean" + }, + "enforceDarkLightMode": { + "description": "\"dark\" or \"light\"", + "type": "string" + }, + "expire": { + "type": "integer" + }, + "expires": { + "type": "string" + }, + "extractEmbeddedSubtitles": { + "type": "boolean" + }, + "favicon": { + "type": "string" + }, + "faviconUrl": { + "type": "string" + }, + "hasPassword": { + "type": "boolean" + }, + "hash": { + "type": "string" + }, + "hideFileExt": { + "description": "show hidden files based on extensions in shares", + "type": "string" + }, + "hideNavButtons": { + "type": "boolean" + }, + "keepAfterExpiration": { + "type": "boolean" + }, + "maxBandwidth": { + "type": "integer" + }, + "path": { + "type": "string" + }, + "pathExists": { + "type": "boolean" + }, + "perUserDownloadLimit": { + "type": "boolean" + }, + "quickDownload": { + "type": "boolean" + }, + "shareTheme": { + "type": "string" + }, + "shareType": { + "type": "string" + }, + "shareURL": { + "type": "string" + }, + "showHidden": { + "type": "boolean" + }, + "sidebarLinks": { + "type": "array", + "items": { + "$ref": "#/definitions/users.SidebarLink" + } + }, + "singleFileShare": { + "type": "boolean" + }, + "source": { + "description": "source display name for API; backend path is Share.SourcePath", + "type": "string" + }, + "sourceURL": { + "type": "string" + }, + "themeColor": { + "type": "string" + }, + "title": { + "type": "string" + }, + "unit": { + "type": "string" + }, + "username": { + "type": "string" + }, + "viewMode": { + "description": "default view mode for anonymous users", + "type": "string" + } + } + }, + "share.SharePostBody": { + "type": "object", + "properties": { + "allowCreate": { + "type": "boolean" + }, + "allowDelete": { + "type": "boolean" + }, + "allowModify": { + "type": "boolean" + }, + "allowReplacements": { + "type": "boolean" + }, + "allowedUsernames": { + "type": "array", + "items": { + "type": "string" + } + }, + "banner": { + "type": "string" + }, + "bannerUrl": { + "type": "string" + }, + "canEditShare": { + "type": "boolean" + }, + "description": { + "type": "string" + }, + "disableAnonymous": { + "type": "boolean" + }, + "disableDownload": { + "type": "boolean" + }, + "disableFileViewer": { + "type": "boolean" + }, + "disableLoginOption": { + "type": "boolean" + }, + "disableShareCard": { + "type": "boolean" + }, + "disableSidebar": { + "type": "boolean" + }, + "disableThumbnails": { + "type": "boolean" + }, + "downloadURL": { + "type": "string" + }, + "downloadsLimit": { + "type": "integer" + }, + "enableOnlyOffice": { + "type": "boolean" + }, + "enforceDarkLightMode": { + "description": "\"dark\" or \"light\"", + "type": "string" + }, + "expires": { + "type": "string" + }, + "extractEmbeddedSubtitles": { + "type": "boolean" + }, + "favicon": { + "type": "string" + }, + "faviconUrl": { + "type": "string" + }, + "hasPassword": { + "type": "boolean" + }, + "hash": { + "type": "string" + }, + "hideFileExt": { + "description": "show hidden files based on extensions in shares", + "type": "string" + }, + "hideNavButtons": { + "type": "boolean" + }, + "keepAfterExpiration": { + "type": "boolean" + }, + "maxBandwidth": { + "type": "integer" + }, + "password": { + "type": "string" + }, + "path": { + "type": "string" + }, + "perUserDownloadLimit": { + "type": "boolean" + }, + "quickDownload": { + "type": "boolean" + }, + "shareTheme": { + "type": "string" + }, + "shareType": { + "type": "string" + }, + "shareURL": { + "type": "string" + }, + "showHidden": { + "type": "boolean" + }, + "sidebarLinks": { + "type": "array", + "items": { + "$ref": "#/definitions/users.SidebarLink" + } + }, + "singleFileShare": { + "type": "boolean" + }, + "source": { + "description": "source display name for API; backend path is Share.SourcePath", + "type": "string" + }, + "sourceURL": { + "type": "string" + }, + "themeColor": { + "type": "string" + }, + "title": { + "type": "string" + }, + "unit": { + "type": "string" + }, + "viewMode": { + "description": "default view mode for anonymous users", "type": "string" } } @@ -7462,6 +7122,7 @@ const docTemplate = `{ "$ref": "#/definitions/users.Permissions" }, "belongsTo": { + "description": "numeric user id in JWT claims (bolt-era small ids still work)", "type": "integer" }, "expiresAt": { @@ -7479,6 +7140,25 @@ const docTemplate = `{ }, "token": { "type": "string" + }, + "username": { + "type": "string" + } + } + }, + "users.BackendScope": { + "type": "object", + "properties": { + "path": { + "description": "real path for the source", + "type": "string" + }, + "permissions": { + "$ref": "#/definitions/users.SourceFilePermissions" + }, + "scope": { + "description": "index path within that source", + "type": "string" } } }, @@ -7499,6 +7179,215 @@ const docTemplate = `{ } } }, + "users.FrontendScope": { + "type": "object", + "properties": { + "name": { + "description": "Bolt: filesystem path; JSON API: display name after prepForFrontend", + "type": "string" + }, + "permissions": { + "$ref": "#/definitions/users.SourceFilePermissions" + }, + "scope": { + "description": "index path within that source", + "type": "string" + } + } + }, + "users.FrontendUser": { + "type": "object", + "properties": { + "customTheme": { + "description": "Name of theme to use chosen from custom themes config.", + "type": "string" + }, + "darkMode": { + "description": "should dark mode be enabled", + "type": "boolean" + }, + "dateFormat": { + "description": "when false, the date is relative, when true, the date is an exact timestamp", + "type": "boolean" + }, + "debugOffice": { + "description": "debug onlyoffice editor", + "type": "boolean" + }, + "deleteAfterArchive": { + "description": "delete source files after successful creation/extraction of archives", + "type": "boolean" + }, + "deleteWithoutConfirming": { + "description": "delete files without confirmation", + "type": "boolean" + }, + "disableOfficePreviewExt": { + "description": "deprecated", + "type": "string" + }, + "disableOnlyOfficeExt": { + "description": "deprecated", + "type": "string" + }, + "disablePreviewExt": { + "description": "space separated list of file extensions to disable preview for", + "type": "string" + }, + "disableQuickToggles": { + "description": "disable the quick toggles in the sidebar", + "type": "boolean" + }, + "disableSearchOptions": { + "description": "disable the search options in the search bar", + "type": "boolean" + }, + "disableSettings": { + "type": "boolean" + }, + "disableUpdateNotifications": { + "description": "disable update notifications", + "type": "boolean" + }, + "disableViewingExt": { + "description": "space separated list of file extensions to disable viewing for", + "type": "string" + }, + "editorQuickSave": { + "description": "show quick save button in editor", + "type": "boolean" + }, + "fileLoading": { + "description": "upload and download settings", + "allOf": [ + { + "$ref": "#/definitions/users.FileLoading" + } + ] + }, + "gallerySize": { + "description": "0-9 - the size of the gallery thumbnails", + "type": "integer" + }, + "hideFileExt": { + "description": "space separated list of file extensions to hide in UI and API", + "type": "string" + }, + "hideFilesInTree": { + "description": "hide files in the sidebar tree navigation, when true, will show only directories.", + "type": "boolean" + }, + "hideSidebarFileActions": { + "description": "hide the file actions in the sidebar", + "type": "boolean" + }, + "locale": { + "description": "language to use: eg. de, en, or fr", + "type": "string" + }, + "lockPassword": { + "type": "boolean" + }, + "loginMethod": { + "$ref": "#/definitions/users.LoginMethod" + }, + "otpEnabled": { + "type": "boolean" + }, + "passkeyCredentials": { + "type": "array", + "items": { + "$ref": "#/definitions/users.WebAuthnCredential" + } + }, + "password": { + "type": "string" + }, + "perm": { + "$ref": "#/definitions/users.Permissions" + }, + "permissions": { + "description": "global: admin, api, share, realtime", + "allOf": [ + { + "$ref": "#/definitions/users.Permissions" + } + ] + }, + "preferEditorForMarkdown": { + "description": "prefer editor first for markdown files instead of the Markdown Viewer", + "type": "boolean" + }, + "preview": { + "$ref": "#/definitions/users.Preview" + }, + "quickDownload": { + "description": "show icon to download in one click", + "type": "boolean" + }, + "scopes": { + "type": "array", + "items": { + "$ref": "#/definitions/users.FrontendScope" + } + }, + "showCopyPath": { + "description": "show copy path action in the context menu", + "type": "boolean" + }, + "showFirstLogin": { + "type": "boolean" + }, + "showHidden": { + "description": "show hidden files in the UI. On windows this includes files starting with a dot and windows hidden files", + "type": "boolean" + }, + "showSelectMultiple": { + "description": "show select multiple files on desktop", + "type": "boolean" + }, + "showToolsInSidebar": { + "description": "when false, sidebar hides links with category \"tool\" (default: true)", + "type": "boolean" + }, + "sidebarLinks": { + "description": "customizable sidebar links", + "type": "array", + "items": { + "$ref": "#/definitions/users.SidebarLink" + } + }, + "singleClick": { + "description": "open directory on single click, also enables middle click to open in new tab", + "type": "boolean" + }, + "sorting": { + "$ref": "#/definitions/users.Sorting" + }, + "sourcePermissions": { + "description": "deprecated: use scopes[].permissions", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/users.SourceFilePermissions" + } + }, + "stickySidebar": { + "description": "keep sidebar open when navigating", + "type": "boolean" + }, + "themeColor": { + "description": "theme color to use: eg. #ff0000, or var(--red), var(--purple), etc", + "type": "string" + }, + "username": { + "type": "string" + }, + "viewMode": { + "description": "view mode to use: eg. normal, list, grid, or compact", + "type": "string" + } + } + }, "users.LoginMethod": { "type": "string", "enum": [ @@ -7528,19 +7417,19 @@ const docTemplate = `{ "type": "boolean" }, "create": { - "description": "allow creating or uploading files", + "description": "deprecated: legacy user migration only; not used for API tokens", "type": "boolean" }, "delete": { - "description": "allow deleting files", + "description": "deprecated: legacy user migration only; not used for API tokens", "type": "boolean" }, "download": { - "description": "allow downloading files", + "description": "deprecated: legacy user migration only; not used for API tokens", "type": "boolean" }, "modify": { - "description": "allow modifying files", + "description": "deprecated: legacy user migration only; not used for API tokens", "type": "boolean" }, "realtime": { @@ -7550,6 +7439,10 @@ const docTemplate = `{ "share": { "description": "allow sharing files", "type": "boolean" + }, + "view": { + "description": "deprecated: legacy user migration only; not used for API tokens", + "type": "boolean" } } }, @@ -7576,10 +7469,6 @@ const docTemplate = `{ "description": "autoplay media files in preview", "type": "boolean" }, - "defaultMediaPlayer": { - "description": "disable html5 media player and use the default media player", - "type": "boolean" - }, "disableHideSidebar": { "description": "disable the hide sidebar preview for previews and editors", "type": "boolean" @@ -7650,16 +7539,27 @@ const docTemplate = `{ } } }, - "users.SourceScope": { + "users.SourceFilePermissions": { "type": "object", "properties": { - "name": { - "description": "Bolt: filesystem path; JSON API: display name after prepForFrontend", - "type": "string" + "configured": { + "description": "true when explicitly set (allows intentional deny-all)", + "type": "boolean" }, - "scope": { - "description": "index path within that source", - "type": "string" + "create": { + "type": "boolean" + }, + "delete": { + "type": "boolean" + }, + "download": { + "type": "boolean" + }, + "modify": { + "type": "boolean" + }, + "view": { + "type": "boolean" } } }, @@ -7667,12 +7567,25 @@ const docTemplate = `{ "type": "object", "properties": { "apiKeys": { - "description": "deprecated: use Tokens instead", "type": "object", "additionalProperties": { "$ref": "#/definitions/users.AuthToken" } }, + "backendScopes": { + "description": "BackendScopes is the authoritative, persisted access list (SourceScope.Name = backend source path).\nSQLite stores this inside user_data JSON under the key \"scopes\" (see sqldb.UserData).", + "type": "array", + "items": { + "$ref": "#/definitions/users.BackendScope" + } + }, + "backendSourcePermissions": { + "description": "key = source path", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/users.SourceFilePermissions" + } + }, "customTheme": { "description": "Name of theme to use chosen from custom themes config.", "type": "string" @@ -7770,7 +7683,6 @@ const docTemplate = `{ "$ref": "#/definitions/users.LoginMethod" }, "otpEnabled": { - "description": "true if TOTP is enabled, false otherwise", "type": "boolean" }, "passkeyCredentials": { @@ -7783,16 +7695,16 @@ const docTemplate = `{ "type": "string" }, "perm": { - "description": "legacy for migration purposes... og filebrowser has perm attribute", + "$ref": "#/definitions/users.Permissions" + }, + "permissions": { + "description": "global: admin, api, share, realtime", "allOf": [ { "$ref": "#/definitions/users.Permissions" } ] }, - "permissions": { - "$ref": "#/definitions/users.Permissions" - }, "pinnedItems": { "$ref": "#/definitions/users.PinnedItems" }, @@ -7807,13 +7719,10 @@ const docTemplate = `{ "description": "show icon to download in one click", "type": "boolean" }, - "scope": { - "type": "string" - }, "scopes": { "type": "array", "items": { - "$ref": "#/definitions/users.SourceScope" + "$ref": "#/definitions/users.FrontendScope" } }, "showCopyPath": { @@ -7849,6 +7758,13 @@ const docTemplate = `{ "sorting": { "$ref": "#/definitions/users.Sorting" }, + "sourcePermissions": { + "description": "deprecated: use scopes[].permissions", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/users.SourceFilePermissions" + } + }, "stickySidebar": { "description": "keep sidebar open when navigating", "type": "boolean" @@ -7985,6 +7901,346 @@ const docTemplate = `{ "type": "string" } } + }, + "web.AuthTokenFrontend": { + "type": "object", + "properties": { + "Permissions": { + "$ref": "#/definitions/users.Permissions" + }, + "expiresAt": { + "type": "integer" + }, + "issuedAt": { + "type": "integer" + }, + "minimal": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "token": { + "type": "string" + } + } + }, + "web.BulkDeleteItem": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "path": { + "type": "string" + }, + "source": { + "type": "string" + } + } + }, + "web.BulkDeleteResponse": { + "type": "object", + "properties": { + "failed": { + "type": "array", + "items": { + "$ref": "#/definitions/web.BulkDeleteItem" + } + }, + "succeeded": { + "type": "array", + "items": { + "$ref": "#/definitions/web.BulkDeleteItem" + } + } + } + }, + "web.DirectDownloadResponse": { + "type": "object", + "properties": { + "hash": { + "type": "string" + }, + "shareUrl": { + "type": "string" + }, + "status": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "web.GroupListResponse": { + "type": "object", + "properties": { + "groups": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "web.HttpResponse": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "status": { + "type": "integer" + }, + "token": { + "type": "string" + } + } + }, + "web.MoveCopyItem": { + "type": "object", + "properties": { + "fromPath": { + "type": "string" + }, + "fromSource": { + "type": "string" + }, + "message": { + "type": "string" + }, + "toPath": { + "type": "string" + }, + "toSource": { + "type": "string" + } + } + }, + "web.MoveCopyRequest": { + "type": "object", + "properties": { + "action": { + "description": "\"copy\", \"move\", or \"rename\"", + "type": "string" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/definitions/web.MoveCopyItem" + } + }, + "overwrite": { + "description": "Overwrite if destination exists", + "type": "boolean" + }, + "rename": { + "description": "Auto-rename if destination exists", + "type": "boolean" + } + } + }, + "web.MoveCopyResponse": { + "type": "object", + "properties": { + "failed": { + "type": "array", + "items": { + "$ref": "#/definitions/web.MoveCopyItem" + } + }, + "succeeded": { + "type": "array", + "items": { + "$ref": "#/definitions/web.MoveCopyItem" + } + } + } + }, + "web.archiveCreateRequest": { + "type": "object", + "properties": { + "compression": { + "description": "Gzip compression level for tar.gz only, 0-9; 0 = default; ignored for zip (optional). Example: 6", + "type": "integer" + }, + "deleteAfter": { + "description": "If true, delete the source files/directories after successful archive creation (optional; requires delete permission). Example: true", + "type": "boolean" + }, + "destination": { + "description": "Full path where the archive will be created; use .zip or .tar.gz extension (required). Example: \"/backups/my-archive.zip\"", + "type": "string" + }, + "format": { + "description": "Archive format: \"zip\" or \"tar.gz\" (optional; inferred from destination if omitted). Example: \"zip\"", + "type": "string" + }, + "fromSource": { + "description": "Source name where the paths to archive live (required). Example: \"default\"", + "type": "string" + }, + "paths": { + "description": "Paths of files or directories to add; directories are walked; access-denied entries skipped (required). Example: [\"/docs/file.txt\", \"/photos\"]", + "type": "array", + "items": { + "type": "string" + } + }, + "toSource": { + "description": "Source name where the archive file will be written (optional; default: fromSource). Example: \"backups\"", + "type": "string" + } + } + }, + "web.duplicateGroup": { + "type": "object", + "properties": { + "count": { + "type": "integer" + }, + "files": { + "type": "array", + "items": { + "$ref": "#/definitions/indexing.SearchResult" + } + }, + "size": { + "type": "integer" + } + } + }, + "web.duplicateResponse": { + "type": "object", + "properties": { + "groups": { + "type": "array", + "items": { + "$ref": "#/definitions/web.duplicateGroup" + } + }, + "incomplete": { + "type": "boolean" + }, + "reason": { + "type": "string" + } + } + }, + "web.fileWatchMetadata": { + "type": "object", + "properties": { + "modified": { + "description": "Modification time", + "type": "string" + }, + "name": { + "description": "File name", + "type": "string" + }, + "size": { + "description": "File size in bytes (for directories, total size of all files)", + "type": "integer" + }, + "type": { + "description": "MIME type", + "type": "string" + } + } + }, + "web.fileWatchResponse": { + "type": "object", + "properties": { + "contents": { + "description": "Text content for text files", + "type": "string" + }, + "isText": { + "description": "Whether the file is a text file", + "type": "boolean" + }, + "metadata": { + "description": "File metadata for non-text files", + "allOf": [ + { + "$ref": "#/definitions/web.fileWatchMetadata" + } + ] + } + } + }, + "web.pinnedItemPatchRequest": { + "type": "object", + "required": [ + "name", + "path", + "source" + ], + "properties": { + "name": { + "description": "item basename within path", + "type": "string" + }, + "path": { + "description": "scope-relative parent directory", + "type": "string" + }, + "source": { + "type": "string" + } + } + }, + "web.sharePinnedItemPatchRequest": { + "type": "object", + "required": [ + "name", + "path" + ], + "properties": { + "name": { + "type": "string" + }, + "path": { + "type": "string" + } + } + }, + "web.unarchiveRequest": { + "type": "object", + "properties": { + "deleteAfter": { + "description": "If true, delete the archive file after successful extraction (optional; default: false). Example: true", + "type": "boolean" + }, + "destination": { + "description": "Directory path on toSource to extract into (required). Example: \"/projects/imported\"", + "type": "string" + }, + "fromSource": { + "description": "Source name where the archive file lives (required). Example: \"default\"", + "type": "string" + }, + "path": { + "description": "Path to the archive file on fromSource; .zip, .tar.gz, or .tgz (required). Example: \"/downloads/data.zip\"", + "type": "string" + }, + "toSource": { + "description": "Source name where contents will be extracted (optional; default: fromSource). Example: \"restored\"", + "type": "string" + } + } + }, + "web.viewTokenResponse": { + "type": "object", + "properties": { + "expiresAt": { + "type": "integer" + }, + "viewToken": { + "type": "string" + } + } } } }` diff --git a/backend/swagger/docs/swagger.json b/backend/swagger/docs/swagger.json index d6c9710dc4..75e6fc2d2a 100644 --- a/backend/swagger/docs/swagger.json +++ b/backend/swagger/docs/swagger.json @@ -438,7 +438,7 @@ "200": { "description": "Object containing a list of groups", "schema": { - "$ref": "#/definitions/http.GroupListResponse" + "$ref": "#/definitions/web.GroupListResponse" } }, "403": { @@ -739,7 +739,7 @@ "200": { "description": "OTP token is valid.", "schema": { - "$ref": "#/definitions/http.HttpResponse" + "$ref": "#/definitions/web.HttpResponse" } }, "401": { @@ -885,7 +885,7 @@ "200": { "description": "API token details", "schema": { - "$ref": "#/definitions/http.AuthTokenFrontend" + "$ref": "#/definitions/web.AuthTokenFrontend" } }, "404": { @@ -937,17 +937,22 @@ }, { "type": "string", - "description": "Permissions for the API token (comma-separated)", + "description": "Global permissions (comma-separated: admin, api, share, realtime). Send \\", "name": "permissions", - "in": "query", - "required": true + "in": "query" + }, + { + "type": "boolean", + "description": "When true, create a minimal token (standard JWT claims only). When false, create a customized token using permissions (may be empty).", + "name": "minimal", + "in": "query" } ], "responses": { "200": { "description": "Token created successfully, response contains json object with token", "schema": { - "$ref": "#/definitions/http.HttpResponse" + "$ref": "#/definitions/web.HttpResponse" } }, "400": { @@ -1013,7 +1018,7 @@ "200": { "description": "API token deleted successfully", "schema": { - "$ref": "#/definitions/http.HttpResponse" + "$ref": "#/definitions/web.HttpResponse" } }, "404": { @@ -1056,7 +1061,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/http.AuthTokenFrontend" + "$ref": "#/definitions/web.AuthTokenFrontend" } } }, @@ -1303,7 +1308,7 @@ "application/json" ], "tags": [ - "Resources" + "Media" ], "summary": "Get lyrics for an audio file", "parameters": [ @@ -1361,7 +1366,7 @@ "application/json" ], "tags": [ - "Resources" + "Media" ], "summary": "Directory with media metadata", "parameters": [ @@ -1414,6 +1419,76 @@ } } }, + "/api/media/stream": { + "get": { + "description": "Returns raw file bytes for inline UI viewing in capped byte ranges. Requires a viewToken minted by GET /resources. Media files must use Range requests; full-file GET responses are rejected. Never counts toward download limits or activity.", + "consumes": [ + "application/json" + ], + "tags": [ + "Resources" + ], + "summary": "Stream content of a single media file for inline viewing", + "parameters": [ + { + "type": "string", + "description": "Source name for the file (required)", + "name": "source", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "File path", + "name": "file", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Opaque view grant token from file metadata", + "name": "viewToken", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "Raw file content (inline)", + "schema": { + "type": "file" + } + }, + "403": { + "description": "Missing or invalid view token", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "404": { + "description": "File not found", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "500": { + "description": "Internal server error", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } + }, "/api/media/subtitles": { "get": { "description": "Returns raw subtitle content from external files or embedded streams", @@ -1424,7 +1499,7 @@ "text/plain" ], "tags": [ - "Resources" + "Media" ], "summary": "Get subtitle content", "parameters": [ @@ -2013,7 +2088,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/http.MoveCopyRequest" + "$ref": "#/definitions/web.MoveCopyRequest" } } ], @@ -2021,13 +2096,13 @@ "200": { "description": "All operations completed successfully", "schema": { - "$ref": "#/definitions/http.MoveCopyResponse" + "$ref": "#/definitions/web.MoveCopyResponse" } }, "207": { "description": "Partial success - some operations succeeded, some failed", "schema": { - "$ref": "#/definitions/http.MoveCopyResponse" + "$ref": "#/definitions/web.MoveCopyResponse" } }, "400": { @@ -2060,7 +2135,7 @@ "500": { "description": "All operations failed", "schema": { - "$ref": "#/definitions/http.MoveCopyResponse" + "$ref": "#/definitions/web.MoveCopyResponse" } } } @@ -2086,7 +2161,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/http.archiveCreateRequest" + "$ref": "#/definitions/web.archiveCreateRequest" } } ], @@ -2170,7 +2245,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/http.BulkDeleteItem" + "$ref": "#/definitions/web.BulkDeleteItem" } } } @@ -2179,13 +2254,13 @@ "200": { "description": "All resources deleted successfully", "schema": { - "$ref": "#/definitions/http.BulkDeleteResponse" + "$ref": "#/definitions/web.BulkDeleteResponse" } }, "207": { "description": "Partial success - some resources deleted, some failed", "schema": { - "$ref": "#/definitions/http.BulkDeleteResponse" + "$ref": "#/definitions/web.BulkDeleteResponse" } }, "400": { @@ -2455,7 +2530,7 @@ }, { "type": "string", - "description": "Preview size ('small' or 'large'). Default is based on server config.", + "description": "Preview size ('small' or 'large'). Default is based on server settings.Config.", "name": "size", "in": "query" } @@ -2544,7 +2619,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/http.unarchiveRequest" + "$ref": "#/definitions/web.unarchiveRequest" } } ], @@ -2606,6 +2681,128 @@ } } }, + "/api/resources/view": { + "get": { + "description": "Returns raw file bytes for inline UI viewing. Requires a viewToken minted by GET /resources. Never counts toward download limits or activity and does not require download permission.", + "consumes": [ + "application/json" + ], + "tags": [ + "Resources" + ], + "summary": "View content of a single non-media file inline", + "parameters": [ + { + "type": "string", + "description": "Source name for the file (required)", + "name": "source", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "File path", + "name": "file", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Opaque view grant token from file metadata", + "name": "viewToken", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "Raw file content (inline)", + "schema": { + "type": "file" + } + }, + "403": { + "description": "Missing or invalid view token", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "404": { + "description": "File not found", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "500": { + "description": "Internal server error", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } + }, + "/api/resources/view-token": { + "post": { + "description": "Mints or extends a source-scoped view token for inline viewing. Authenticated routes require a web session (not a named API token). Public share routes accept anonymous users when the share allows it.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Resources" + ], + "summary": "Refresh view token", + "parameters": [ + { + "type": "string", + "description": "Source name or share hash", + "name": "source", + "in": "query" + }, + { + "type": "string", + "description": "Share hash (public share routes)", + "name": "hash", + "in": "query" + }, + { + "type": "string", + "description": "Existing view token to extend", + "name": "viewToken", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.viewTokenResponse" + } + }, + "403": { + "description": "Missing permission or API token used", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } + }, "/api/settings": { "get": { "description": "Returns the current configuration settings for signup, user directories, rules, frontend.", @@ -2709,7 +2906,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/share.Link" + "$ref": "#/definitions/share.ShareFrontend" } } }, @@ -2743,7 +2940,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/share.CreateBody" + "$ref": "#/definitions/share.SharePostBody" } } ], @@ -2751,7 +2948,7 @@ "200": { "description": "Created share link", "schema": { - "$ref": "#/definitions/share.Link" + "$ref": "#/definitions/share.ShareFrontend" } }, "400": { @@ -2854,7 +3051,7 @@ "200": { "description": "Updated share link", "schema": { - "$ref": "#/definitions/http.ShareResponse" + "$ref": "#/definitions/share.ShareFrontend" } }, "400": { @@ -2929,7 +3126,7 @@ "201": { "description": "Direct download link created", "schema": { - "$ref": "#/definitions/http.DirectDownloadResponse" + "$ref": "#/definitions/web.DirectDownloadResponse" } }, "400": { @@ -2981,7 +3178,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/share.Link" + "$ref": "#/definitions/share.ShareFrontend" } } }, @@ -2997,7 +3194,7 @@ } } }, - "/api/tools/duplicateFinder": { + "/api/tools/duplicate-finder": { "get": { "description": "Finds duplicate files using multi-stage filtering: size → type → fuzzy filename → progressive checksums. Files must match on size, MIME type, and have 50%+ filename similarity before checksum verification. Large fuzzy groups (\u003e10 files) are skipped to avoid false positives. Checksums use 2-pass progressive verification (header → middle) for accuracy while minimizing disk I/O (~16KB read per file).", "consumes": [ @@ -3035,7 +3232,7 @@ "200": { "description": "List of duplicate file groups with metadata. Response includes 'incomplete' flag if processing stopped early due to resource limits.", "schema": { - "$ref": "#/definitions/http.duplicateResponse" + "$ref": "#/definitions/web.duplicateResponse" } }, "400": { @@ -3059,7 +3256,7 @@ } } }, - "/api/tools/fileWatcher": { + "/api/tools/file-watcher": { "get": { "description": "Returns the last N lines of a file", "consumes": [ @@ -3104,7 +3301,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/http.fileWatchResponse" + "$ref": "#/definitions/web.fileWatchResponse" } }, "400": { @@ -3146,7 +3343,7 @@ } } }, - "/api/tools/fileWatcher/sse": { + "/api/tools/file-watcher/sse": { "get": { "description": "Establishes an SSE connection to receive periodic file updates", "tags": [ @@ -3231,7 +3428,7 @@ "parameters": [ { "type": "string", - "description": "Filter prefix or full legacy search text (required when no terms are supplied)", + "description": "Filter prefix or full search text (required when no terms are supplied)", "name": "query", "in": "query" }, @@ -3245,12 +3442,6 @@ "name": "terms", "in": "query" }, - { - "type": "string", - "description": "Source name for the desired source (deprecated, use 'sources' instead)", - "name": "source", - "in": "query" - }, { "type": "string", "description": "Comma-separated source names when not using repeated scope=source:path", @@ -3263,7 +3454,7 @@ "type": "string" }, "collectionFormat": "csv", - "description": "Repeated: either 'sourceName:relativePath' per source, or legacy single path when one source", + "description": "Repeated: 'sourceName:relativePath' per source", "name": "scope", "in": "query" }, @@ -3285,18 +3476,6 @@ "name": "useWildcard", "in": "query" }, - { - "type": "boolean", - "description": "Deprecated: alias for useWildcard", - "name": "glob", - "in": "query" - }, - { - "type": "boolean", - "description": "Deprecated: alias for useWildcard", - "name": "useGlob", - "in": "query" - }, { "type": "string", "description": "Optional: 'and' to require all repeated 'terms' match; default is OR", @@ -3328,7 +3507,7 @@ }, "/api/users": { "get": { - "description": "Returns a user's details based on their ID, or all users if no id is provided.", + "description": "Returns all users (admins) or only the current user; with ?username=self, the logged-in user; with ?username=login, that user if permitted. Query id= is not supported.", "consumes": [ "application/json" ], @@ -3338,12 +3517,12 @@ "tags": [ "Users" ], - "summary": "Retrieve a user by ID", + "summary": "List users or get one by username", "parameters": [ { "type": "string", - "description": "User ID or 'self'", - "name": "id", + "description": "Login name, or 'self' for the current session user", + "name": "username", "in": "query" } ], @@ -3351,7 +3530,16 @@ "200": { "description": "User details or list of users", "schema": { - "$ref": "#/definitions/users.User" + "$ref": "#/definitions/users.FrontendUser" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } } }, "403": { @@ -3383,86 +3571,6 @@ } } }, - "put": { - "description": "Updates the details of a user identified by ID. When the authenticated actor uses password login, they must send their current password in the X-Password header unless the update only touches NonAdminEditable profile fields (not password). Full updates (which empty or \"all\") or any admin-only field require confirmation.", - "consumes": [ - "application/json" - ], - "tags": [ - "Users" - ], - "summary": "Update a user's details", - "parameters": [ - { - "type": "string", - "description": "user ID to update", - "name": "id", - "in": "query" - }, - { - "type": "string", - "description": "usename to update", - "name": "id", - "in": "query" - }, - { - "type": "string", - "description": "Actor's current password (URL-encoded); required for password-login actors when updating password, using which=all, or any field outside NonAdminEditable", - "name": "X-Password", - "in": "header" - }, - { - "description": "User data to update", - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/users.User" - } - } - ], - "responses": { - "204": { - "description": "No Content - User updated successfully" - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - }, - "401": { - "description": "Unauthorized - invalid or missing actor password when required", - "schema": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - }, - "403": { - "description": "Forbidden", - "schema": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - } - } - }, "post": { "description": "Adds a new user to the system. When the authenticated actor uses password login, they must send their current password in the X-Password header.", "consumes": [ @@ -3529,7 +3637,7 @@ } }, "delete": { - "description": "Deletes a user identified by their ID. When the authenticated actor uses password login, they must send their current password in the X-Password header.", + "description": "Deletes a user identified by login name.", "consumes": [ "application/json" ], @@ -3539,26 +3647,91 @@ "tags": [ "Users" ], - "summary": "Delete a user by ID", + "summary": "Delete a user by username", "parameters": [ { "type": "string", - "description": "User ID", - "name": "id", + "description": "Username", + "name": "username", "in": "query", "required": true - }, - { - "type": "string", - "description": "Actor's current password (URL-encoded); required for password-login actors", - "name": "X-Password", - "in": "header" } ], "responses": { "200": { "description": "User deleted successfully" }, + "403": { + "description": "Forbidden", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + }, + "patch": { + "description": "Updates the details of a user identified by ID. which must list the JSON field names to update. When the authenticated actor uses password login, they must send their current password in the X-Password header unless the update only touches NonAdminEditable profile fields (not password). Any admin-only field requires confirmation.", + "consumes": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Update a user's details", + "parameters": [ + { + "type": "string", + "description": "user ID to update", + "name": "id", + "in": "query" + }, + { + "type": "string", + "description": "usename to update", + "name": "id", + "in": "query" + }, + { + "type": "string", + "description": "Actor's current password (URL-encoded); required for password-login actors when updating password or any field outside NonAdminEditable", + "name": "X-Password", + "in": "header" + }, + { + "description": "User data to update", + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/users.User" + } + } + ], + "responses": { + "204": { + "description": "No Content - User updated successfully" + }, + "400": { + "description": "Bad Request", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, "401": { "description": "Unauthorized - invalid or missing actor password when required", "schema": { @@ -3589,7 +3762,7 @@ } } }, - "/api/users/pinnedItems": { + "/api/users/pinned-items": { "patch": { "description": "Patches one pinned item at a time. Defaults to add; pass ?action=remove to unpin.", "consumes": [ @@ -3615,7 +3788,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/http.pinnedItemPatchRequest" + "$ref": "#/definitions/web.pinnedItemPatchRequest" } } ], @@ -3653,33 +3826,13 @@ } } }, - "/health": { - "get": { - "description": "Returns the health status of the API.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "summary": "Health Check", - "responses": { - "200": { - "description": "successful health check response", - "schema": { - "$ref": "#/definitions/http.HttpResponse" - } - } - } - } - }, "/public/api/media/lyrics": { "get": { "produces": [ "application/json" ], "tags": [ - "Shares" + "Media" ], "summary": "Get lyrics for an audio file (public share)", "parameters": [ @@ -3732,7 +3885,7 @@ "application/json" ], "tags": [ - "Shares" + "Media" ], "summary": "Directory with media metadata (public share)", "parameters": [ @@ -3766,6 +3919,79 @@ } } }, + "/public/api/media/stream": { + "get": { + "description": "Returns raw file bytes for inline UI viewing in capped byte ranges on a share link. Requires viewToken from GET /public/api/resources. Media files must use Range requests. Does not count toward download limits.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/octet-stream" + ], + "tags": [ + "Resources" + ], + "summary": "Stream a single media file from a public share for inline viewing", + "parameters": [ + { + "type": "string", + "description": "Share hash for authentication", + "name": "hash", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "File path within the share", + "name": "file", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Opaque view grant token from share file metadata", + "name": "viewToken", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "Raw file content (inline)", + "schema": { + "type": "file" + } + }, + "403": { + "description": "Missing or invalid view token", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "404": { + "description": "Share or file not found", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "500": { + "description": "Internal server error", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } + }, "/public/api/resources": { "get": { "description": "Returns metadata for files or directories accessible via a public share link. Browsing is disabled for upload-only shares.", @@ -3776,7 +4002,7 @@ "application/json" ], "tags": [ - "Shares" + "Resources" ], "summary": "Get file/directory information from a public share", "parameters": [ @@ -3860,7 +4086,7 @@ "application/json" ], "tags": [ - "Shares" + "Resources" ], "summary": "Update a file in a public share", "parameters": [ @@ -3945,7 +4171,7 @@ "application/json" ], "tags": [ - "Shares" + "Resources" ], "summary": "Upload files to a public upload share", "parameters": [ @@ -4058,7 +4284,7 @@ "application/json" ], "tags": [ - "Shares" + "Resources" ], "summary": "Move, copy, or rename resources in a public share", "parameters": [ @@ -4075,7 +4301,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/http.MoveCopyRequest" + "$ref": "#/definitions/web.MoveCopyRequest" } } ], @@ -4083,13 +4309,13 @@ "200": { "description": "All operations completed successfully", "schema": { - "$ref": "#/definitions/http.MoveCopyResponse" + "$ref": "#/definitions/web.MoveCopyResponse" } }, "207": { "description": "Partial success - some operations succeeded, some failed", "schema": { - "$ref": "#/definitions/http.MoveCopyResponse" + "$ref": "#/definitions/web.MoveCopyResponse" } }, "400": { @@ -4122,7 +4348,7 @@ "500": { "description": "Internal server error", "schema": { - "$ref": "#/definitions/http.MoveCopyResponse" + "$ref": "#/definitions/web.MoveCopyResponse" } } } @@ -4138,7 +4364,7 @@ "application/json" ], "tags": [ - "Shares" + "Resources" ], "summary": "Bulk delete resources from public share", "parameters": [ @@ -4157,7 +4383,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/http.BulkDeleteItem" + "$ref": "#/definitions/web.BulkDeleteItem" } } } @@ -4166,13 +4392,13 @@ "200": { "description": "All resources deleted successfully", "schema": { - "$ref": "#/definitions/http.BulkDeleteResponse" + "$ref": "#/definitions/web.BulkDeleteResponse" } }, "207": { "description": "Partial success - some resources deleted, some failed", "schema": { - "$ref": "#/definitions/http.BulkDeleteResponse" + "$ref": "#/definitions/web.BulkDeleteResponse" } }, "400": { @@ -4215,7 +4441,7 @@ "application/octet-stream" ], "tags": [ - "Shares" + "Resources" ], "summary": "Download files from a public share", "parameters": [ @@ -4315,7 +4541,7 @@ "application/json" ], "tags": [ - "Shares" + "Resources" ], "summary": "Get directory items (public share)", "parameters": [ @@ -4386,7 +4612,7 @@ "application/json" ], "tags": [ - "Shares" + "Resources" ], "summary": "Register graceful chunked upload pause (public share)", "parameters": [ @@ -4440,7 +4666,7 @@ "image/jpeg" ], "tags": [ - "Shares" + "Resources" ], "summary": "Get image/video preview from a public share", "parameters": [ @@ -4460,7 +4686,7 @@ }, { "type": "string", - "description": "Preview size: 'small' or 'large'. Default is based on server config.", + "description": "Preview size: 'small' or 'large'. Default is based on server settings.Config.", "name": "size", "in": "query" } @@ -4511,6 +4737,131 @@ } } }, + "/public/api/resources/view": { + "get": { + "description": "Returns raw file bytes for inline UI viewing on a share link. Requires viewToken from GET /public/api/resources. Does not count toward download limits.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/octet-stream" + ], + "tags": [ + "Resources" + ], + "summary": "View a single non-media file from a public share inline", + "parameters": [ + { + "type": "string", + "description": "Share hash for authentication", + "name": "hash", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "File path within the share", + "name": "file", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Opaque view grant token from share file metadata", + "name": "viewToken", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "Raw file content (inline)", + "schema": { + "type": "file" + } + }, + "403": { + "description": "Missing or invalid view token", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "404": { + "description": "Share or file not found", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "500": { + "description": "Internal server error", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } + }, + "/public/api/resources/view-token": { + "post": { + "description": "Mints or extends a source-scoped view token for inline viewing. Authenticated routes require a web session (not a named API token). Public share routes accept anonymous users when the share allows it.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Resources" + ], + "summary": "Refresh view token", + "parameters": [ + { + "type": "string", + "description": "Source name or share hash", + "name": "source", + "in": "query" + }, + { + "type": "string", + "description": "Share hash (public share routes)", + "name": "hash", + "in": "query" + }, + { + "type": "string", + "description": "Existing view token to extend", + "name": "viewToken", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.viewTokenResponse" + } + }, + "403": { + "description": "Missing permission or API token used", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } + }, "/public/api/share/image": { "get": { "description": "Returns a resizable preview (large size) for the banner or favicon file of a share", @@ -4605,7 +4956,7 @@ "200": { "description": "Share information", "schema": { - "$ref": "#/definitions/share.CommonShare" + "$ref": "#/definitions/share.Share" } }, "404": { @@ -4620,9 +4971,9 @@ } } }, - "/public/api/share/pinnedItems": { + "/public/api/share/pinned-items": { "patch": { - "description": "Patches one pinned item at a time for share owners. Defaults to add; pass ?action=remove to unpin.", + "description": "Patches one pinned item at a time on a share. Defaults to add; pass ?action=remove to unpin.", "consumes": [ "application/json" ], @@ -4630,7 +4981,7 @@ "application/json" ], "tags": [ - "Shares" + "Share" ], "summary": "Add or remove a pinned item on a share", "parameters": [ @@ -4653,7 +5004,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/http.sharePinnedItemPatchRequest" + "$ref": "#/definitions/web.sharePinnedItemPatchRequest" } } ], @@ -4680,7 +5031,7 @@ } }, "404": { - "description": "Share not found", + "description": "Not Found", "schema": { "type": "object", "additionalProperties": { @@ -4719,520 +5070,6 @@ } } }, - "http.AuthTokenFrontend": { - "type": "object", - "properties": { - "Permissions": { - "$ref": "#/definitions/users.Permissions" - }, - "expiresAt": { - "type": "integer" - }, - "issuedAt": { - "type": "integer" - }, - "name": { - "type": "string" - }, - "token": { - "type": "string" - } - } - }, - "http.BulkDeleteItem": { - "type": "object", - "properties": { - "message": { - "type": "string" - }, - "path": { - "type": "string" - }, - "source": { - "type": "string" - } - } - }, - "http.BulkDeleteResponse": { - "type": "object", - "properties": { - "failed": { - "type": "array", - "items": { - "$ref": "#/definitions/http.BulkDeleteItem" - } - }, - "succeeded": { - "type": "array", - "items": { - "$ref": "#/definitions/http.BulkDeleteItem" - } - } - } - }, - "http.DirectDownloadResponse": { - "type": "object", - "properties": { - "hash": { - "type": "string" - }, - "shareUrl": { - "type": "string" - }, - "status": { - "type": "string" - }, - "url": { - "type": "string" - } - } - }, - "http.GroupListResponse": { - "type": "object", - "properties": { - "groups": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "http.HttpResponse": { - "type": "object", - "properties": { - "message": { - "type": "string" - }, - "status": { - "type": "integer" - }, - "token": { - "type": "string" - } - } - }, - "http.MoveCopyItem": { - "type": "object", - "properties": { - "fromPath": { - "type": "string" - }, - "fromSource": { - "type": "string" - }, - "message": { - "type": "string" - }, - "toPath": { - "type": "string" - }, - "toSource": { - "type": "string" - } - } - }, - "http.MoveCopyRequest": { - "type": "object", - "properties": { - "action": { - "description": "\"copy\", \"move\", or \"rename\"", - "type": "string" - }, - "items": { - "type": "array", - "items": { - "$ref": "#/definitions/http.MoveCopyItem" - } - }, - "overwrite": { - "description": "Overwrite if destination exists", - "type": "boolean" - }, - "rename": { - "description": "Auto-rename if destination exists", - "type": "boolean" - } - } - }, - "http.MoveCopyResponse": { - "type": "object", - "properties": { - "failed": { - "type": "array", - "items": { - "$ref": "#/definitions/http.MoveCopyItem" - } - }, - "succeeded": { - "type": "array", - "items": { - "$ref": "#/definitions/http.MoveCopyItem" - } - } - } - }, - "http.ShareResponse": { - "type": "object", - "properties": { - "allowCreate": { - "description": "allow creating files", - "type": "boolean" - }, - "allowDelete": { - "type": "boolean" - }, - "allowModify": { - "description": "allow modifying files", - "type": "boolean" - }, - "allowReplacements": { - "description": "allow replacements of files", - "type": "boolean" - }, - "allowedUsernames": { - "type": "array", - "items": { - "type": "string" - } - }, - "banner": { - "type": "string" - }, - "bannerUrl": { - "type": "string" - }, - "canEditShare": { - "type": "boolean" - }, - "description": { - "type": "string" - }, - "disableAnonymous": { - "type": "boolean" - }, - "disableDownload": { - "description": "don't allow downloading files", - "type": "boolean" - }, - "disableFileViewer": { - "description": "don't allow viewing files", - "type": "boolean" - }, - "disableLoginOption": { - "description": "disable login option in share (true = hide, false = show)", - "type": "boolean" - }, - "disableShareCard": { - "type": "boolean" - }, - "disableSidebar": { - "type": "boolean" - }, - "disableThumbnails": { - "type": "boolean" - }, - "downloadURL": { - "type": "string" - }, - "downloads": { - "type": "integer" - }, - "downloadsLimit": { - "type": "integer" - }, - "enableOnlyOffice": { - "type": "boolean" - }, - "enforceDarkLightMode": { - "description": "\"dark\" or \"light\"", - "type": "string" - }, - "expire": { - "type": "integer" - }, - "extractEmbeddedSubtitles": { - "description": "can be io intensive for large files and take 10-30 seconds.", - "type": "boolean" - }, - "favicon": { - "type": "string" - }, - "faviconUrl": { - "type": "string" - }, - "hasPassword": { - "type": "boolean" - }, - "hash": { - "type": "string" - }, - "hideFileExt": { - "description": "show hidden files based on extensions in shares", - "type": "string" - }, - "hideNavButtons": { - "type": "boolean" - }, - "keepAfterExpiration": { - "type": "boolean" - }, - "maxBandwidth": { - "type": "integer" - }, - "password_hash": { - "type": "string" - }, - "path": { - "type": "string" - }, - "pathExists": { - "type": "boolean" - }, - "perUserDownloadLimit": { - "type": "boolean" - }, - "pinnedItems": { - "$ref": "#/definitions/share.PinnedItems" - }, - "quickDownload": { - "type": "boolean" - }, - "shareTheme": { - "type": "string" - }, - "shareType": { - "description": "type of share: normal, upload, max", - "type": "string" - }, - "shareURL": { - "type": "string" - }, - "showHidden": { - "description": "show hidden files in share (true = show, false = hide)", - "type": "boolean" - }, - "sidebarLinks": { - "description": "customizable sidebar links", - "type": "array", - "items": { - "$ref": "#/definitions/users.SidebarLink" - } - }, - "source": { - "description": "Override embedded field to show source name", - "type": "string" - }, - "sourceURL": { - "type": "string" - }, - "themeColor": { - "type": "string" - }, - "title": { - "type": "string" - }, - "token": { - "description": "Token is a random value that will only be set when PasswordHash is set. It is\nURL-Safe and is used to download links in password-protected shares via a\nquery arg.", - "type": "string" - }, - "userDownloads": { - "description": "Track downloads per username", - "type": "object", - "additionalProperties": { - "type": "integer" - } - }, - "userID": { - "type": "integer" - }, - "username": { - "type": "string" - }, - "version": { - "type": "integer" - }, - "viewMode": { - "description": "default view mode for anonymous users: \"list\", \"compact\", \"normal\", \"gallery\"", - "type": "string" - } - } - }, - "http.archiveCreateRequest": { - "type": "object", - "properties": { - "compression": { - "description": "Gzip compression level for tar.gz only, 0-9; 0 = default; ignored for zip (optional). Example: 6", - "type": "integer" - }, - "deleteAfter": { - "description": "If true, delete the source files/directories after successful archive creation (optional; requires delete permission). Example: true", - "type": "boolean" - }, - "destination": { - "description": "Full path where the archive will be created; use .zip or .tar.gz extension (required). Example: \"/backups/my-archive.zip\"", - "type": "string" - }, - "format": { - "description": "Archive format: \"zip\" or \"tar.gz\" (optional; inferred from destination if omitted). Example: \"zip\"", - "type": "string" - }, - "fromSource": { - "description": "Source name where the paths to archive live (required). Example: \"default\"", - "type": "string" - }, - "paths": { - "description": "Paths of files or directories to add; directories are walked; access-denied entries skipped (required). Example: [\"/docs/file.txt\", \"/photos\"]", - "type": "array", - "items": { - "type": "string" - } - }, - "toSource": { - "description": "Source name where the archive file will be written (optional; default: fromSource). Example: \"backups\"", - "type": "string" - } - } - }, - "http.duplicateGroup": { - "type": "object", - "properties": { - "count": { - "type": "integer" - }, - "files": { - "type": "array", - "items": { - "$ref": "#/definitions/indexing.SearchResult" - } - }, - "size": { - "type": "integer" - } - } - }, - "http.duplicateResponse": { - "type": "object", - "properties": { - "groups": { - "type": "array", - "items": { - "$ref": "#/definitions/http.duplicateGroup" - } - }, - "incomplete": { - "type": "boolean" - }, - "reason": { - "type": "string" - } - } - }, - "http.fileWatchMetadata": { - "type": "object", - "properties": { - "modified": { - "description": "Modification time", - "type": "string" - }, - "name": { - "description": "File name", - "type": "string" - }, - "size": { - "description": "File size in bytes (for directories, total size of all files)", - "type": "integer" - }, - "type": { - "description": "MIME type", - "type": "string" - } - } - }, - "http.fileWatchResponse": { - "type": "object", - "properties": { - "contents": { - "description": "Text content for text files", - "type": "string" - }, - "isText": { - "description": "Whether the file is a text file", - "type": "boolean" - }, - "metadata": { - "description": "File metadata for non-text files", - "allOf": [ - { - "$ref": "#/definitions/http.fileWatchMetadata" - } - ] - } - } - }, - "http.pinnedItemPatchRequest": { - "type": "object", - "required": [ - "name", - "path", - "source" - ], - "properties": { - "name": { - "description": "item basename within path", - "type": "string" - }, - "path": { - "description": "scope-relative parent directory", - "type": "string" - }, - "source": { - "type": "string" - } - } - }, - "http.sharePinnedItemPatchRequest": { - "type": "object", - "required": [ - "name", - "path" - ], - "properties": { - "name": { - "description": "item basename within path", - "type": "string" - }, - "path": { - "description": "share-relative parent directory", - "type": "string" - } - } - }, - "http.unarchiveRequest": { - "type": "object", - "properties": { - "deleteAfter": { - "description": "If true, delete the archive file after successful extraction (optional; default: false). Example: true", - "type": "boolean" - }, - "destination": { - "description": "Directory path on toSource to extract into (required). Example: \"/projects/imported\"", - "type": "string" - }, - "fromSource": { - "description": "Source name where the archive file lives (required). Example: \"default\"", - "type": "string" - }, - "path": { - "description": "Path to the archive file on fromSource; .zip, .tar.gz, or .tgz (required). Example: \"/downloads/data.zip\"", - "type": "string" - }, - "toSource": { - "description": "Source name where contents will be extracted (optional; default: fromSource). Example: \"restored\"", - "type": "string" - } - } - }, "indexing.SearchResult": { "type": "object", "properties": { @@ -5353,6 +5190,10 @@ "type": { "description": "type of the file, either \"directory\" or a file mimetype", "type": "string" + }, + "viewToken": { + "description": "opaque token for inline viewing via /resources/view or /media/stream", + "type": "string" } } }, @@ -5394,6 +5235,10 @@ "type": { "description": "type of the file, either \"directory\" or a file mimetype", "type": "string" + }, + "viewToken": { + "description": "opaque token for inline viewing via /resources/view or /media/stream", + "type": "string" } } }, @@ -5511,6 +5356,14 @@ "description": "track artist", "type": "string" }, + "audioCodec": { + "description": "audio codec name (e.g. aac)", + "type": "string" + }, + "container": { + "description": "container/format name (e.g. mov,mp4,m4a,3gp,3g2,mj2)", + "type": "string" + }, "duration": { "description": "duration in seconds", "type": "integer" @@ -5538,12 +5391,37 @@ "description": "track number", "type": "integer" }, + "videoCodec": { + "description": "video codec name (e.g. h264)", + "type": "string" + }, "year": { "description": "release year", "type": "integer" } } }, + "settings.ActivityConfig": { + "type": "object", + "properties": { + "disabled": { + "description": "disable semantic activity audit logging (default: false)", + "type": "boolean" + }, + "flushIntervalSeconds": { + "description": "buffer flush interval in seconds (default 10)", + "type": "integer" + }, + "maxBufferSize": { + "description": "max in-memory buffer before immediate flush (default 10000)", + "type": "integer" + }, + "retentionDays": { + "description": "purge activity rows older than this many days (default 30)", + "type": "integer" + } + } + }, "settings.Auth": { "type": "object", "properties": { @@ -5572,30 +5450,6 @@ } } }, - "settings.ConditionalFilter": { - "type": "object", - "properties": { - "hidden": { - "description": "deprecated: use ignoreHidden instead. eg, FolderPath: \"/\" and ignoreHidden: true will exclude hidden files and folders under the root folder.", - "type": "boolean" - }, - "ignoreHidden": { - "description": "deprecated: use ignoreHidden instead. eg, FolderPath: \"/\" and ignoreHidden: true will exclude hidden files and folders under the root folder.", - "type": "boolean" - }, - "ignoreZeroSizeFolders": { - "description": "deprecated: use ignoreZeroSizeFolders instead. eg, FolderPath: \"/\" and ignoreZeroSizeFolders: true will ignore folders with 0 size under the root folder.", - "type": "boolean" - }, - "rules": { - "description": "list of item rules to apply to specific paths", - "type": "array", - "items": { - "$ref": "#/definitions/settings.ConditionalRule" - } - } - } - }, "settings.ConditionalRule": { "type": "object", "properties": { @@ -5607,10 +5461,6 @@ "description": "(global) exclude files that match these names. Eg. \"file.txt\" or \"test.csv\"", "type": "string" }, - "fileNames": { - "description": "deprecated: exclude files that match these names. Eg. \"file.txt\" or \"test.csv\"", - "type": "string" - }, "filePath": { "description": "(global) exclude files that match this path. Eg. \"/path/to/file.txt\" or \"/path/to/file.txt/subfile.txt\"", "type": "string" @@ -5627,10 +5477,6 @@ "description": "(global) exclude folders that match these names. Eg. \"folder\" or \"subfolder\"", "type": "string" }, - "folderNames": { - "description": "deprecated: exclude folders that match these names. Eg. \"folder\" or \"subfolder\"", - "type": "string" - }, "folderPath": { "description": "(global) exclude folders that match this path. Eg. \"/path/to/folder\" or \"/path/to/folder/subfolder\"", "type": "string" @@ -5678,6 +5524,27 @@ } } }, + "settings.Database": { + "type": "object", + "properties": { + "activity": { + "description": "activity audit logging configuration", + "allOf": [ + { + "$ref": "#/definitions/settings.ActivityConfig" + } + ] + }, + "migrateFrom": { + "description": "path to legacy database file for migration (optional)", + "type": "string" + }, + "path": { + "description": "path to SQLite database file", + "type": "string" + } + } + }, "settings.ExternalLink": { "type": "object", "required": [ @@ -5788,16 +5655,49 @@ "settings.Http": { "type": "object", "properties": { + "baseURL": { + "description": "base URL for the server, the subpath that the server is running on.", + "type": "string" + }, "disableRateLimit": { "description": "turns off built-in auth route rate limiting and failed-login lockout (default false).", "type": "boolean" }, - "trustedHeaders": { - "description": "list of headers to trust, useful when behind a reverse proxy.", - "type": "array", - "items": { - "type": "string" - } + "disableWebDAV": { + "description": "disable webdav support (default: false)", + "type": "boolean" + }, + "externalUrl": { + "description": "used by share links if set (eg. http://mydomain.com)", + "type": "string" + }, + "internalUrl": { + "description": "used by integrations if set, this is the base domain that an integration service will use to communicate with filebrowser (eg. http://localhost:8080)", + "type": "string" + }, + "listen": { + "description": "address to listen on (default: 0.0.0.0)", + "type": "string" + }, + "port": { + "description": "port to listen on", + "type": "integer" + }, + "socket": { + "description": "socket to listen on - eg. /var/run/filebrowser.sock", + "type": "string" + }, + "tlsCert": { + "description": "path to TLS cert", + "type": "string" + }, + "tlsKey": { + "description": "path to TLS key", + "type": "string" + }, + "trustProxyHeaders": { + "description": "honor X-Forwarded-* and X-Real-IP from a reverse proxy (default: false)", + "type": "boolean" } } }, @@ -6029,10 +5929,6 @@ "description": "output ffmpeg stdout for media integration -- careful can produces lots of output!", "type": "boolean" }, - "exiftoolPath": { - "description": "path to exiftool executable", - "type": "string" - }, "extractEmbeddedSubtitles": { "description": "extract embedded subtitles from media files", "type": "boolean" @@ -6040,6 +5936,10 @@ "ffmpegPath": { "description": "path to ffmpeg directory with ffmpeg and ffprobe (eg. /usr/local/bin)", "type": "string" + }, + "hardwareAcceleration": { + "description": "enable hardware acceleration for ffmpeg if available", + "type": "boolean" } } }, @@ -6249,10 +6149,6 @@ "sources" ], "properties": { - "baseURL": { - "description": "base URL for the server, the subpath that the server is running on.", - "type": "string" - }, "cacheDir": { "description": "path to the cache directory, used for thumbnails and other cached files", "type": "string" @@ -6262,8 +6158,12 @@ "type": "boolean" }, "database": { - "description": "path to the database file", - "type": "string" + "description": "SQLite database configuration", + "allOf": [ + { + "$ref": "#/definitions/settings.Database" + } + ] }, "disablePreviewResize": { "description": "disable resizing of previews for faster loading over slow connections", @@ -6281,14 +6181,6 @@ "description": "disables backend update check service", "type": "boolean" }, - "disableWebDAV": { - "description": "disable webdav support (default: false)", - "type": "boolean" - }, - "externalUrl": { - "description": "used by share links if set (eg. http://mydomain.com)", - "type": "string" - }, "filesystem": { "description": "filesystem settings", "allOf": [ @@ -6305,14 +6197,6 @@ } ] }, - "internalUrl": { - "description": "used by integrations if set, this is the base domain that an integration service will use to communicate with filebrowser (eg. http://localhost:8080)", - "type": "string" - }, - "listen": { - "description": "address to listen on (default: 0.0.0.0)", - "type": "string" - }, "logging": { "type": "array", "items": { @@ -6331,27 +6215,11 @@ "description": "number of concurrent image processing jobs used to create previews, default is 4.", "type": "integer" }, - "port": { - "description": "port to listen on", - "type": "integer" - }, - "socket": { - "description": "socket to listen on - eg. /var/run/filebrowser.sock", - "type": "string" - }, "sources": { "type": "array", "items": { "$ref": "#/definitions/settings.Source" } - }, - "tlsCert": { - "description": "path to TLS cert", - "type": "string" - }, - "tlsKey": { - "description": "path to TLS key", - "type": "string" } } }, @@ -6374,7 +6242,12 @@ "$ref": "#/definitions/settings.Server" }, "userDefaults": { - "$ref": "#/definitions/settings.UserDefaults" + "description": "optional signup/CLI defaults; per-user values are managed in the UI", + "allOf": [ + { + "$ref": "#/definitions/settings.UserDefaults" + } + ] } } }, @@ -6400,14 +6273,6 @@ "settings.SourceConfig": { "type": "object", "properties": { - "conditionals": { - "description": "deprecated: use source.rules instead", - "allOf": [ - { - "$ref": "#/definitions/settings.ConditionalFilter" - } - ] - }, "createUserDir": { "description": "create a user directory for each user under defaultUserScope + username", "type": "boolean" @@ -6416,6 +6281,14 @@ "description": "should be added as a default source for new users?", "type": "boolean" }, + "defaultPermissions": { + "description": "DefaultPermissions is the template for new user scopes on this source (also synced globally via Access settings).", + "allOf": [ + { + "$ref": "#/definitions/users.SourceFilePermissions" + } + ] + }, "defaultUserScope": { "description": "defaults to root of index \"/\" should match folders under path", "type": "string" @@ -6428,10 +6301,6 @@ "description": "disable the source, this is useful so you don't need to remove it from the config file", "type": "boolean" }, - "indexingIntervalMinutes": { - "description": "deprecated: create a rule with indexingIntervalMinutes to set the indexing interval for this source", - "type": "integer" - }, "private": { "description": "designate as source as private -- currently just means no sharing permitted.", "type": "boolean" @@ -6487,167 +6356,26 @@ "account": { "$ref": "#/definitions/settings.UserDefaultsAccount" }, - "customTheme": { - "description": "deprecated: use ui.customTheme instead", - "type": "string" - }, - "darkMode": { - "description": "deprecated: use sidebar.darkMode instead", - "type": "boolean" - }, - "dateFormat": { - "description": "deprecated: use listing.dateFormat instead", - "type": "boolean" - }, - "debugOffice": { - "description": "deprecated: use fileViewer.debugOffice instead", - "type": "boolean" - }, - "deleteAfterArchive": { - "description": "deprecated: use listing.deleteAfterArchive instead", - "type": "boolean" - }, - "deleteWithoutConfirming": { - "description": "deprecated: use listing.deleteWithoutConfirming instead", - "type": "boolean" - }, - "disableOfficePreviewExt": { - "description": "deprecated: use disablePreviewExt instead", - "type": "string" - }, - "disableOnlyOfficeExt": { - "description": "deprecated: use fileViewer.disableOnlyOfficeExt instead", - "type": "string" - }, - "disablePreviewExt": { - "description": "deprecated: use preview.disablePreviewExt instead", - "type": "string" - }, - "disableQuickToggles": { - "description": "deprecated: use sidebar.disableQuickToggles instead", - "type": "boolean" - }, - "disableSearchOptions": { - "description": "deprecated: use search.disableOptions instead", - "type": "boolean" - }, - "disableSettings": { - "description": "deprecated: use account.disableSettings instead", - "type": "boolean" - }, - "disableUpdateNotifications": { - "description": "deprecated: use account.disableUpdateNotifications instead", - "type": "boolean" - }, - "disableViewingExt": { - "description": "deprecated: use fileViewer.disableViewingExt instead", - "type": "string" - }, - "editorQuickSave": { - "description": "Deprecated fields - kept for backwards compatibility", - "type": "boolean" - }, "fileLoading": { "$ref": "#/definitions/users.FileLoading" }, "fileViewer": { "$ref": "#/definitions/settings.UserDefaultsFileViewer" }, - "gallerySize": { - "description": "deprecated: use sidebar.gallerySize instead", - "type": "integer" - }, - "hideFileExt": { - "description": "deprecated: use listing.hideFileExt instead", - "type": "string" - }, - "hideFilesInTree": { - "description": "deprecated: use sidebar.hideFilesInTree instead", - "type": "boolean" - }, - "hideSidebarFileActions": { - "description": "deprecated: use sidebar.hideSidebarFileActions instead", - "type": "boolean" - }, "listing": { "$ref": "#/definitions/settings.UserDefaultsListing" }, - "locale": { - "description": "deprecated: use ui.locale instead", - "type": "string" - }, - "lockPassword": { - "description": "deprecated: use account.lockPassword instead", - "type": "boolean" - }, - "loginMethod": { - "description": "deprecated: use account.loginMethod instead", - "type": "string" - }, - "permissions": { - "description": "deprecated: use account.permissions instead", - "allOf": [ - { - "$ref": "#/definitions/settings.UserDefaultsPermissions" - } - ] - }, - "preferEditorForMarkdown": { - "description": "deprecated: use fileViewer.preferEditorForMarkdown instead", - "type": "boolean" - }, "preview": { "$ref": "#/definitions/settings.UserDefaultsPreview" }, - "quickDownload": { - "description": "deprecated: use listing.quickDownload instead", - "type": "boolean" - }, "search": { "$ref": "#/definitions/settings.UserDefaultsSearch" }, - "showCopyPath": { - "description": "deprecated: use listing.showCopyPath instead", - "type": "boolean" - }, - "showHidden": { - "description": "deprecated: use listing.showHidden instead", - "type": "boolean" - }, - "showSelectMultiple": { - "description": "deprecated: use listing.showSelectMultiple instead", - "type": "boolean" - }, - "showToolsInSidebar": { - "description": "deprecated: use sidebar.showToolsInSidebar instead", - "type": "boolean" - }, "sidebar": { - "description": "New organized structure", - "allOf": [ - { - "$ref": "#/definitions/settings.UserDefaultsSidebar" - } - ] - }, - "singleClick": { - "description": "deprecated: use sidebar.singleClick instead", - "type": "boolean" - }, - "stickySidebar": { - "description": "deprecated: use sidebar.stickySidebar instead", - "type": "boolean" - }, - "themeColor": { - "description": "deprecated: use ui.themeColor instead", - "type": "string" + "$ref": "#/definitions/settings.UserDefaultsSidebar" }, "ui": { "$ref": "#/definitions/settings.UserDefaultsUI" - }, - "viewMode": { - "description": "deprecated: use sidebar.viewMode instead", - "type": "string" } } }, @@ -6686,22 +6414,6 @@ "description": "allow api access", "type": "boolean" }, - "create": { - "description": "allow creating or uploading files", - "type": "boolean" - }, - "delete": { - "description": "allow deleting files", - "type": "boolean" - }, - "download": { - "description": "allow downloading files", - "type": "boolean" - }, - "modify": { - "description": "allow modifying files", - "type": "boolean" - }, "realtime": { "description": "allow realtime updates", "type": "boolean" @@ -6723,10 +6435,6 @@ "description": "debug onlyoffice editor", "type": "boolean" }, - "defaultMediaPlayer": { - "description": "disable the styled feature-rich media player for browser default", - "type": "boolean" - }, "disableOnlyOfficeExt": { "description": "list of file extensions to disable onlyoffice editor for", "type": "string" @@ -6794,43 +6502,6 @@ } } }, - "settings.UserDefaultsPermissions": { - "type": "object", - "properties": { - "admin": { - "description": "deprecated: use account.permissions.admin instead. allow admin access", - "type": "boolean" - }, - "api": { - "description": "deprecated: use account.permissions.api instead. allow api access", - "type": "boolean" - }, - "create": { - "description": "deprecated: use account.permissions.create instead. allow creating or uploading files", - "type": "boolean" - }, - "delete": { - "description": "deprecated: use account.permissions.delete instead. allow deleting files", - "type": "boolean" - }, - "download": { - "description": "deprecated: use account.permissions.download instead. allow downloading files", - "type": "boolean" - }, - "modify": { - "description": "deprecated: use account.permissions.modify instead. allow modifying files", - "type": "boolean" - }, - "realtime": { - "description": "deprecated: use account.permissions.realtime instead. allow realtime updates", - "type": "boolean" - }, - "share": { - "description": "deprecated: use account.permissions.share instead. allow sharing files", - "type": "boolean" - } - } - }, "settings.UserDefaultsPreview": { "type": "object", "properties": { @@ -6838,18 +6509,6 @@ "description": "show thumbnails for audio files", "type": "boolean" }, - "autoplayMedia": { - "description": "deprecated: use fileViewer.autoplayMedia instead. autoplay media files in preview", - "type": "boolean" - }, - "defaultMediaPlayer": { - "description": "deprecated: use fileViewer.defaultMediaPlayer instead. disable the styled feature-rich media player for browser default", - "type": "boolean" - }, - "disableHideSidebar": { - "description": "deprecated fields", - "type": "boolean" - }, "disablePreviewExt": { "description": "comma separated list of file extensions to disable preview for", "type": "string" @@ -6947,170 +6606,28 @@ } } }, - "share.CommonShare": { + "share.PinnedItems": { "type": "object", - "properties": { - "allowCreate": { - "description": "allow creating files", - "type": "boolean" - }, - "allowDelete": { - "type": "boolean" - }, - "allowModify": { - "description": "allow modifying files", - "type": "boolean" - }, - "allowReplacements": { - "description": "allow replacements of files", - "type": "boolean" - }, - "allowedUsernames": { - "type": "array", - "items": { - "type": "string" - } - }, - "banner": { - "type": "string" - }, - "bannerUrl": { - "type": "string" - }, - "canEditShare": { - "type": "boolean" - }, - "description": { - "type": "string" - }, - "disableAnonymous": { - "type": "boolean" - }, - "disableDownload": { - "description": "don't allow downloading files", - "type": "boolean" - }, - "disableFileViewer": { - "description": "don't allow viewing files", - "type": "boolean" - }, - "disableLoginOption": { - "description": "disable login option in share (true = hide, false = show)", - "type": "boolean" - }, - "disableShareCard": { - "type": "boolean" - }, - "disableSidebar": { - "type": "boolean" - }, - "disableThumbnails": { - "type": "boolean" - }, - "downloadURL": { - "type": "string" - }, - "downloadsLimit": { - "type": "integer" - }, - "enableOnlyOffice": { - "type": "boolean" - }, - "enforceDarkLightMode": { - "description": "\"dark\" or \"light\"", - "type": "string" - }, - "extractEmbeddedSubtitles": { - "description": "can be io intensive for large files and take 10-30 seconds.", - "type": "boolean" - }, - "favicon": { - "type": "string" - }, - "faviconUrl": { - "type": "string" - }, - "hasPassword": { - "type": "boolean" - }, - "hideFileExt": { - "description": "show hidden files based on extensions in shares", - "type": "string" - }, - "hideNavButtons": { - "type": "boolean" - }, - "keepAfterExpiration": { - "type": "boolean" - }, - "maxBandwidth": { - "type": "integer" - }, - "path": { - "type": "string" - }, - "perUserDownloadLimit": { - "type": "boolean" - }, - "quickDownload": { - "type": "boolean" - }, - "shareTheme": { - "type": "string" - }, - "shareType": { - "description": "type of share: normal, upload, max", - "type": "string" - }, - "shareURL": { - "type": "string" - }, - "showHidden": { - "description": "show hidden files in share (true = show, false = hide)", - "type": "boolean" - }, - "sidebarLinks": { - "description": "customizable sidebar links", - "type": "array", - "items": { - "$ref": "#/definitions/users.SidebarLink" - } - }, - "source": { - "description": "backend source is path to maintain between name changes", - "type": "string" - }, - "sourceURL": { - "type": "string" - }, - "themeColor": { - "type": "string" - }, - "title": { - "type": "string" - }, - "viewMode": { - "description": "default view mode for anonymous users: \"list\", \"compact\", \"normal\", \"gallery\"", + "additionalProperties": { + "type": "array", + "items": { "type": "string" } } }, - "share.CreateBody": { + "share.Share": { "type": "object", "properties": { "allowCreate": { - "description": "allow creating files", "type": "boolean" }, "allowDelete": { "type": "boolean" }, "allowModify": { - "description": "allow modifying files", "type": "boolean" }, "allowReplacements": { - "description": "allow replacements of files", "type": "boolean" }, "allowedUsernames": { @@ -7135,175 +6652,12 @@ "type": "boolean" }, "disableDownload": { - "description": "don't allow downloading files", "type": "boolean" }, "disableFileViewer": { - "description": "don't allow viewing files", "type": "boolean" }, "disableLoginOption": { - "description": "disable login option in share (true = hide, false = show)", - "type": "boolean" - }, - "disableShareCard": { - "type": "boolean" - }, - "disableSidebar": { - "type": "boolean" - }, - "disableThumbnails": { - "type": "boolean" - }, - "downloadURL": { - "type": "string" - }, - "downloadsLimit": { - "type": "integer" - }, - "enableOnlyOffice": { - "type": "boolean" - }, - "enforceDarkLightMode": { - "description": "\"dark\" or \"light\"", - "type": "string" - }, - "expires": { - "type": "string" - }, - "extractEmbeddedSubtitles": { - "description": "can be io intensive for large files and take 10-30 seconds.", - "type": "boolean" - }, - "favicon": { - "type": "string" - }, - "faviconUrl": { - "type": "string" - }, - "hasPassword": { - "type": "boolean" - }, - "hash": { - "type": "string" - }, - "hideFileExt": { - "description": "show hidden files based on extensions in shares", - "type": "string" - }, - "hideNavButtons": { - "type": "boolean" - }, - "keepAfterExpiration": { - "type": "boolean" - }, - "maxBandwidth": { - "type": "integer" - }, - "password": { - "type": "string" - }, - "path": { - "type": "string" - }, - "perUserDownloadLimit": { - "type": "boolean" - }, - "quickDownload": { - "type": "boolean" - }, - "shareTheme": { - "type": "string" - }, - "shareType": { - "description": "type of share: normal, upload, max", - "type": "string" - }, - "shareURL": { - "type": "string" - }, - "showHidden": { - "description": "show hidden files in share (true = show, false = hide)", - "type": "boolean" - }, - "sidebarLinks": { - "description": "customizable sidebar links", - "type": "array", - "items": { - "$ref": "#/definitions/users.SidebarLink" - } - }, - "source": { - "description": "backend source is path to maintain between name changes", - "type": "string" - }, - "sourceURL": { - "type": "string" - }, - "themeColor": { - "type": "string" - }, - "title": { - "type": "string" - }, - "unit": { - "type": "string" - }, - "viewMode": { - "description": "default view mode for anonymous users: \"list\", \"compact\", \"normal\", \"gallery\"", - "type": "string" - } - } - }, - "share.Link": { - "type": "object", - "properties": { - "allowCreate": { - "description": "allow creating files", - "type": "boolean" - }, - "allowDelete": { - "type": "boolean" - }, - "allowModify": { - "description": "allow modifying files", - "type": "boolean" - }, - "allowReplacements": { - "description": "allow replacements of files", - "type": "boolean" - }, - "allowedUsernames": { - "type": "array", - "items": { - "type": "string" - } - }, - "banner": { - "type": "string" - }, - "bannerUrl": { - "type": "string" - }, - "canEditShare": { - "type": "boolean" - }, - "description": { - "type": "string" - }, - "disableAnonymous": { - "type": "boolean" - }, - "disableDownload": { - "description": "don't allow downloading files", - "type": "boolean" - }, - "disableFileViewer": { - "description": "don't allow viewing files", - "type": "boolean" - }, - "disableLoginOption": { - "description": "disable login option in share (true = hide, false = show)", "type": "boolean" }, "disableShareCard": { @@ -7335,7 +6689,6 @@ "type": "integer" }, "extractEmbeddedSubtitles": { - "description": "can be io intensive for large files and take 10-30 seconds.", "type": "boolean" }, "favicon": { @@ -7382,25 +6735,28 @@ "type": "string" }, "shareType": { - "description": "type of share: normal, upload, max", "type": "string" }, "shareURL": { "type": "string" }, "showHidden": { - "description": "show hidden files in share (true = show, false = hide)", "type": "boolean" }, "sidebarLinks": { - "description": "customizable sidebar links", "type": "array", "items": { "$ref": "#/definitions/users.SidebarLink" } }, + "singleFileShare": { + "type": "boolean" + }, "source": { - "description": "backend source is path to maintain between name changes", + "description": "source display name for API; backend path is Share.SourcePath", + "type": "string" + }, + "sourcePath": { "type": "string" }, "sourceURL": { @@ -7413,11 +6769,9 @@ "type": "string" }, "token": { - "description": "Token is a random value that will only be set when PasswordHash is set. It is\nURL-Safe and is used to download links in password-protected shares via a\nquery arg.", "type": "string" }, "userDownloads": { - "description": "Track downloads per username", "type": "object", "additionalProperties": { "type": "integer" @@ -7430,16 +6784,322 @@ "type": "integer" }, "viewMode": { - "description": "default view mode for anonymous users: \"list\", \"compact\", \"normal\", \"gallery\"", + "description": "default view mode for anonymous users", "type": "string" } } }, - "share.PinnedItems": { + "share.ShareFrontend": { "type": "object", - "additionalProperties": { - "type": "array", - "items": { + "properties": { + "allowCreate": { + "type": "boolean" + }, + "allowDelete": { + "type": "boolean" + }, + "allowModify": { + "type": "boolean" + }, + "allowReplacements": { + "type": "boolean" + }, + "allowedUsernames": { + "type": "array", + "items": { + "type": "string" + } + }, + "banner": { + "type": "string" + }, + "bannerUrl": { + "type": "string" + }, + "canEditShare": { + "type": "boolean" + }, + "description": { + "type": "string" + }, + "disableAnonymous": { + "type": "boolean" + }, + "disableDownload": { + "type": "boolean" + }, + "disableFileViewer": { + "type": "boolean" + }, + "disableLoginOption": { + "type": "boolean" + }, + "disableShareCard": { + "type": "boolean" + }, + "disableSidebar": { + "type": "boolean" + }, + "disableThumbnails": { + "type": "boolean" + }, + "downloadURL": { + "type": "string" + }, + "downloads": { + "type": "integer" + }, + "downloadsLimit": { + "type": "integer" + }, + "enableOnlyOffice": { + "type": "boolean" + }, + "enforceDarkLightMode": { + "description": "\"dark\" or \"light\"", + "type": "string" + }, + "expire": { + "type": "integer" + }, + "expires": { + "type": "string" + }, + "extractEmbeddedSubtitles": { + "type": "boolean" + }, + "favicon": { + "type": "string" + }, + "faviconUrl": { + "type": "string" + }, + "hasPassword": { + "type": "boolean" + }, + "hash": { + "type": "string" + }, + "hideFileExt": { + "description": "show hidden files based on extensions in shares", + "type": "string" + }, + "hideNavButtons": { + "type": "boolean" + }, + "keepAfterExpiration": { + "type": "boolean" + }, + "maxBandwidth": { + "type": "integer" + }, + "path": { + "type": "string" + }, + "pathExists": { + "type": "boolean" + }, + "perUserDownloadLimit": { + "type": "boolean" + }, + "quickDownload": { + "type": "boolean" + }, + "shareTheme": { + "type": "string" + }, + "shareType": { + "type": "string" + }, + "shareURL": { + "type": "string" + }, + "showHidden": { + "type": "boolean" + }, + "sidebarLinks": { + "type": "array", + "items": { + "$ref": "#/definitions/users.SidebarLink" + } + }, + "singleFileShare": { + "type": "boolean" + }, + "source": { + "description": "source display name for API; backend path is Share.SourcePath", + "type": "string" + }, + "sourceURL": { + "type": "string" + }, + "themeColor": { + "type": "string" + }, + "title": { + "type": "string" + }, + "unit": { + "type": "string" + }, + "username": { + "type": "string" + }, + "viewMode": { + "description": "default view mode for anonymous users", + "type": "string" + } + } + }, + "share.SharePostBody": { + "type": "object", + "properties": { + "allowCreate": { + "type": "boolean" + }, + "allowDelete": { + "type": "boolean" + }, + "allowModify": { + "type": "boolean" + }, + "allowReplacements": { + "type": "boolean" + }, + "allowedUsernames": { + "type": "array", + "items": { + "type": "string" + } + }, + "banner": { + "type": "string" + }, + "bannerUrl": { + "type": "string" + }, + "canEditShare": { + "type": "boolean" + }, + "description": { + "type": "string" + }, + "disableAnonymous": { + "type": "boolean" + }, + "disableDownload": { + "type": "boolean" + }, + "disableFileViewer": { + "type": "boolean" + }, + "disableLoginOption": { + "type": "boolean" + }, + "disableShareCard": { + "type": "boolean" + }, + "disableSidebar": { + "type": "boolean" + }, + "disableThumbnails": { + "type": "boolean" + }, + "downloadURL": { + "type": "string" + }, + "downloadsLimit": { + "type": "integer" + }, + "enableOnlyOffice": { + "type": "boolean" + }, + "enforceDarkLightMode": { + "description": "\"dark\" or \"light\"", + "type": "string" + }, + "expires": { + "type": "string" + }, + "extractEmbeddedSubtitles": { + "type": "boolean" + }, + "favicon": { + "type": "string" + }, + "faviconUrl": { + "type": "string" + }, + "hasPassword": { + "type": "boolean" + }, + "hash": { + "type": "string" + }, + "hideFileExt": { + "description": "show hidden files based on extensions in shares", + "type": "string" + }, + "hideNavButtons": { + "type": "boolean" + }, + "keepAfterExpiration": { + "type": "boolean" + }, + "maxBandwidth": { + "type": "integer" + }, + "password": { + "type": "string" + }, + "path": { + "type": "string" + }, + "perUserDownloadLimit": { + "type": "boolean" + }, + "quickDownload": { + "type": "boolean" + }, + "shareTheme": { + "type": "string" + }, + "shareType": { + "type": "string" + }, + "shareURL": { + "type": "string" + }, + "showHidden": { + "type": "boolean" + }, + "sidebarLinks": { + "type": "array", + "items": { + "$ref": "#/definitions/users.SidebarLink" + } + }, + "singleFileShare": { + "type": "boolean" + }, + "source": { + "description": "source display name for API; backend path is Share.SourcePath", + "type": "string" + }, + "sourceURL": { + "type": "string" + }, + "themeColor": { + "type": "string" + }, + "title": { + "type": "string" + }, + "unit": { + "type": "string" + }, + "viewMode": { + "description": "default view mode for anonymous users", "type": "string" } } @@ -7451,6 +7111,7 @@ "$ref": "#/definitions/users.Permissions" }, "belongsTo": { + "description": "numeric user id in JWT claims (bolt-era small ids still work)", "type": "integer" }, "expiresAt": { @@ -7468,6 +7129,25 @@ }, "token": { "type": "string" + }, + "username": { + "type": "string" + } + } + }, + "users.BackendScope": { + "type": "object", + "properties": { + "path": { + "description": "real path for the source", + "type": "string" + }, + "permissions": { + "$ref": "#/definitions/users.SourceFilePermissions" + }, + "scope": { + "description": "index path within that source", + "type": "string" } } }, @@ -7488,6 +7168,215 @@ } } }, + "users.FrontendScope": { + "type": "object", + "properties": { + "name": { + "description": "Bolt: filesystem path; JSON API: display name after prepForFrontend", + "type": "string" + }, + "permissions": { + "$ref": "#/definitions/users.SourceFilePermissions" + }, + "scope": { + "description": "index path within that source", + "type": "string" + } + } + }, + "users.FrontendUser": { + "type": "object", + "properties": { + "customTheme": { + "description": "Name of theme to use chosen from custom themes config.", + "type": "string" + }, + "darkMode": { + "description": "should dark mode be enabled", + "type": "boolean" + }, + "dateFormat": { + "description": "when false, the date is relative, when true, the date is an exact timestamp", + "type": "boolean" + }, + "debugOffice": { + "description": "debug onlyoffice editor", + "type": "boolean" + }, + "deleteAfterArchive": { + "description": "delete source files after successful creation/extraction of archives", + "type": "boolean" + }, + "deleteWithoutConfirming": { + "description": "delete files without confirmation", + "type": "boolean" + }, + "disableOfficePreviewExt": { + "description": "deprecated", + "type": "string" + }, + "disableOnlyOfficeExt": { + "description": "deprecated", + "type": "string" + }, + "disablePreviewExt": { + "description": "space separated list of file extensions to disable preview for", + "type": "string" + }, + "disableQuickToggles": { + "description": "disable the quick toggles in the sidebar", + "type": "boolean" + }, + "disableSearchOptions": { + "description": "disable the search options in the search bar", + "type": "boolean" + }, + "disableSettings": { + "type": "boolean" + }, + "disableUpdateNotifications": { + "description": "disable update notifications", + "type": "boolean" + }, + "disableViewingExt": { + "description": "space separated list of file extensions to disable viewing for", + "type": "string" + }, + "editorQuickSave": { + "description": "show quick save button in editor", + "type": "boolean" + }, + "fileLoading": { + "description": "upload and download settings", + "allOf": [ + { + "$ref": "#/definitions/users.FileLoading" + } + ] + }, + "gallerySize": { + "description": "0-9 - the size of the gallery thumbnails", + "type": "integer" + }, + "hideFileExt": { + "description": "space separated list of file extensions to hide in UI and API", + "type": "string" + }, + "hideFilesInTree": { + "description": "hide files in the sidebar tree navigation, when true, will show only directories.", + "type": "boolean" + }, + "hideSidebarFileActions": { + "description": "hide the file actions in the sidebar", + "type": "boolean" + }, + "locale": { + "description": "language to use: eg. de, en, or fr", + "type": "string" + }, + "lockPassword": { + "type": "boolean" + }, + "loginMethod": { + "$ref": "#/definitions/users.LoginMethod" + }, + "otpEnabled": { + "type": "boolean" + }, + "passkeyCredentials": { + "type": "array", + "items": { + "$ref": "#/definitions/users.WebAuthnCredential" + } + }, + "password": { + "type": "string" + }, + "perm": { + "$ref": "#/definitions/users.Permissions" + }, + "permissions": { + "description": "global: admin, api, share, realtime", + "allOf": [ + { + "$ref": "#/definitions/users.Permissions" + } + ] + }, + "preferEditorForMarkdown": { + "description": "prefer editor first for markdown files instead of the Markdown Viewer", + "type": "boolean" + }, + "preview": { + "$ref": "#/definitions/users.Preview" + }, + "quickDownload": { + "description": "show icon to download in one click", + "type": "boolean" + }, + "scopes": { + "type": "array", + "items": { + "$ref": "#/definitions/users.FrontendScope" + } + }, + "showCopyPath": { + "description": "show copy path action in the context menu", + "type": "boolean" + }, + "showFirstLogin": { + "type": "boolean" + }, + "showHidden": { + "description": "show hidden files in the UI. On windows this includes files starting with a dot and windows hidden files", + "type": "boolean" + }, + "showSelectMultiple": { + "description": "show select multiple files on desktop", + "type": "boolean" + }, + "showToolsInSidebar": { + "description": "when false, sidebar hides links with category \"tool\" (default: true)", + "type": "boolean" + }, + "sidebarLinks": { + "description": "customizable sidebar links", + "type": "array", + "items": { + "$ref": "#/definitions/users.SidebarLink" + } + }, + "singleClick": { + "description": "open directory on single click, also enables middle click to open in new tab", + "type": "boolean" + }, + "sorting": { + "$ref": "#/definitions/users.Sorting" + }, + "sourcePermissions": { + "description": "deprecated: use scopes[].permissions", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/users.SourceFilePermissions" + } + }, + "stickySidebar": { + "description": "keep sidebar open when navigating", + "type": "boolean" + }, + "themeColor": { + "description": "theme color to use: eg. #ff0000, or var(--red), var(--purple), etc", + "type": "string" + }, + "username": { + "type": "string" + }, + "viewMode": { + "description": "view mode to use: eg. normal, list, grid, or compact", + "type": "string" + } + } + }, "users.LoginMethod": { "type": "string", "enum": [ @@ -7517,19 +7406,19 @@ "type": "boolean" }, "create": { - "description": "allow creating or uploading files", + "description": "deprecated: legacy user migration only; not used for API tokens", "type": "boolean" }, "delete": { - "description": "allow deleting files", + "description": "deprecated: legacy user migration only; not used for API tokens", "type": "boolean" }, "download": { - "description": "allow downloading files", + "description": "deprecated: legacy user migration only; not used for API tokens", "type": "boolean" }, "modify": { - "description": "allow modifying files", + "description": "deprecated: legacy user migration only; not used for API tokens", "type": "boolean" }, "realtime": { @@ -7539,6 +7428,10 @@ "share": { "description": "allow sharing files", "type": "boolean" + }, + "view": { + "description": "deprecated: legacy user migration only; not used for API tokens", + "type": "boolean" } } }, @@ -7565,10 +7458,6 @@ "description": "autoplay media files in preview", "type": "boolean" }, - "defaultMediaPlayer": { - "description": "disable html5 media player and use the default media player", - "type": "boolean" - }, "disableHideSidebar": { "description": "disable the hide sidebar preview for previews and editors", "type": "boolean" @@ -7639,16 +7528,27 @@ } } }, - "users.SourceScope": { + "users.SourceFilePermissions": { "type": "object", "properties": { - "name": { - "description": "Bolt: filesystem path; JSON API: display name after prepForFrontend", - "type": "string" + "configured": { + "description": "true when explicitly set (allows intentional deny-all)", + "type": "boolean" }, - "scope": { - "description": "index path within that source", - "type": "string" + "create": { + "type": "boolean" + }, + "delete": { + "type": "boolean" + }, + "download": { + "type": "boolean" + }, + "modify": { + "type": "boolean" + }, + "view": { + "type": "boolean" } } }, @@ -7656,12 +7556,25 @@ "type": "object", "properties": { "apiKeys": { - "description": "deprecated: use Tokens instead", "type": "object", "additionalProperties": { "$ref": "#/definitions/users.AuthToken" } }, + "backendScopes": { + "description": "BackendScopes is the authoritative, persisted access list (SourceScope.Name = backend source path).\nSQLite stores this inside user_data JSON under the key \"scopes\" (see sqldb.UserData).", + "type": "array", + "items": { + "$ref": "#/definitions/users.BackendScope" + } + }, + "backendSourcePermissions": { + "description": "key = source path", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/users.SourceFilePermissions" + } + }, "customTheme": { "description": "Name of theme to use chosen from custom themes config.", "type": "string" @@ -7759,7 +7672,6 @@ "$ref": "#/definitions/users.LoginMethod" }, "otpEnabled": { - "description": "true if TOTP is enabled, false otherwise", "type": "boolean" }, "passkeyCredentials": { @@ -7772,16 +7684,16 @@ "type": "string" }, "perm": { - "description": "legacy for migration purposes... og filebrowser has perm attribute", + "$ref": "#/definitions/users.Permissions" + }, + "permissions": { + "description": "global: admin, api, share, realtime", "allOf": [ { "$ref": "#/definitions/users.Permissions" } ] }, - "permissions": { - "$ref": "#/definitions/users.Permissions" - }, "pinnedItems": { "$ref": "#/definitions/users.PinnedItems" }, @@ -7796,13 +7708,10 @@ "description": "show icon to download in one click", "type": "boolean" }, - "scope": { - "type": "string" - }, "scopes": { "type": "array", "items": { - "$ref": "#/definitions/users.SourceScope" + "$ref": "#/definitions/users.FrontendScope" } }, "showCopyPath": { @@ -7838,6 +7747,13 @@ "sorting": { "$ref": "#/definitions/users.Sorting" }, + "sourcePermissions": { + "description": "deprecated: use scopes[].permissions", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/users.SourceFilePermissions" + } + }, "stickySidebar": { "description": "keep sidebar open when navigating", "type": "boolean" @@ -7974,6 +7890,346 @@ "type": "string" } } + }, + "web.AuthTokenFrontend": { + "type": "object", + "properties": { + "Permissions": { + "$ref": "#/definitions/users.Permissions" + }, + "expiresAt": { + "type": "integer" + }, + "issuedAt": { + "type": "integer" + }, + "minimal": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "token": { + "type": "string" + } + } + }, + "web.BulkDeleteItem": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "path": { + "type": "string" + }, + "source": { + "type": "string" + } + } + }, + "web.BulkDeleteResponse": { + "type": "object", + "properties": { + "failed": { + "type": "array", + "items": { + "$ref": "#/definitions/web.BulkDeleteItem" + } + }, + "succeeded": { + "type": "array", + "items": { + "$ref": "#/definitions/web.BulkDeleteItem" + } + } + } + }, + "web.DirectDownloadResponse": { + "type": "object", + "properties": { + "hash": { + "type": "string" + }, + "shareUrl": { + "type": "string" + }, + "status": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "web.GroupListResponse": { + "type": "object", + "properties": { + "groups": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "web.HttpResponse": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "status": { + "type": "integer" + }, + "token": { + "type": "string" + } + } + }, + "web.MoveCopyItem": { + "type": "object", + "properties": { + "fromPath": { + "type": "string" + }, + "fromSource": { + "type": "string" + }, + "message": { + "type": "string" + }, + "toPath": { + "type": "string" + }, + "toSource": { + "type": "string" + } + } + }, + "web.MoveCopyRequest": { + "type": "object", + "properties": { + "action": { + "description": "\"copy\", \"move\", or \"rename\"", + "type": "string" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/definitions/web.MoveCopyItem" + } + }, + "overwrite": { + "description": "Overwrite if destination exists", + "type": "boolean" + }, + "rename": { + "description": "Auto-rename if destination exists", + "type": "boolean" + } + } + }, + "web.MoveCopyResponse": { + "type": "object", + "properties": { + "failed": { + "type": "array", + "items": { + "$ref": "#/definitions/web.MoveCopyItem" + } + }, + "succeeded": { + "type": "array", + "items": { + "$ref": "#/definitions/web.MoveCopyItem" + } + } + } + }, + "web.archiveCreateRequest": { + "type": "object", + "properties": { + "compression": { + "description": "Gzip compression level for tar.gz only, 0-9; 0 = default; ignored for zip (optional). Example: 6", + "type": "integer" + }, + "deleteAfter": { + "description": "If true, delete the source files/directories after successful archive creation (optional; requires delete permission). Example: true", + "type": "boolean" + }, + "destination": { + "description": "Full path where the archive will be created; use .zip or .tar.gz extension (required). Example: \"/backups/my-archive.zip\"", + "type": "string" + }, + "format": { + "description": "Archive format: \"zip\" or \"tar.gz\" (optional; inferred from destination if omitted). Example: \"zip\"", + "type": "string" + }, + "fromSource": { + "description": "Source name where the paths to archive live (required). Example: \"default\"", + "type": "string" + }, + "paths": { + "description": "Paths of files or directories to add; directories are walked; access-denied entries skipped (required). Example: [\"/docs/file.txt\", \"/photos\"]", + "type": "array", + "items": { + "type": "string" + } + }, + "toSource": { + "description": "Source name where the archive file will be written (optional; default: fromSource). Example: \"backups\"", + "type": "string" + } + } + }, + "web.duplicateGroup": { + "type": "object", + "properties": { + "count": { + "type": "integer" + }, + "files": { + "type": "array", + "items": { + "$ref": "#/definitions/indexing.SearchResult" + } + }, + "size": { + "type": "integer" + } + } + }, + "web.duplicateResponse": { + "type": "object", + "properties": { + "groups": { + "type": "array", + "items": { + "$ref": "#/definitions/web.duplicateGroup" + } + }, + "incomplete": { + "type": "boolean" + }, + "reason": { + "type": "string" + } + } + }, + "web.fileWatchMetadata": { + "type": "object", + "properties": { + "modified": { + "description": "Modification time", + "type": "string" + }, + "name": { + "description": "File name", + "type": "string" + }, + "size": { + "description": "File size in bytes (for directories, total size of all files)", + "type": "integer" + }, + "type": { + "description": "MIME type", + "type": "string" + } + } + }, + "web.fileWatchResponse": { + "type": "object", + "properties": { + "contents": { + "description": "Text content for text files", + "type": "string" + }, + "isText": { + "description": "Whether the file is a text file", + "type": "boolean" + }, + "metadata": { + "description": "File metadata for non-text files", + "allOf": [ + { + "$ref": "#/definitions/web.fileWatchMetadata" + } + ] + } + } + }, + "web.pinnedItemPatchRequest": { + "type": "object", + "required": [ + "name", + "path", + "source" + ], + "properties": { + "name": { + "description": "item basename within path", + "type": "string" + }, + "path": { + "description": "scope-relative parent directory", + "type": "string" + }, + "source": { + "type": "string" + } + } + }, + "web.sharePinnedItemPatchRequest": { + "type": "object", + "required": [ + "name", + "path" + ], + "properties": { + "name": { + "type": "string" + }, + "path": { + "type": "string" + } + } + }, + "web.unarchiveRequest": { + "type": "object", + "properties": { + "deleteAfter": { + "description": "If true, delete the archive file after successful extraction (optional; default: false). Example: true", + "type": "boolean" + }, + "destination": { + "description": "Directory path on toSource to extract into (required). Example: \"/projects/imported\"", + "type": "string" + }, + "fromSource": { + "description": "Source name where the archive file lives (required). Example: \"default\"", + "type": "string" + }, + "path": { + "description": "Path to the archive file on fromSource; .zip, .tar.gz, or .tgz (required). Example: \"/downloads/data.zip\"", + "type": "string" + }, + "toSource": { + "description": "Source name where contents will be extracted (optional; default: fromSource). Example: \"restored\"", + "type": "string" + } + } + }, + "web.viewTokenResponse": { + "type": "object", + "properties": { + "expiresAt": { + "type": "integer" + }, + "viewToken": { + "type": "string" + } + } } } } \ No newline at end of file diff --git a/backend/swagger/docs/swagger.yaml b/backend/swagger/docs/swagger.yaml index dd2cf8eed0..d5e7ec8de8 100644 --- a/backend/swagger/docs/swagger.yaml +++ b/backend/swagger/docs/swagger.yaml @@ -10,372 +10,6 @@ definitions: type: string type: array type: object - http.AuthTokenFrontend: - properties: - Permissions: - $ref: '#/definitions/users.Permissions' - expiresAt: - type: integer - issuedAt: - type: integer - name: - type: string - token: - type: string - type: object - http.BulkDeleteItem: - properties: - message: - type: string - path: - type: string - source: - type: string - type: object - http.BulkDeleteResponse: - properties: - failed: - items: - $ref: '#/definitions/http.BulkDeleteItem' - type: array - succeeded: - items: - $ref: '#/definitions/http.BulkDeleteItem' - type: array - type: object - http.DirectDownloadResponse: - properties: - hash: - type: string - shareUrl: - type: string - status: - type: string - url: - type: string - type: object - http.GroupListResponse: - properties: - groups: - items: - type: string - type: array - type: object - http.HttpResponse: - properties: - message: - type: string - status: - type: integer - token: - type: string - type: object - http.MoveCopyItem: - properties: - fromPath: - type: string - fromSource: - type: string - message: - type: string - toPath: - type: string - toSource: - type: string - type: object - http.MoveCopyRequest: - properties: - action: - description: '"copy", "move", or "rename"' - type: string - items: - items: - $ref: '#/definitions/http.MoveCopyItem' - type: array - overwrite: - description: Overwrite if destination exists - type: boolean - rename: - description: Auto-rename if destination exists - type: boolean - type: object - http.MoveCopyResponse: - properties: - failed: - items: - $ref: '#/definitions/http.MoveCopyItem' - type: array - succeeded: - items: - $ref: '#/definitions/http.MoveCopyItem' - type: array - type: object - http.ShareResponse: - properties: - allowCreate: - description: allow creating files - type: boolean - allowDelete: - type: boolean - allowModify: - description: allow modifying files - type: boolean - allowReplacements: - description: allow replacements of files - type: boolean - allowedUsernames: - items: - type: string - type: array - banner: - type: string - bannerUrl: - type: string - canEditShare: - type: boolean - description: - type: string - disableAnonymous: - type: boolean - disableDownload: - description: don't allow downloading files - type: boolean - disableFileViewer: - description: don't allow viewing files - type: boolean - disableLoginOption: - description: disable login option in share (true = hide, false = show) - type: boolean - disableShareCard: - type: boolean - disableSidebar: - type: boolean - disableThumbnails: - type: boolean - downloadURL: - type: string - downloads: - type: integer - downloadsLimit: - type: integer - enableOnlyOffice: - type: boolean - enforceDarkLightMode: - description: '"dark" or "light"' - type: string - expire: - type: integer - extractEmbeddedSubtitles: - description: can be io intensive for large files and take 10-30 seconds. - type: boolean - favicon: - type: string - faviconUrl: - type: string - hasPassword: - type: boolean - hash: - type: string - hideFileExt: - description: show hidden files based on extensions in shares - type: string - hideNavButtons: - type: boolean - keepAfterExpiration: - type: boolean - maxBandwidth: - type: integer - password_hash: - type: string - path: - type: string - pathExists: - type: boolean - perUserDownloadLimit: - type: boolean - pinnedItems: - $ref: '#/definitions/share.PinnedItems' - quickDownload: - type: boolean - shareTheme: - type: string - shareType: - description: 'type of share: normal, upload, max' - type: string - shareURL: - type: string - showHidden: - description: show hidden files in share (true = show, false = hide) - type: boolean - sidebarLinks: - description: customizable sidebar links - items: - $ref: '#/definitions/users.SidebarLink' - type: array - source: - description: Override embedded field to show source name - type: string - sourceURL: - type: string - themeColor: - type: string - title: - type: string - token: - description: |- - Token is a random value that will only be set when PasswordHash is set. It is - URL-Safe and is used to download links in password-protected shares via a - query arg. - type: string - userDownloads: - additionalProperties: - type: integer - description: Track downloads per username - type: object - userID: - type: integer - username: - type: string - version: - type: integer - viewMode: - description: 'default view mode for anonymous users: "list", "compact", "normal", - "gallery"' - type: string - type: object - http.archiveCreateRequest: - properties: - compression: - description: 'Gzip compression level for tar.gz only, 0-9; 0 = default; ignored - for zip (optional). Example: 6' - type: integer - deleteAfter: - description: 'If true, delete the source files/directories after successful - archive creation (optional; requires delete permission). Example: true' - type: boolean - destination: - description: 'Full path where the archive will be created; use .zip or .tar.gz - extension (required). Example: "/backups/my-archive.zip"' - type: string - format: - description: 'Archive format: "zip" or "tar.gz" (optional; inferred from destination - if omitted). Example: "zip"' - type: string - fromSource: - description: 'Source name where the paths to archive live (required). Example: - "default"' - type: string - paths: - description: 'Paths of files or directories to add; directories are walked; - access-denied entries skipped (required). Example: ["/docs/file.txt", "/photos"]' - items: - type: string - type: array - toSource: - description: 'Source name where the archive file will be written (optional; - default: fromSource). Example: "backups"' - type: string - type: object - http.duplicateGroup: - properties: - count: - type: integer - files: - items: - $ref: '#/definitions/indexing.SearchResult' - type: array - size: - type: integer - type: object - http.duplicateResponse: - properties: - groups: - items: - $ref: '#/definitions/http.duplicateGroup' - type: array - incomplete: - type: boolean - reason: - type: string - type: object - http.fileWatchMetadata: - properties: - modified: - description: Modification time - type: string - name: - description: File name - type: string - size: - description: File size in bytes (for directories, total size of all files) - type: integer - type: - description: MIME type - type: string - type: object - http.fileWatchResponse: - properties: - contents: - description: Text content for text files - type: string - isText: - description: Whether the file is a text file - type: boolean - metadata: - allOf: - - $ref: '#/definitions/http.fileWatchMetadata' - description: File metadata for non-text files - type: object - http.pinnedItemPatchRequest: - properties: - name: - description: item basename within path - type: string - path: - description: scope-relative parent directory - type: string - source: - type: string - required: - - name - - path - - source - type: object - http.sharePinnedItemPatchRequest: - properties: - name: - description: item basename within path - type: string - path: - description: share-relative parent directory - type: string - required: - - name - - path - type: object - http.unarchiveRequest: - properties: - deleteAfter: - description: 'If true, delete the archive file after successful extraction - (optional; default: false). Example: true' - type: boolean - destination: - description: 'Directory path on toSource to extract into (required). Example: - "/projects/imported"' - type: string - fromSource: - description: 'Source name where the archive file lives (required). Example: - "default"' - type: string - path: - description: 'Path to the archive file on fromSource; .zip, .tar.gz, or .tgz - (required). Example: "/downloads/data.zip"' - type: string - toSource: - description: 'Source name where contents will be extracted (optional; default: - fromSource). Example: "restored"' - type: string - type: object indexing.SearchResult: properties: hasPreview: @@ -461,6 +95,9 @@ definitions: type: description: type of the file, either "directory" or a file mimetype type: string + viewToken: + description: opaque token for inline viewing via /resources/view or /media/stream + type: string type: object iteminfo.ExtendedItemInfo: properties: @@ -489,6 +126,9 @@ definitions: type: description: type of the file, either "directory" or a file mimetype type: string + viewToken: + description: opaque token for inline viewing via /resources/view or /media/stream + type: string type: object iteminfo.FileInfo: properties: @@ -572,6 +212,12 @@ definitions: artist: description: track artist type: string + audioCodec: + description: audio codec name (e.g. aac) + type: string + container: + description: container/format name (e.g. mov,mp4,m4a,3gp,3g2,mj2) + type: string duration: description: duration in seconds type: integer @@ -592,10 +238,28 @@ definitions: track: description: track number type: integer + videoCodec: + description: video codec name (e.g. h264) + type: string year: description: release year type: integer type: object + settings.ActivityConfig: + properties: + disabled: + description: 'disable semantic activity audit logging (default: false)' + type: boolean + flushIntervalSeconds: + description: buffer flush interval in seconds (default 10) + type: integer + maxBufferSize: + description: max in-memory buffer before immediate flush (default 10000) + type: integer + retentionDays: + description: purge activity rows older than this many days (default 30) + type: integer + type: object settings.Auth: properties: adminPassword: @@ -620,29 +284,6 @@ definitions: description: 'secret: secret used to encrypt TOTP secrets' type: string type: object - settings.ConditionalFilter: - properties: - hidden: - description: 'deprecated: use ignoreHidden instead. eg, FolderPath: "/" and - ignoreHidden: true will exclude hidden files and folders under the root - folder.' - type: boolean - ignoreHidden: - description: 'deprecated: use ignoreHidden instead. eg, FolderPath: "/" and - ignoreHidden: true will exclude hidden files and folders under the root - folder.' - type: boolean - ignoreZeroSizeFolders: - description: 'deprecated: use ignoreZeroSizeFolders instead. eg, FolderPath: - "/" and ignoreZeroSizeFolders: true will ignore folders with 0 size under - the root folder.' - type: boolean - rules: - description: list of item rules to apply to specific paths - items: - $ref: '#/definitions/settings.ConditionalRule' - type: array - type: object settings.ConditionalRule: properties: fileEndsWith: @@ -653,10 +294,6 @@ definitions: description: (global) exclude files that match these names. Eg. "file.txt" or "test.csv" type: string - fileNames: - description: 'deprecated: exclude files that match these names. Eg. "file.txt" - or "test.csv"' - type: string filePath: description: (global) exclude files that match this path. Eg. "/path/to/file.txt" or "/path/to/file.txt/subfile.txt" @@ -673,10 +310,6 @@ definitions: description: (global) exclude folders that match these names. Eg. "folder" or "subfolder" type: string - folderNames: - description: 'deprecated: exclude folders that match these names. Eg. "folder" - or "subfolder"' - type: string folderPath: description: (global) exclude folders that match this path. Eg. "/path/to/folder" or "/path/to/folder/subfolder" @@ -714,6 +347,19 @@ definitions: description: The description of the theme to display in the UI. type: string type: object + settings.Database: + properties: + activity: + allOf: + - $ref: '#/definitions/settings.ActivityConfig' + description: activity audit logging configuration + migrateFrom: + description: path to legacy database file for migration (optional) + type: string + path: + description: path to SQLite database file + type: string + type: object settings.ExternalLink: properties: text: @@ -794,15 +440,43 @@ definitions: type: object settings.Http: properties: + baseURL: + description: base URL for the server, the subpath that the server is running + on. + type: string disableRateLimit: description: turns off built-in auth route rate limiting and failed-login lockout (default false). type: boolean - trustedHeaders: - description: list of headers to trust, useful when behind a reverse proxy. - items: - type: string - type: array + disableWebDAV: + description: 'disable webdav support (default: false)' + type: boolean + externalUrl: + description: used by share links if set (eg. http://mydomain.com) + type: string + internalUrl: + description: used by integrations if set, this is the base domain that an + integration service will use to communicate with filebrowser (eg. http://localhost:8080) + type: string + listen: + description: 'address to listen on (default: 0.0.0.0)' + type: string + port: + description: port to listen on + type: integer + socket: + description: socket to listen on - eg. /var/run/filebrowser.sock + type: string + tlsCert: + description: path to TLS cert + type: string + tlsKey: + description: path to TLS key + type: string + trustProxyHeaders: + description: 'honor X-Forwarded-* and X-Real-IP from a reverse proxy (default: + false)' + type: boolean type: object settings.IndexSqlConfig: properties: @@ -984,15 +658,15 @@ definitions: description: output ffmpeg stdout for media integration -- careful can produces lots of output! type: boolean - exiftoolPath: - description: path to exiftool executable - type: string extractEmbeddedSubtitles: description: extract embedded subtitles from media files type: boolean ffmpegPath: description: path to ffmpeg directory with ffmpeg and ffprobe (eg. /usr/local/bin) type: string + hardwareAcceleration: + description: enable hardware acceleration for ffmpeg if available + type: boolean type: object settings.OidcConfig: properties: @@ -1151,10 +825,6 @@ definitions: type: object settings.Server: properties: - baseURL: - description: base URL for the server, the subpath that the server is running - on. - type: string cacheDir: description: path to the cache directory, used for thumbnails and other cached files @@ -1165,8 +835,9 @@ definitions: false)' type: boolean database: - description: path to the database file - type: string + allOf: + - $ref: '#/definitions/settings.Database' + description: SQLite database configuration disablePreviewResize: description: disable resizing of previews for faster loading over slow connections type: boolean @@ -1179,12 +850,6 @@ definitions: disableUpdateCheck: description: disables backend update check service type: boolean - disableWebDAV: - description: 'disable webdav support (default: false)' - type: boolean - externalUrl: - description: used by share links if set (eg. http://mydomain.com) - type: string filesystem: allOf: - $ref: '#/definitions/settings.Filesystem' @@ -1193,13 +858,6 @@ definitions: allOf: - $ref: '#/definitions/settings.IndexSqlConfig' description: Index database SQL configuration - internalUrl: - description: used by integrations if set, this is the base domain that an - integration service will use to communicate with filebrowser (eg. http://localhost:8080) - type: string - listen: - description: 'address to listen on (default: 0.0.0.0)' - type: string logging: items: $ref: '#/definitions/settings.LogConfig' @@ -1216,22 +874,10 @@ definitions: description: number of concurrent image processing jobs used to create previews, default is 4. type: integer - port: - description: port to listen on - type: integer - socket: - description: socket to listen on - eg. /var/run/filebrowser.sock - type: string sources: items: $ref: '#/definitions/settings.Source' type: array - tlsCert: - description: path to TLS cert - type: string - tlsKey: - description: path to TLS key - type: string required: - sources type: object @@ -1248,7 +894,10 @@ definitions: server: $ref: '#/definitions/settings.Server' userDefaults: - $ref: '#/definitions/settings.UserDefaults' + allOf: + - $ref: '#/definitions/settings.UserDefaults' + description: optional signup/CLI defaults; per-user values are managed in + the UI type: object settings.Source: properties: @@ -1265,10 +914,6 @@ definitions: type: object settings.SourceConfig: properties: - conditionals: - allOf: - - $ref: '#/definitions/settings.ConditionalFilter' - description: 'deprecated: use source.rules instead' createUserDir: description: create a user directory for each user under defaultUserScope + username @@ -1276,6 +921,11 @@ definitions: defaultEnabled: description: should be added as a default source for new users? type: boolean + defaultPermissions: + allOf: + - $ref: '#/definitions/users.SourceFilePermissions' + description: DefaultPermissions is the template for new user scopes on this + source (also synced globally via Access settings). defaultUserScope: description: defaults to root of index "/" should match folders under path type: string @@ -1286,10 +936,6 @@ definitions: description: disable the source, this is useful so you don't need to remove it from the config file type: boolean - indexingIntervalMinutes: - description: 'deprecated: create a rule with indexingIntervalMinutes to set - the indexing interval for this source' - type: integer private: description: designate as source as private -- currently just means no sharing permitted. @@ -1337,122 +983,20 @@ definitions: properties: account: $ref: '#/definitions/settings.UserDefaultsAccount' - customTheme: - description: 'deprecated: use ui.customTheme instead' - type: string - darkMode: - description: 'deprecated: use sidebar.darkMode instead' - type: boolean - dateFormat: - description: 'deprecated: use listing.dateFormat instead' - type: boolean - debugOffice: - description: 'deprecated: use fileViewer.debugOffice instead' - type: boolean - deleteAfterArchive: - description: 'deprecated: use listing.deleteAfterArchive instead' - type: boolean - deleteWithoutConfirming: - description: 'deprecated: use listing.deleteWithoutConfirming instead' - type: boolean - disableOfficePreviewExt: - description: 'deprecated: use disablePreviewExt instead' - type: string - disableOnlyOfficeExt: - description: 'deprecated: use fileViewer.disableOnlyOfficeExt instead' - type: string - disablePreviewExt: - description: 'deprecated: use preview.disablePreviewExt instead' - type: string - disableQuickToggles: - description: 'deprecated: use sidebar.disableQuickToggles instead' - type: boolean - disableSearchOptions: - description: 'deprecated: use search.disableOptions instead' - type: boolean - disableSettings: - description: 'deprecated: use account.disableSettings instead' - type: boolean - disableUpdateNotifications: - description: 'deprecated: use account.disableUpdateNotifications instead' - type: boolean - disableViewingExt: - description: 'deprecated: use fileViewer.disableViewingExt instead' - type: string - editorQuickSave: - description: Deprecated fields - kept for backwards compatibility - type: boolean fileLoading: $ref: '#/definitions/users.FileLoading' fileViewer: $ref: '#/definitions/settings.UserDefaultsFileViewer' - gallerySize: - description: 'deprecated: use sidebar.gallerySize instead' - type: integer - hideFileExt: - description: 'deprecated: use listing.hideFileExt instead' - type: string - hideFilesInTree: - description: 'deprecated: use sidebar.hideFilesInTree instead' - type: boolean - hideSidebarFileActions: - description: 'deprecated: use sidebar.hideSidebarFileActions instead' - type: boolean listing: $ref: '#/definitions/settings.UserDefaultsListing' - locale: - description: 'deprecated: use ui.locale instead' - type: string - lockPassword: - description: 'deprecated: use account.lockPassword instead' - type: boolean - loginMethod: - description: 'deprecated: use account.loginMethod instead' - type: string - permissions: - allOf: - - $ref: '#/definitions/settings.UserDefaultsPermissions' - description: 'deprecated: use account.permissions instead' - preferEditorForMarkdown: - description: 'deprecated: use fileViewer.preferEditorForMarkdown instead' - type: boolean preview: $ref: '#/definitions/settings.UserDefaultsPreview' - quickDownload: - description: 'deprecated: use listing.quickDownload instead' - type: boolean search: $ref: '#/definitions/settings.UserDefaultsSearch' - showCopyPath: - description: 'deprecated: use listing.showCopyPath instead' - type: boolean - showHidden: - description: 'deprecated: use listing.showHidden instead' - type: boolean - showSelectMultiple: - description: 'deprecated: use listing.showSelectMultiple instead' - type: boolean - showToolsInSidebar: - description: 'deprecated: use sidebar.showToolsInSidebar instead' - type: boolean sidebar: - allOf: - - $ref: '#/definitions/settings.UserDefaultsSidebar' - description: New organized structure - singleClick: - description: 'deprecated: use sidebar.singleClick instead' - type: boolean - stickySidebar: - description: 'deprecated: use sidebar.stickySidebar instead' - type: boolean - themeColor: - description: 'deprecated: use ui.themeColor instead' - type: string + $ref: '#/definitions/settings.UserDefaultsSidebar' ui: $ref: '#/definitions/settings.UserDefaultsUI' - viewMode: - description: 'deprecated: use sidebar.viewMode instead' - type: string type: object settings.UserDefaultsAccount: properties: @@ -1479,18 +1023,6 @@ definitions: api: description: allow api access type: boolean - create: - description: allow creating or uploading files - type: boolean - delete: - description: allow deleting files - type: boolean - download: - description: allow downloading files - type: boolean - modify: - description: allow modifying files - type: boolean realtime: description: allow realtime updates type: boolean @@ -1506,9 +1038,6 @@ definitions: debugOffice: description: debug onlyoffice editor type: boolean - defaultMediaPlayer: - description: disable the styled feature-rich media player for browser default - type: boolean disableOnlyOfficeExt: description: list of file extensions to disable onlyoffice editor for type: string @@ -1562,56 +1091,11 @@ definitions: description: 'view mode to use: eg. normal, list, grid, or compact' type: string type: object - settings.UserDefaultsPermissions: - properties: - admin: - description: 'deprecated: use account.permissions.admin instead. allow admin - access' - type: boolean - api: - description: 'deprecated: use account.permissions.api instead. allow api access' - type: boolean - create: - description: 'deprecated: use account.permissions.create instead. allow creating - or uploading files' - type: boolean - delete: - description: 'deprecated: use account.permissions.delete instead. allow deleting - files' - type: boolean - download: - description: 'deprecated: use account.permissions.download instead. allow - downloading files' - type: boolean - modify: - description: 'deprecated: use account.permissions.modify instead. allow modifying - files' - type: boolean - realtime: - description: 'deprecated: use account.permissions.realtime instead. allow - realtime updates' - type: boolean - share: - description: 'deprecated: use account.permissions.share instead. allow sharing - files' - type: boolean - type: object settings.UserDefaultsPreview: properties: audio: description: show thumbnails for audio files type: boolean - autoplayMedia: - description: 'deprecated: use fileViewer.autoplayMedia instead. autoplay media - files in preview' - type: boolean - defaultMediaPlayer: - description: 'deprecated: use fileViewer.defaultMediaPlayer instead. disable - the styled feature-rich media player for browser default' - type: boolean - disableHideSidebar: - description: deprecated fields - type: boolean disablePreviewExt: description: comma separated list of file extensions to disable preview for type: string @@ -1684,122 +1168,21 @@ definitions: etc' type: string type: object - share.CommonShare: - properties: - allowCreate: - description: allow creating files - type: boolean - allowDelete: - type: boolean - allowModify: - description: allow modifying files - type: boolean - allowReplacements: - description: allow replacements of files - type: boolean - allowedUsernames: - items: - type: string - type: array - banner: - type: string - bannerUrl: - type: string - canEditShare: - type: boolean - description: - type: string - disableAnonymous: - type: boolean - disableDownload: - description: don't allow downloading files - type: boolean - disableFileViewer: - description: don't allow viewing files - type: boolean - disableLoginOption: - description: disable login option in share (true = hide, false = show) - type: boolean - disableShareCard: - type: boolean - disableSidebar: - type: boolean - disableThumbnails: - type: boolean - downloadURL: - type: string - downloadsLimit: - type: integer - enableOnlyOffice: - type: boolean - enforceDarkLightMode: - description: '"dark" or "light"' - type: string - extractEmbeddedSubtitles: - description: can be io intensive for large files and take 10-30 seconds. - type: boolean - favicon: - type: string - faviconUrl: - type: string - hasPassword: - type: boolean - hideFileExt: - description: show hidden files based on extensions in shares - type: string - hideNavButtons: - type: boolean - keepAfterExpiration: - type: boolean - maxBandwidth: - type: integer - path: - type: string - perUserDownloadLimit: - type: boolean - quickDownload: - type: boolean - shareTheme: - type: string - shareType: - description: 'type of share: normal, upload, max' - type: string - shareURL: - type: string - showHidden: - description: show hidden files in share (true = show, false = hide) - type: boolean - sidebarLinks: - description: customizable sidebar links - items: - $ref: '#/definitions/users.SidebarLink' - type: array - source: - description: backend source is path to maintain between name changes - type: string - sourceURL: - type: string - themeColor: - type: string - title: - type: string - viewMode: - description: 'default view mode for anonymous users: "list", "compact", "normal", - "gallery"' + share.PinnedItems: + additionalProperties: + items: type: string + type: array type: object - share.CreateBody: + share.Share: properties: allowCreate: - description: allow creating files type: boolean allowDelete: type: boolean allowModify: - description: allow modifying files type: boolean allowReplacements: - description: allow replacements of files type: boolean allowedUsernames: items: @@ -1816,125 +1199,10 @@ definitions: disableAnonymous: type: boolean disableDownload: - description: don't allow downloading files type: boolean disableFileViewer: - description: don't allow viewing files type: boolean disableLoginOption: - description: disable login option in share (true = hide, false = show) - type: boolean - disableShareCard: - type: boolean - disableSidebar: - type: boolean - disableThumbnails: - type: boolean - downloadURL: - type: string - downloadsLimit: - type: integer - enableOnlyOffice: - type: boolean - enforceDarkLightMode: - description: '"dark" or "light"' - type: string - expires: - type: string - extractEmbeddedSubtitles: - description: can be io intensive for large files and take 10-30 seconds. - type: boolean - favicon: - type: string - faviconUrl: - type: string - hasPassword: - type: boolean - hash: - type: string - hideFileExt: - description: show hidden files based on extensions in shares - type: string - hideNavButtons: - type: boolean - keepAfterExpiration: - type: boolean - maxBandwidth: - type: integer - password: - type: string - path: - type: string - perUserDownloadLimit: - type: boolean - quickDownload: - type: boolean - shareTheme: - type: string - shareType: - description: 'type of share: normal, upload, max' - type: string - shareURL: - type: string - showHidden: - description: show hidden files in share (true = show, false = hide) - type: boolean - sidebarLinks: - description: customizable sidebar links - items: - $ref: '#/definitions/users.SidebarLink' - type: array - source: - description: backend source is path to maintain between name changes - type: string - sourceURL: - type: string - themeColor: - type: string - title: - type: string - unit: - type: string - viewMode: - description: 'default view mode for anonymous users: "list", "compact", "normal", - "gallery"' - type: string - type: object - share.Link: - properties: - allowCreate: - description: allow creating files - type: boolean - allowDelete: - type: boolean - allowModify: - description: allow modifying files - type: boolean - allowReplacements: - description: allow replacements of files - type: boolean - allowedUsernames: - items: - type: string - type: array - banner: - type: string - bannerUrl: - type: string - canEditShare: - type: boolean - description: - type: string - disableAnonymous: - type: boolean - disableDownload: - description: don't allow downloading files - type: boolean - disableFileViewer: - description: don't allow viewing files - type: boolean - disableLoginOption: - description: disable login option in share (true = hide, false = show) type: boolean disableShareCard: type: boolean @@ -1956,7 +1224,6 @@ definitions: expire: type: integer extractEmbeddedSubtitles: - description: can be io intensive for large files and take 10-30 seconds. type: boolean favicon: type: string @@ -1988,20 +1255,21 @@ definitions: shareTheme: type: string shareType: - description: 'type of share: normal, upload, max' type: string shareURL: type: string showHidden: - description: show hidden files in share (true = show, false = hide) type: boolean sidebarLinks: - description: customizable sidebar links items: $ref: '#/definitions/users.SidebarLink' type: array + singleFileShare: + type: boolean source: - description: backend source is path to maintain between name changes + description: source display name for API; backend path is Share.SourcePath + type: string + sourcePath: type: string sourceURL: type: string @@ -2010,36 +1278,237 @@ definitions: title: type: string token: - description: |- - Token is a random value that will only be set when PasswordHash is set. It is - URL-Safe and is used to download links in password-protected shares via a - query arg. type: string userDownloads: additionalProperties: type: integer - description: Track downloads per username type: object userID: type: integer version: type: integer viewMode: - description: 'default view mode for anonymous users: "list", "compact", "normal", - "gallery"' + description: default view mode for anonymous users type: string type: object - share.PinnedItems: - additionalProperties: - items: + share.ShareFrontend: + properties: + allowCreate: + type: boolean + allowDelete: + type: boolean + allowModify: + type: boolean + allowReplacements: + type: boolean + allowedUsernames: + items: + type: string + type: array + banner: + type: string + bannerUrl: + type: string + canEditShare: + type: boolean + description: + type: string + disableAnonymous: + type: boolean + disableDownload: + type: boolean + disableFileViewer: + type: boolean + disableLoginOption: + type: boolean + disableShareCard: + type: boolean + disableSidebar: + type: boolean + disableThumbnails: + type: boolean + downloadURL: + type: string + downloads: + type: integer + downloadsLimit: + type: integer + enableOnlyOffice: + type: boolean + enforceDarkLightMode: + description: '"dark" or "light"' + type: string + expire: + type: integer + expires: + type: string + extractEmbeddedSubtitles: + type: boolean + favicon: + type: string + faviconUrl: + type: string + hasPassword: + type: boolean + hash: + type: string + hideFileExt: + description: show hidden files based on extensions in shares + type: string + hideNavButtons: + type: boolean + keepAfterExpiration: + type: boolean + maxBandwidth: + type: integer + path: + type: string + pathExists: + type: boolean + perUserDownloadLimit: + type: boolean + quickDownload: + type: boolean + shareTheme: + type: string + shareType: + type: string + shareURL: + type: string + showHidden: + type: boolean + sidebarLinks: + items: + $ref: '#/definitions/users.SidebarLink' + type: array + singleFileShare: + type: boolean + source: + description: source display name for API; backend path is Share.SourcePath + type: string + sourceURL: + type: string + themeColor: + type: string + title: + type: string + unit: + type: string + username: + type: string + viewMode: + description: default view mode for anonymous users + type: string + type: object + share.SharePostBody: + properties: + allowCreate: + type: boolean + allowDelete: + type: boolean + allowModify: + type: boolean + allowReplacements: + type: boolean + allowedUsernames: + items: + type: string + type: array + banner: + type: string + bannerUrl: + type: string + canEditShare: + type: boolean + description: + type: string + disableAnonymous: + type: boolean + disableDownload: + type: boolean + disableFileViewer: + type: boolean + disableLoginOption: + type: boolean + disableShareCard: + type: boolean + disableSidebar: + type: boolean + disableThumbnails: + type: boolean + downloadURL: + type: string + downloadsLimit: + type: integer + enableOnlyOffice: + type: boolean + enforceDarkLightMode: + description: '"dark" or "light"' + type: string + expires: + type: string + extractEmbeddedSubtitles: + type: boolean + favicon: + type: string + faviconUrl: + type: string + hasPassword: + type: boolean + hash: + type: string + hideFileExt: + description: show hidden files based on extensions in shares + type: string + hideNavButtons: + type: boolean + keepAfterExpiration: + type: boolean + maxBandwidth: + type: integer + password: + type: string + path: + type: string + perUserDownloadLimit: + type: boolean + quickDownload: + type: boolean + shareTheme: + type: string + shareType: + type: string + shareURL: + type: string + showHidden: + type: boolean + sidebarLinks: + items: + $ref: '#/definitions/users.SidebarLink' + type: array + singleFileShare: + type: boolean + source: + description: source display name for API; backend path is Share.SourcePath + type: string + sourceURL: + type: string + themeColor: + type: string + title: + type: string + unit: + type: string + viewMode: + description: default view mode for anonymous users type: string - type: array type: object users.AuthToken: properties: Permissions: $ref: '#/definitions/users.Permissions' belongsTo: + description: numeric user id in JWT claims (bolt-era small ids still work) type: integer expiresAt: type: integer @@ -2052,6 +1521,19 @@ definitions: type: string token: type: string + username: + type: string + type: object + users.BackendScope: + properties: + path: + description: real path for the source + type: string + permissions: + $ref: '#/definitions/users.SourceFilePermissions' + scope: + description: index path within that source + type: string type: object users.FileLoading: properties: @@ -2064,6 +1546,160 @@ definitions: uploadChunkSizeMb: type: integer type: object + users.FrontendScope: + properties: + name: + description: 'Bolt: filesystem path; JSON API: display name after prepForFrontend' + type: string + permissions: + $ref: '#/definitions/users.SourceFilePermissions' + scope: + description: index path within that source + type: string + type: object + users.FrontendUser: + properties: + customTheme: + description: Name of theme to use chosen from custom themes config. + type: string + darkMode: + description: should dark mode be enabled + type: boolean + dateFormat: + description: when false, the date is relative, when true, the date is an exact + timestamp + type: boolean + debugOffice: + description: debug onlyoffice editor + type: boolean + deleteAfterArchive: + description: delete source files after successful creation/extraction of archives + type: boolean + deleteWithoutConfirming: + description: delete files without confirmation + type: boolean + disableOfficePreviewExt: + description: deprecated + type: string + disableOnlyOfficeExt: + description: deprecated + type: string + disablePreviewExt: + description: space separated list of file extensions to disable preview for + type: string + disableQuickToggles: + description: disable the quick toggles in the sidebar + type: boolean + disableSearchOptions: + description: disable the search options in the search bar + type: boolean + disableSettings: + type: boolean + disableUpdateNotifications: + description: disable update notifications + type: boolean + disableViewingExt: + description: space separated list of file extensions to disable viewing for + type: string + editorQuickSave: + description: show quick save button in editor + type: boolean + fileLoading: + allOf: + - $ref: '#/definitions/users.FileLoading' + description: upload and download settings + gallerySize: + description: 0-9 - the size of the gallery thumbnails + type: integer + hideFileExt: + description: space separated list of file extensions to hide in UI and API + type: string + hideFilesInTree: + description: hide files in the sidebar tree navigation, when true, will show + only directories. + type: boolean + hideSidebarFileActions: + description: hide the file actions in the sidebar + type: boolean + locale: + description: 'language to use: eg. de, en, or fr' + type: string + lockPassword: + type: boolean + loginMethod: + $ref: '#/definitions/users.LoginMethod' + otpEnabled: + type: boolean + passkeyCredentials: + items: + $ref: '#/definitions/users.WebAuthnCredential' + type: array + password: + type: string + perm: + $ref: '#/definitions/users.Permissions' + permissions: + allOf: + - $ref: '#/definitions/users.Permissions' + description: 'global: admin, api, share, realtime' + preferEditorForMarkdown: + description: prefer editor first for markdown files instead of the Markdown + Viewer + type: boolean + preview: + $ref: '#/definitions/users.Preview' + quickDownload: + description: show icon to download in one click + type: boolean + scopes: + items: + $ref: '#/definitions/users.FrontendScope' + type: array + showCopyPath: + description: show copy path action in the context menu + type: boolean + showFirstLogin: + type: boolean + showHidden: + description: show hidden files in the UI. On windows this includes files starting + with a dot and windows hidden files + type: boolean + showSelectMultiple: + description: show select multiple files on desktop + type: boolean + showToolsInSidebar: + description: 'when false, sidebar hides links with category "tool" (default: + true)' + type: boolean + sidebarLinks: + description: customizable sidebar links + items: + $ref: '#/definitions/users.SidebarLink' + type: array + singleClick: + description: open directory on single click, also enables middle click to + open in new tab + type: boolean + sorting: + $ref: '#/definitions/users.Sorting' + sourcePermissions: + additionalProperties: + $ref: '#/definitions/users.SourceFilePermissions' + description: 'deprecated: use scopes[].permissions' + type: object + stickySidebar: + description: keep sidebar open when navigating + type: boolean + themeColor: + description: 'theme color to use: eg. #ff0000, or var(--red), var(--purple), + etc' + type: string + username: + type: string + viewMode: + description: 'view mode to use: eg. normal, list, grid, or compact' + type: string + type: object users.LoginMethod: enum: - password @@ -2087,16 +1723,16 @@ definitions: description: allow api access type: boolean create: - description: allow creating or uploading files + description: 'deprecated: legacy user migration only; not used for API tokens' type: boolean delete: - description: allow deleting files + description: 'deprecated: legacy user migration only; not used for API tokens' type: boolean download: - description: allow downloading files + description: 'deprecated: legacy user migration only; not used for API tokens' type: boolean modify: - description: allow modifying files + description: 'deprecated: legacy user migration only; not used for API tokens' type: boolean realtime: description: allow realtime updates @@ -2104,6 +1740,9 @@ definitions: share: description: allow sharing files type: boolean + view: + description: 'deprecated: legacy user migration only; not used for API tokens' + type: boolean type: object users.PinnedItems: additionalProperties: @@ -2121,9 +1760,6 @@ definitions: autoplayMedia: description: autoplay media files in preview type: boolean - defaultMediaPlayer: - description: disable html5 media player and use the default media player - type: boolean disableHideSidebar: description: disable the hide sidebar preview for previews and editors type: boolean @@ -2175,21 +1811,39 @@ definitions: by: type: string type: object - users.SourceScope: + users.SourceFilePermissions: properties: - name: - description: 'Bolt: filesystem path; JSON API: display name after prepForFrontend' - type: string - scope: - description: index path within that source - type: string + configured: + description: true when explicitly set (allows intentional deny-all) + type: boolean + create: + type: boolean + delete: + type: boolean + download: + type: boolean + modify: + type: boolean + view: + type: boolean type: object users.User: properties: apiKeys: additionalProperties: $ref: '#/definitions/users.AuthToken' - description: 'deprecated: use Tokens instead' + type: object + backendScopes: + description: |- + BackendScopes is the authoritative, persisted access list (SourceScope.Name = backend source path). + SQLite stores this inside user_data JSON under the key "scopes" (see sqldb.UserData). + items: + $ref: '#/definitions/users.BackendScope' + type: array + backendSourcePermissions: + additionalProperties: + $ref: '#/definitions/users.SourceFilePermissions' + description: key = source path type: object customTheme: description: Name of theme to use chosen from custom themes config. @@ -2263,7 +1917,6 @@ definitions: loginMethod: $ref: '#/definitions/users.LoginMethod' otpEnabled: - description: true if TOTP is enabled, false otherwise type: boolean passkeyCredentials: items: @@ -2272,11 +1925,11 @@ definitions: password: type: string perm: + $ref: '#/definitions/users.Permissions' + permissions: allOf: - $ref: '#/definitions/users.Permissions' - description: legacy for migration purposes... og filebrowser has perm attribute - permissions: - $ref: '#/definitions/users.Permissions' + description: 'global: admin, api, share, realtime' pinnedItems: $ref: '#/definitions/users.PinnedItems' preferEditorForMarkdown: @@ -2288,11 +1941,9 @@ definitions: quickDownload: description: show icon to download in one click type: boolean - scope: - type: string scopes: items: - $ref: '#/definitions/users.SourceScope' + $ref: '#/definitions/users.FrontendScope' type: array showCopyPath: description: show copy path action in the context menu @@ -2321,6 +1972,11 @@ definitions: type: boolean sorting: $ref: '#/definitions/users.Sorting' + sourcePermissions: + additionalProperties: + $ref: '#/definitions/users.SourceFilePermissions' + description: 'deprecated: use scopes[].permissions' + type: object stickySidebar: description: keep sidebar open when navigating type: boolean @@ -2415,6 +2071,246 @@ definitions: description: title/description type: string type: object + web.AuthTokenFrontend: + properties: + Permissions: + $ref: '#/definitions/users.Permissions' + expiresAt: + type: integer + issuedAt: + type: integer + minimal: + type: boolean + name: + type: string + token: + type: string + type: object + web.BulkDeleteItem: + properties: + message: + type: string + path: + type: string + source: + type: string + type: object + web.BulkDeleteResponse: + properties: + failed: + items: + $ref: '#/definitions/web.BulkDeleteItem' + type: array + succeeded: + items: + $ref: '#/definitions/web.BulkDeleteItem' + type: array + type: object + web.DirectDownloadResponse: + properties: + hash: + type: string + shareUrl: + type: string + status: + type: string + url: + type: string + type: object + web.GroupListResponse: + properties: + groups: + items: + type: string + type: array + type: object + web.HttpResponse: + properties: + message: + type: string + status: + type: integer + token: + type: string + type: object + web.MoveCopyItem: + properties: + fromPath: + type: string + fromSource: + type: string + message: + type: string + toPath: + type: string + toSource: + type: string + type: object + web.MoveCopyRequest: + properties: + action: + description: '"copy", "move", or "rename"' + type: string + items: + items: + $ref: '#/definitions/web.MoveCopyItem' + type: array + overwrite: + description: Overwrite if destination exists + type: boolean + rename: + description: Auto-rename if destination exists + type: boolean + type: object + web.MoveCopyResponse: + properties: + failed: + items: + $ref: '#/definitions/web.MoveCopyItem' + type: array + succeeded: + items: + $ref: '#/definitions/web.MoveCopyItem' + type: array + type: object + web.archiveCreateRequest: + properties: + compression: + description: 'Gzip compression level for tar.gz only, 0-9; 0 = default; ignored + for zip (optional). Example: 6' + type: integer + deleteAfter: + description: 'If true, delete the source files/directories after successful + archive creation (optional; requires delete permission). Example: true' + type: boolean + destination: + description: 'Full path where the archive will be created; use .zip or .tar.gz + extension (required). Example: "/backups/my-archive.zip"' + type: string + format: + description: 'Archive format: "zip" or "tar.gz" (optional; inferred from destination + if omitted). Example: "zip"' + type: string + fromSource: + description: 'Source name where the paths to archive live (required). Example: + "default"' + type: string + paths: + description: 'Paths of files or directories to add; directories are walked; + access-denied entries skipped (required). Example: ["/docs/file.txt", "/photos"]' + items: + type: string + type: array + toSource: + description: 'Source name where the archive file will be written (optional; + default: fromSource). Example: "backups"' + type: string + type: object + web.duplicateGroup: + properties: + count: + type: integer + files: + items: + $ref: '#/definitions/indexing.SearchResult' + type: array + size: + type: integer + type: object + web.duplicateResponse: + properties: + groups: + items: + $ref: '#/definitions/web.duplicateGroup' + type: array + incomplete: + type: boolean + reason: + type: string + type: object + web.fileWatchMetadata: + properties: + modified: + description: Modification time + type: string + name: + description: File name + type: string + size: + description: File size in bytes (for directories, total size of all files) + type: integer + type: + description: MIME type + type: string + type: object + web.fileWatchResponse: + properties: + contents: + description: Text content for text files + type: string + isText: + description: Whether the file is a text file + type: boolean + metadata: + allOf: + - $ref: '#/definitions/web.fileWatchMetadata' + description: File metadata for non-text files + type: object + web.pinnedItemPatchRequest: + properties: + name: + description: item basename within path + type: string + path: + description: scope-relative parent directory + type: string + source: + type: string + required: + - name + - path + - source + type: object + web.sharePinnedItemPatchRequest: + properties: + name: + type: string + path: + type: string + required: + - name + - path + type: object + web.unarchiveRequest: + properties: + deleteAfter: + description: 'If true, delete the archive file after successful extraction + (optional; default: false). Example: true' + type: boolean + destination: + description: 'Directory path on toSource to extract into (required). Example: + "/projects/imported"' + type: string + fromSource: + description: 'Source name where the archive file lives (required). Example: + "default"' + type: string + path: + description: 'Path to the archive file on fromSource; .zip, .tar.gz, or .tgz + (required). Example: "/downloads/data.zip"' + type: string + toSource: + description: 'Source name where contents will be extracted (optional; default: + fromSource). Example: "restored"' + type: string + type: object + web.viewTokenResponse: + properties: + expiresAt: + type: integer + viewToken: + type: string + type: object info: contact: {} paths: @@ -2713,7 +2609,7 @@ paths: "200": description: Object containing a list of groups schema: - $ref: '#/definitions/http.GroupListResponse' + $ref: '#/definitions/web.GroupListResponse' "403": description: Forbidden schema: @@ -2918,7 +2814,7 @@ paths: "200": description: OTP token is valid. schema: - $ref: '#/definitions/http.HttpResponse' + $ref: '#/definitions/web.HttpResponse' "401": description: Unauthorized - invalid TOTP token schema: @@ -3013,7 +2909,7 @@ paths: "200": description: API token deleted successfully schema: - $ref: '#/definitions/http.HttpResponse' + $ref: '#/definitions/web.HttpResponse' "404": description: Not found schema: @@ -3045,7 +2941,7 @@ paths: "200": description: API token details schema: - $ref: '#/definitions/http.AuthTokenFrontend' + $ref: '#/definitions/web.AuthTokenFrontend' "404": description: Not found schema: @@ -3076,11 +2972,16 @@ paths: name: days required: true type: string - - description: Permissions for the API token (comma-separated) + - description: 'Global permissions (comma-separated: admin, api, share, realtime). + Send \' in: query name: permissions - required: true type: string + - description: When true, create a minimal token (standard JWT claims only). + When false, create a customized token using permissions (may be empty). + in: query + name: minimal + type: boolean produces: - application/json responses: @@ -3088,7 +2989,7 @@ paths: description: Token created successfully, response contains json object with token schema: - $ref: '#/definitions/http.HttpResponse' + $ref: '#/definitions/web.HttpResponse' "400": description: Bad request schema: @@ -3128,7 +3029,7 @@ paths: description: List of API tokens schema: items: - $ref: '#/definitions/http.AuthTokenFrontend' + $ref: '#/definitions/web.AuthTokenFrontend' type: array "404": description: Not found @@ -3326,7 +3227,7 @@ paths: type: object summary: Get lyrics for an audio file tags: - - Resources + - Media /api/media/metadata: get: consumes: @@ -3369,6 +3270,56 @@ paths: type: object summary: Directory with media metadata tags: + - Media + /api/media/stream: + get: + consumes: + - application/json + description: Returns raw file bytes for inline UI viewing in capped byte ranges. + Requires a viewToken minted by GET /resources. Media files must use Range + requests; full-file GET responses are rejected. Never counts toward download + limits or activity. + parameters: + - description: Source name for the file (required) + in: query + name: source + required: true + type: string + - description: File path + in: query + name: file + required: true + type: string + - description: Opaque view grant token from file metadata + in: query + name: viewToken + required: true + type: string + responses: + "200": + description: Raw file content (inline) + schema: + type: file + "403": + description: Missing or invalid view token + schema: + additionalProperties: + type: string + type: object + "404": + description: File not found + schema: + additionalProperties: + type: string + type: object + "500": + description: Internal server error + schema: + additionalProperties: + type: string + type: object + summary: Stream content of a single media file for inline viewing + tags: - Resources /api/media/subtitles: get: @@ -3430,7 +3381,7 @@ paths: type: object summary: Get subtitle content tags: - - Resources + - Media /api/office/callback: get: consumes: @@ -3671,18 +3622,18 @@ paths: name: request required: true schema: - $ref: '#/definitions/http.MoveCopyRequest' + $ref: '#/definitions/web.MoveCopyRequest' produces: - application/json responses: "200": description: All operations completed successfully schema: - $ref: '#/definitions/http.MoveCopyResponse' + $ref: '#/definitions/web.MoveCopyResponse' "207": description: Partial success - some operations succeeded, some failed schema: - $ref: '#/definitions/http.MoveCopyResponse' + $ref: '#/definitions/web.MoveCopyResponse' "400": description: Bad request - invalid JSON or parameters schema: @@ -3704,7 +3655,7 @@ paths: "500": description: All operations failed schema: - $ref: '#/definitions/http.MoveCopyResponse' + $ref: '#/definitions/web.MoveCopyResponse' summary: Move, copy, or rename resources tags: - Resources @@ -3836,7 +3787,7 @@ paths: name: body required: true schema: - $ref: '#/definitions/http.archiveCreateRequest' + $ref: '#/definitions/web.archiveCreateRequest' produces: - application/json responses: @@ -3893,7 +3844,7 @@ paths: required: true schema: items: - $ref: '#/definitions/http.BulkDeleteItem' + $ref: '#/definitions/web.BulkDeleteItem' type: array produces: - application/json @@ -3901,11 +3852,11 @@ paths: "200": description: All resources deleted successfully schema: - $ref: '#/definitions/http.BulkDeleteResponse' + $ref: '#/definitions/web.BulkDeleteResponse' "207": description: Partial success - some resources deleted, some failed schema: - $ref: '#/definitions/http.BulkDeleteResponse' + $ref: '#/definitions/web.BulkDeleteResponse' "400": description: Bad request - invalid JSON or empty items array schema: @@ -4097,7 +4048,7 @@ paths: required: true type: string - description: Preview size ('small' or 'large'). Default is based on server - config. + settings.Config. in: query name: size type: string @@ -4167,7 +4118,7 @@ paths: name: body required: true schema: - $ref: '#/definitions/http.unarchiveRequest' + $ref: '#/definitions/web.unarchiveRequest' produces: - application/json responses: @@ -4212,6 +4163,91 @@ paths: summary: Extract an archive on the server tags: - Resources + /api/resources/view: + get: + consumes: + - application/json + description: Returns raw file bytes for inline UI viewing. Requires a viewToken + minted by GET /resources. Never counts toward download limits or activity + and does not require download permission. + parameters: + - description: Source name for the file (required) + in: query + name: source + required: true + type: string + - description: File path + in: query + name: file + required: true + type: string + - description: Opaque view grant token from file metadata + in: query + name: viewToken + required: true + type: string + responses: + "200": + description: Raw file content (inline) + schema: + type: file + "403": + description: Missing or invalid view token + schema: + additionalProperties: + type: string + type: object + "404": + description: File not found + schema: + additionalProperties: + type: string + type: object + "500": + description: Internal server error + schema: + additionalProperties: + type: string + type: object + summary: View content of a single non-media file inline + tags: + - Resources + /api/resources/view-token: + post: + consumes: + - application/json + description: Mints or extends a source-scoped view token for inline viewing. + Authenticated routes require a web session (not a named API token). Public + share routes accept anonymous users when the share allows it. + parameters: + - description: Source name or share hash + in: query + name: source + type: string + - description: Share hash (public share routes) + in: query + name: hash + type: string + - description: Existing view token to extend + in: query + name: viewToken + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/web.viewTokenResponse' + "403": + description: Missing permission or API token used + schema: + additionalProperties: + type: string + type: object + summary: Refresh view token + tags: + - Resources /api/settings: get: consumes: @@ -4313,7 +4349,7 @@ paths: description: List of share links for the specified path schema: items: - $ref: '#/definitions/share.Link' + $ref: '#/definitions/share.ShareFrontend' type: array "500": description: Internal server error @@ -4346,7 +4382,7 @@ paths: "200": description: Updated share link schema: - $ref: '#/definitions/http.ShareResponse' + $ref: '#/definitions/share.ShareFrontend' "400": description: Bad request - missing or invalid parameters schema: @@ -4373,14 +4409,14 @@ paths: name: body required: true schema: - $ref: '#/definitions/share.CreateBody' + $ref: '#/definitions/share.SharePostBody' produces: - application/json responses: "200": description: Created share link schema: - $ref: '#/definitions/share.Link' + $ref: '#/definitions/share.ShareFrontend' "400": description: Bad request - failed to decode body schema: @@ -4432,7 +4468,7 @@ paths: "201": description: Direct download link created schema: - $ref: '#/definitions/http.DirectDownloadResponse' + $ref: '#/definitions/web.DirectDownloadResponse' "400": description: Bad request - invalid parameters or path is not a file schema: @@ -4467,7 +4503,7 @@ paths: description: List of share links schema: items: - $ref: '#/definitions/share.Link' + $ref: '#/definitions/share.ShareFrontend' type: array "500": description: Internal server error @@ -4478,7 +4514,7 @@ paths: summary: List share links tags: - Shares - /api/tools/duplicateFinder: + /api/tools/duplicate-finder: get: consumes: - application/json @@ -4509,7 +4545,7 @@ paths: description: List of duplicate file groups with metadata. Response includes 'incomplete' flag if processing stopped early due to resource limits. schema: - $ref: '#/definitions/http.duplicateResponse' + $ref: '#/definitions/web.duplicateResponse' "400": description: Bad Request schema: @@ -4526,7 +4562,7 @@ paths: summary: Find Duplicate Files tags: - Tools - /api/tools/fileWatcher: + /api/tools/file-watcher: get: consumes: - application/json @@ -4556,7 +4592,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/http.fileWatchResponse' + $ref: '#/definitions/web.fileWatchResponse' "400": description: Invalid request schema: @@ -4584,7 +4620,7 @@ paths: summary: Watch a file tags: - Tools - /api/tools/fileWatcher/sse: + /api/tools/file-watcher/sse: get: description: Establishes an SSE connection to receive periodic file updates parameters: @@ -4639,8 +4675,8 @@ paths: and metadata based on the user's session and scope. Supports searching across multiple sources when using the 'sources' parameter. parameters: - - description: Filter prefix or full legacy search text (required when no terms - are supplied) + - description: Filter prefix or full search text (required when no terms are + supplied) in: query name: query type: string @@ -4652,18 +4688,12 @@ paths: type: string name: terms type: array - - description: Source name for the desired source (deprecated, use 'sources' - instead) - in: query - name: source - type: string - description: Comma-separated source names when not using repeated scope=source:path in: query name: sources type: string - collectionFormat: csv - description: 'Repeated: either ''sourceName:relativePath'' per source, or - legacy single path when one source' + description: 'Repeated: ''sourceName:relativePath'' per source' in: query items: type: string @@ -4682,14 +4712,6 @@ paths: in: query name: useWildcard type: boolean - - description: 'Deprecated: alias for useWildcard' - in: query - name: glob - type: boolean - - description: 'Deprecated: alias for useWildcard' - in: query - name: useGlob - type: boolean - description: 'Optional: ''and'' to require all repeated ''terms'' match; default is OR' in: query @@ -4717,31 +4739,18 @@ paths: delete: consumes: - application/json - description: Deletes a user identified by their ID. When the authenticated actor - uses password login, they must send their current password in the X-Password - header. + description: Deletes a user identified by login name. parameters: - - description: User ID + - description: Username in: query - name: id + name: username required: true type: string - - description: Actor's current password (URL-encoded); required for password-login - actors - in: header - name: X-Password - type: string produces: - application/json responses: "200": description: User deleted successfully - "401": - description: Unauthorized - invalid or missing actor password when required - schema: - additionalProperties: - type: string - type: object "403": description: Forbidden schema: @@ -4754,18 +4763,19 @@ paths: additionalProperties: type: string type: object - summary: Delete a user by ID + summary: Delete a user by username tags: - Users get: consumes: - application/json - description: Returns a user's details based on their ID, or all users if no - id is provided. + description: Returns all users (admins) or only the current user; with ?username=self, + the logged-in user; with ?username=login, that user if permitted. Query id= + is not supported. parameters: - - description: User ID or 'self' + - description: Login name, or 'self' for the current session user in: query - name: id + name: username type: string produces: - application/json @@ -4773,7 +4783,13 @@ paths: "200": description: User details or list of users schema: - $ref: '#/definitions/users.User' + $ref: '#/definitions/users.FrontendUser' + "400": + description: Bad Request + schema: + additionalProperties: + type: string + type: object "403": description: Forbidden schema: @@ -4792,7 +4808,65 @@ paths: additionalProperties: type: string type: object - summary: Retrieve a user by ID + summary: List users or get one by username + tags: + - Users + patch: + consumes: + - application/json + description: Updates the details of a user identified by ID. which must list + the JSON field names to update. When the authenticated actor uses password + login, they must send their current password in the X-Password header unless + the update only touches NonAdminEditable profile fields (not password). Any + admin-only field requires confirmation. + parameters: + - description: user ID to update + in: query + name: id + type: string + - description: usename to update + in: query + name: id + type: string + - description: Actor's current password (URL-encoded); required for password-login + actors when updating password or any field outside NonAdminEditable + in: header + name: X-Password + type: string + - description: User data to update + in: body + name: data + required: true + schema: + $ref: '#/definitions/users.User' + responses: + "204": + description: No Content - User updated successfully + "400": + description: Bad Request + schema: + additionalProperties: + type: string + type: object + "401": + description: Unauthorized - invalid or missing actor password when required + schema: + additionalProperties: + type: string + type: object + "403": + description: Forbidden + schema: + additionalProperties: + type: string + type: object + "500": + description: Internal Server Error + schema: + additionalProperties: + type: string + type: object + summary: Update a user's details tags: - Users post: @@ -4840,65 +4914,7 @@ paths: summary: Create a new user tags: - Users - put: - consumes: - - application/json - description: Updates the details of a user identified by ID. When the authenticated - actor uses password login, they must send their current password in the X-Password - header unless the update only touches NonAdminEditable profile fields (not - password). Full updates (which empty or "all") or any admin-only field require - confirmation. - parameters: - - description: user ID to update - in: query - name: id - type: string - - description: usename to update - in: query - name: id - type: string - - description: Actor's current password (URL-encoded); required for password-login - actors when updating password, using which=all, or any field outside NonAdminEditable - in: header - name: X-Password - type: string - - description: User data to update - in: body - name: data - required: true - schema: - $ref: '#/definitions/users.User' - responses: - "204": - description: No Content - User updated successfully - "400": - description: Bad Request - schema: - additionalProperties: - type: string - type: object - "401": - description: Unauthorized - invalid or missing actor password when required - schema: - additionalProperties: - type: string - type: object - "403": - description: Forbidden - schema: - additionalProperties: - type: string - type: object - "500": - description: Internal Server Error - schema: - additionalProperties: - type: string - type: object - summary: Update a user's details - tags: - - Users - /api/users/pinnedItems: + /api/users/pinned-items: patch: consumes: - application/json @@ -4914,7 +4930,7 @@ paths: name: body required: true schema: - $ref: '#/definitions/http.pinnedItemPatchRequest' + $ref: '#/definitions/web.pinnedItemPatchRequest' produces: - application/json responses: @@ -4941,19 +4957,6 @@ paths: summary: Add or remove a pinned item tags: - Users - /health: - get: - consumes: - - application/json - description: Returns the health status of the API. - produces: - - application/json - responses: - "200": - description: successful health check response - schema: - $ref: '#/definitions/http.HttpResponse' - summary: Health Check /public/api/media/lyrics: get: parameters: @@ -4988,7 +4991,7 @@ paths: type: object summary: Get lyrics for an audio file (public share) tags: - - Shares + - Media /public/api/media/metadata: get: parameters: @@ -5015,7 +5018,58 @@ paths: $ref: '#/definitions/iteminfo.ExtendedFileInfo' summary: Directory with media metadata (public share) tags: - - Shares + - Media + /public/api/media/stream: + get: + consumes: + - application/json + description: Returns raw file bytes for inline UI viewing in capped byte ranges + on a share link. Requires viewToken from GET /public/api/resources. Media + files must use Range requests. Does not count toward download limits. + parameters: + - description: Share hash for authentication + in: query + name: hash + required: true + type: string + - description: File path within the share + in: query + name: file + required: true + type: string + - description: Opaque view grant token from share file metadata + in: query + name: viewToken + required: true + type: string + produces: + - application/octet-stream + responses: + "200": + description: Raw file content (inline) + schema: + type: file + "403": + description: Missing or invalid view token + schema: + additionalProperties: + type: string + type: object + "404": + description: Share or file not found + schema: + additionalProperties: + type: string + type: object + "500": + description: Internal server error + schema: + additionalProperties: + type: string + type: object + summary: Stream a single media file from a public share for inline viewing + tags: + - Resources /public/api/resources: get: consumes: @@ -5074,7 +5128,7 @@ paths: type: object summary: Get file/directory information from a public share tags: - - Shares + - Resources patch: consumes: - application/json @@ -5091,18 +5145,18 @@ paths: name: request required: true schema: - $ref: '#/definitions/http.MoveCopyRequest' + $ref: '#/definitions/web.MoveCopyRequest' produces: - application/json responses: "200": description: All operations completed successfully schema: - $ref: '#/definitions/http.MoveCopyResponse' + $ref: '#/definitions/web.MoveCopyResponse' "207": description: Partial success - some operations succeeded, some failed schema: - $ref: '#/definitions/http.MoveCopyResponse' + $ref: '#/definitions/web.MoveCopyResponse' "400": description: Bad request - invalid JSON or parameters schema: @@ -5124,10 +5178,10 @@ paths: "500": description: Internal server error schema: - $ref: '#/definitions/http.MoveCopyResponse' + $ref: '#/definitions/web.MoveCopyResponse' summary: Move, copy, or rename resources in a public share tags: - - Shares + - Resources post: consumes: - multipart/form-data @@ -5206,7 +5260,7 @@ paths: type: object summary: Upload files to a public upload share tags: - - Shares + - Resources put: consumes: - application/json @@ -5263,7 +5317,7 @@ paths: type: object summary: Update a file in a public share tags: - - Shares + - Resources /public/api/resources/bulk: delete: consumes: @@ -5282,7 +5336,7 @@ paths: required: true schema: items: - $ref: '#/definitions/http.BulkDeleteItem' + $ref: '#/definitions/web.BulkDeleteItem' type: array produces: - application/json @@ -5290,11 +5344,11 @@ paths: "200": description: All resources deleted successfully schema: - $ref: '#/definitions/http.BulkDeleteResponse' + $ref: '#/definitions/web.BulkDeleteResponse' "207": description: Partial success - some resources deleted, some failed schema: - $ref: '#/definitions/http.BulkDeleteResponse' + $ref: '#/definitions/web.BulkDeleteResponse' "400": description: Bad request - invalid JSON or empty items array schema: @@ -5315,7 +5369,7 @@ paths: type: object summary: Bulk delete resources from public share tags: - - Shares + - Resources /public/api/resources/download: get: consumes: @@ -5390,7 +5444,7 @@ paths: type: object summary: Download files from a public share tags: - - Shares + - Resources /public/api/resources/items: get: consumes: @@ -5440,7 +5494,7 @@ paths: type: object summary: Get directory items (public share) tags: - - Shares + - Resources /public/api/resources/pause: post: consumes: @@ -5477,7 +5531,7 @@ paths: type: object summary: Register graceful chunked upload pause (public share) tags: - - Shares + - Resources /public/api/resources/preview: get: consumes: @@ -5497,7 +5551,7 @@ paths: required: true type: string - description: 'Preview size: ''small'' or ''large''. Default is based on server - config.' + settings.Config.' in: query name: size type: string @@ -5534,7 +5588,93 @@ paths: type: object summary: Get image/video preview from a public share tags: - - Shares + - Resources + /public/api/resources/view: + get: + consumes: + - application/json + description: Returns raw file bytes for inline UI viewing on a share link. Requires + viewToken from GET /public/api/resources. Does not count toward download limits. + parameters: + - description: Share hash for authentication + in: query + name: hash + required: true + type: string + - description: File path within the share + in: query + name: file + required: true + type: string + - description: Opaque view grant token from share file metadata + in: query + name: viewToken + required: true + type: string + produces: + - application/octet-stream + responses: + "200": + description: Raw file content (inline) + schema: + type: file + "403": + description: Missing or invalid view token + schema: + additionalProperties: + type: string + type: object + "404": + description: Share or file not found + schema: + additionalProperties: + type: string + type: object + "500": + description: Internal server error + schema: + additionalProperties: + type: string + type: object + summary: View a single non-media file from a public share inline + tags: + - Resources + /public/api/resources/view-token: + post: + consumes: + - application/json + description: Mints or extends a source-scoped view token for inline viewing. + Authenticated routes require a web session (not a named API token). Public + share routes accept anonymous users when the share allows it. + parameters: + - description: Source name or share hash + in: query + name: source + type: string + - description: Share hash (public share routes) + in: query + name: hash + type: string + - description: Existing view token to extend + in: query + name: viewToken + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/web.viewTokenResponse' + "403": + description: Missing permission or API token used + schema: + additionalProperties: + type: string + type: object + summary: Refresh view token + tags: + - Resources /public/api/share/image: get: description: Returns a resizable preview (large size) for the banner or favicon @@ -5599,7 +5739,7 @@ paths: "200": description: Share information schema: - $ref: '#/definitions/share.CommonShare' + $ref: '#/definitions/share.Share' "404": description: Share hash not found schema: @@ -5609,12 +5749,12 @@ paths: summary: Get share information by hash tags: - Shares - /public/api/share/pinnedItems: + /public/api/share/pinned-items: patch: consumes: - application/json - description: Patches one pinned item at a time for share owners. Defaults to - add; pass ?action=remove to unpin. + description: Patches one pinned item at a time on a share. Defaults to add; + pass ?action=remove to unpin. parameters: - description: Share hash in: query @@ -5630,7 +5770,7 @@ paths: name: body required: true schema: - $ref: '#/definitions/http.sharePinnedItemPatchRequest' + $ref: '#/definitions/web.sharePinnedItemPatchRequest' produces: - application/json responses: @@ -5649,7 +5789,7 @@ paths: type: string type: object "404": - description: Share not found + description: Not Found schema: additionalProperties: type: string @@ -5662,5 +5802,5 @@ paths: type: object summary: Add or remove a pinned item on a share tags: - - Shares + - Share swagger: "2.0" diff --git a/backend/test-database b/backend/test-database new file mode 100644 index 0000000000..565a427be8 Binary files /dev/null and b/backend/test-database differ diff --git a/frontend/eslint.config.js b/frontend/eslint.config.js index 8f28d996a1..c930490819 100644 --- a/frontend/eslint.config.js +++ b/frontend/eslint.config.js @@ -13,7 +13,6 @@ export default defineConfig( "**/dist/**", "**/node_modules/**", "**/public/**", - "**/*.json", ], }, diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 1c4b7bc94e..c76e7191de 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -11,6 +11,7 @@ "@onlyoffice/document-editor-vue": "^1.4.0", "ace-builds": "^1.24.2", "axios": "^1.13.5", + "chart.js": "^4.5.1", "css-vars-ponyfill": "^2.4.3", "dompurify": "^3.2.4", "epubjs": "^0.3.93", @@ -49,7 +50,8 @@ "vite-plugin-compression2": "^1.0.0", "vitest": "^4.1.8", "vue-eslint-parser": "^10.4.0", - "vue-tsc": "^2.0.7" + "vue-tsc": "^2.0.7", + "wawoff2": "^2.0.1" }, "engines": { "node": ">=20.0.0", @@ -104,12 +106,12 @@ } }, "node_modules/@babel/parser": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz", - "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==", + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz", + "integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==", "license": "MIT", "dependencies": { - "@babel/types": "^7.29.7" + "@babel/types": "^7.29.8" }, "bin": { "parser": "bin/babel-parser.js" @@ -129,9 +131,9 @@ } }, "node_modules/@babel/types": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz", - "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==", + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", + "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", "license": "MIT", "dependencies": { "@babel/helper-string-parser": "^7.29.7", @@ -1366,6 +1368,12 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@kurkle/color": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz", + "integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==", + "license": "MIT" + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -2501,13 +2509,13 @@ } }, "node_modules/adm-zip": { - "version": "0.5.18", - "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.18.tgz", - "integrity": "sha512-ufJnssQGbxzLNS1Ho9bCtX4rQKCCvoVuDLHoJyc3F9dOGDB4BkWs2Ci0kv53lqocAEQ/Cbi+I2XCsNYGqVYqng==", + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.6.0.tgz", + "integrity": "sha512-XleryMhbuksdKtofnWZ9Sk+4CUTbms4Mb/EU32SZwToAyZ5RgVos/ki8n+yr0LWHOGKuakbXTuuYNHLQjhddgg==", "dev": true, "license": "MIT", "engines": { - "node": ">=12.0" + "node": ">=14.0" } }, "node_modules/agent-base": { @@ -2713,6 +2721,18 @@ "node": ">=18" } }, + "node_modules/chart.js": { + "version": "4.5.1", + "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz", + "integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==", + "license": "MIT", + "dependencies": { + "@kurkle/color": "^0.3.0" + }, + "engines": { + "pnpm": ">=8" + } + }, "node_modules/chokidar": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", @@ -4162,9 +4182,9 @@ "license": "MIT" }, "node_modules/js-yaml": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz", - "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz", + "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==", "dev": true, "funding": [ { @@ -6157,6 +6177,20 @@ "node": ">=18" } }, + "node_modules/wawoff2": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/wawoff2/-/wawoff2-2.0.1.tgz", + "integrity": "sha512-r0CEmvpH63r4T15ebFqeOjGqU4+EgTx4I510NtK35EMciSdcTxCw3Byy3JnBonz7iyIFZ0AbVo0bbFpEVuhCYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "woff2_compress.js": "bin/woff2_compress.js", + "woff2_decompress.js": "bin/woff2_decompress.js" + } + }, "node_modules/webidl-conversions": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index 1d04f8533d..2391e56526 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -8,9 +8,9 @@ "node": ">=20.0.0" }, "scripts": { - "build": "rm -rf ../backend/http/dist/* && rm -rf ../backend/http/embed/* && vite build --outDir ../backend/http/dist && cp -r ../backend/http/dist/* ../backend/http/embed", + "build": "rm -rf ../backend/internal/web/embed/* && vite build && cp -r ../backend/internal/web/dist/* ../backend/internal/web/embed", "build:docker": "vite build", - "watch": "vite build --watch --outDir ../backend/http/dist", + "watch": "vite build --watch", "typecheck": "vue-tsc -p ./tsconfig.json --noEmit", "lint": "eslint --ext .js,.vue,.ts src/", "lint:fix": "eslint --fix --ext .js,.vue,.ts src/", @@ -18,6 +18,8 @@ "i18n:check": "node ./scripts/sync-translations.js --check", "i18n:enforce-order": "node scripts/sync-translations.js --enforce-order", "i18n:cleanup": "node scripts/sync-translations.js --cleanup", + "icons:sync": "node ./scripts/build-icon-subset.js", + "icons:check": "node ./scripts/build-icon-subset.js --check", "format": "biome format --write .", "test": "vitest run " }, @@ -25,6 +27,7 @@ "@onlyoffice/document-editor-vue": "^1.4.0", "ace-builds": "^1.24.2", "axios": "^1.13.5", + "chart.js": "^4.5.1", "css-vars-ponyfill": "^2.4.3", "dompurify": "^3.2.4", "epubjs": "^0.3.93", @@ -43,7 +46,8 @@ }, "overrides": { "minimatch": "^10.2.1", - "@xmldom/xmldom": "^0.8.12" + "@xmldom/xmldom": "^0.8.12", + "adm-zip": "^0.6.0" }, "devDependencies": { "@eslint/js": "^10.0.1", @@ -67,6 +71,7 @@ "vite-plugin-compression2": "^1.0.0", "vitest": "^4.1.8", "vue-eslint-parser": "^10.4.0", - "vue-tsc": "^2.0.7" + "vue-tsc": "^2.0.7", + "wawoff2": "^2.0.1" } } diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index 6df7013187..2dbe97eaf2 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -10,16 +10,17 @@ import { defineConfig, devices } from "@playwright/test"; * See https://playwright.dev/docs/test-configuration. */ export default defineConfig({ - globalSetup: "./tests/playwright/screenshots-setup.ts", + globalSetup: "./tests/playwright/global-setup", timeout: 5000, - testDir: "./tests/playwright/screenshots", + testDir: "./tests/playwright/settings", /* Run tests in files in parallel */ fullyParallel: false, /* Fail the build on CI if you accidentally left test.only in the source code. */ forbidOnly: false, /* Retry on CI only */ - retries: 2, + retries: 1, /* Opt out of parallel tests on CI. */ + workers: 1, /* Reporter to use. See https://playwright.dev/docs/test-reporters */ reporter: "line", /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ @@ -27,7 +28,7 @@ export default defineConfig({ actionTimeout: 5000, storageState: "loginAuth.json", /* Base URL to use in actions like `await page.goto('/')`. */ - baseURL: "http://localhost:8080", + baseURL: "http://127.0.0.1/", /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ trace: "on-first-retry", diff --git a/frontend/public/config.generated.yaml b/frontend/public/config.generated.yaml index 65d6faa5ce..d28aa0b0e8 100644 --- a/frontend/public/config.generated.yaml +++ b/frontend/public/config.generated.yaml @@ -2,15 +2,9 @@ server: minSearchLength: 3 # minimum length of search query to begin searching (default: 3) disableUpdateCheck: false # disables backend update check service numImageProcessors: 4 # number of concurrent image processing jobs used to create previews, default is 4. - socket: "" # socket to listen on - eg. /var/run/filebrowser.sock - tlsKey: "" # path to TLS key - tlsCert: "" # path to TLS cert disablePreviews: false # disable all previews thumbnails, simple icons will be used disablePreviewResize: false # disable resizing of previews for faster loading over slow connections disableTypeDetectionByHeader: false # disable type detection by header, useful if filesystem is slow. - port: 80 # port to listen on - listen: "" # address to listen on (default: 0.0.0.0) - baseURL: "/" # base URL for the server, the subpath that the server is running on. logging: - levels: "" # separated list of log levels to enable. (eg. "info|warning|error|debug") apiLevels: "" # separated list of log levels to enable for the API. (eg. "info|warning|error") @@ -19,7 +13,6 @@ server: json: false # output in json format utc: false # use UTC time in the output instead of local time. apiFilter: "" # regex filter that excludes matching full api paths from being logged. (eg. '/user\?id\=self') Defaults to '^/health|^/favicon.ico|^/static|^/public/static' - database: "database.db" # path to the database file sources: # validate:required,dive - path: "/relative/or/absolute/path" # file system path. (Can be relative) validate:required name: "Source Name" # display name @@ -47,8 +40,13 @@ server: defaultEnabled: true # should be added as a default source for new users? createUserDir: false # create a user directory for each user under defaultUserScope + username useLogicalSize: false # calculate sizes based on logical size instead of disk utilization (du -sh), folders will be 0 bytes when empty. - externalUrl: "" # used by share links if set (eg. http://mydomain.com) - internalUrl: "" # used by integrations if set, this is the base domain that an integration service will use to communicate with filebrowser (eg. http://localhost:8080) + defaultPermissions: # DefaultPermissions is the template for new user scopes on this source (also synced globally via Access settings). + view: false + download: false + modify: false + delete: false + create: false + configured: false # true when explicitly set (allows intentional deny-all) cacheDir: "tmp" # path to the cache directory, used for thumbnails and other cached files cacheDirCleanup: false # whether to automatically cleanup the cache directory. Note: docker must also mount a persistent volume to persist the cache (default: false) maxArchiveSize: 20 # maximum archive/unarchive size in GB. 0 means no limit. (default: 20) @@ -61,7 +59,14 @@ server: walMode: false # enable the more complex WAL journaling mode. Slower, more memory usage, but better for deployments with constant user activity. disableReuse: false # enable to always create a new indexing database on startup. startupIntegrityCheck: "quickCheck" # the method used to check the integrity of the index database on startup (default: quickCheck) validate:omitempty,oneof=quickCheck probe off - disableWebDAV: false # disable webdav support (default: false) + database: # SQLite database configuration + path: "filebrowser.sqlite" # path to SQLite database file + migrateFrom: "" # path to legacy database file for migration (optional) + activity: # activity audit logging configuration + disabled: false # disable semantic activity audit logging (default: false) + retentionDays: 30 # purge activity rows older than this many days (default 30) + flushIntervalSeconds: 10 # buffer flush interval in seconds (default 10) + maxBufferSize: 10000 # max in-memory buffer before immediate flush (default 10000) auth: tokenExpirationHours: 2 # time in hours each web UI session token is valid for. Default is 2 hours. methods: @@ -159,8 +164,8 @@ frontend: loginIcon: "" # path to an image file for the login page icon loginButtonText: "" # text to display on the login button oidcLoginButtonText: "" # text to display on the OIDC login button -userDefaults: - sidebar: # New organized structure +userDefaults: # optional signup/CLI defaults; per-user values are managed in the UI + sidebar: disableQuickToggles: false # disable the quick toggles in the sidebar hideFileActions: false # hide the file actions in the sidebar disableHideOnPreview: false # keep sidebar open when previewing files (was preview.disableHideSidebar) @@ -197,7 +202,6 @@ userDefaults: disableOnlyOfficeExt: ".md .txt .pdf .html .xml" # list of file extensions to disable onlyoffice editor for preferEditorForMarkdown: false # prefer editor first for markdown files instead of the Markdown Viewer debugOffice: false # debug onlyoffice editor - defaultMediaPlayer: false # disable the styled feature-rich media player for browser default search: disableOptions: false # disable the search options in the search bar ui: @@ -214,12 +218,8 @@ userDefaults: permissions: api: false # allow api access admin: false # allow admin access - modify: false # allow modifying files share: false # allow sharing files realtime: false # allow realtime updates - delete: false # allow deleting files - create: false # allow creating or uploading files - download: true # allow downloading files lockPassword: false # disable the user from changing their password disableSettings: false # disable the user from viewing the settings page loginMethod: "password" # login method to use: eg. password, proxy, oidc @@ -257,7 +257,16 @@ integrations: wmv: true debug: false # output ffmpeg stdout for media integration -- careful can produces lots of output! extractEmbeddedSubtitles: false # extract embedded subtitles from media files - exiftoolPath: "" # path to exiftool executable + hardwareAcceleration: false # enable hardware acceleration for ffmpeg if available http: - trustedHeaders: # list of headers to trust, useful when behind a reverse proxy. + socket: "" # socket to listen on - eg. /var/run/filebrowser.sock + tlsKey: "" # path to TLS key + tlsCert: "" # path to TLS cert + port: 80 # port to listen on + listen: "" # address to listen on (default: 0.0.0.0) + baseURL: "/" # base URL for the server, the subpath that the server is running on. + externalUrl: "" # used by share links if set (eg. http://mydomain.com) + internalUrl: "" # used by integrations if set, this is the base domain that an integration service will use to communicate with filebrowser (eg. http://localhost:8080) + disableWebDAV: false # disable webdav support (default: false) + trustProxyHeaders: false # honor X-Forwarded-* and X-Real-IP from a reverse proxy (default: false) disableRateLimit: false # turns off built-in auth route rate limiting and failed-login lockout (default false). diff --git a/frontend/public/fonts/material-symbols-core-filled.woff2 b/frontend/public/fonts/material-symbols-core-filled.woff2 new file mode 100644 index 0000000000..52362c3478 Binary files /dev/null and b/frontend/public/fonts/material-symbols-core-filled.woff2 differ diff --git a/frontend/public/index.html b/frontend/public/index.html index e6087d618f..abb2d502f9 100644 --- a/frontend/public/index.html +++ b/frontend/public/index.html @@ -13,7 +13,7 @@ - + diff --git a/frontend/scripts/build-icon-subset.js b/frontend/scripts/build-icon-subset.js new file mode 100644 index 0000000000..53430da2b7 --- /dev/null +++ b/frontend/scripts/build-icon-subset.js @@ -0,0 +1,267 @@ +// scripts/build-icon-subset.js +import fs from 'fs-extra'; +import { sync } from 'glob'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import wawoff2 from 'wawoff2'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const frontendRoot = path.resolve(__dirname, '..'); +const srcDir = path.join(frontendRoot, 'src'); +const inventoryPath = path.join(srcDir, 'utils/icon-inventory-core.json'); +const coreFontPath = path.join(frontendRoot, 'public/fonts/material-symbols-core-filled.woff2'); + +const args = process.argv.slice(2); +const checkOnly = args.includes('--check') || args.includes('-c'); + +const ICON_NAME = '[a-z][a-z0-9_]*'; +const ICON_NAME_RE = new RegExp(`^${ICON_NAME}$`); + +const ICON_MAP_FILES = [ + 'views/bars/Default.vue', + 'views/files/ListingView.vue', +]; + +/** Icons referenced dynamically (not visible to template scan). */ +const EXTRA_ICONS = [ + 'arrow_downward', + 'arrow_upward', + 'autorenew', + 'build', + 'check', + 'cloud_off', + 'copy_all', + 'create_new_folder', + 'do_not_disturb_on', + 'done', + 'error_outline', + 'file', + 'file_copy', + 'forward', + 'forward_10', + 'grid_view', + 'gps_off', + 'insert_drive_file', + 'ios_share', + 'keyboard_arrow_up', + 'lock', + 'lock_open', + 'more_vert', + 'movie', + 'note_add', + 'photo', + 'progress_activity', + 'qr_code', + 'replay_10', + 'repeat', + 'repeat_one', + 'select_all', + 'table_rows_narrow', + 'unarchive', + 'view_list', + 'view_module', + 'volume_up', + 'download', +]; + +function addIcon(icons, value) { + if (typeof value !== 'string') return; + const name = value.trim(); + if (!name || !ICON_NAME_RE.test(name)) return; + icons.add(name); +} + +function scanVueAndTemplates(icons) { + const files = sync(path.join(srcDir, '**/*.vue')); + const materialTag = new RegExp( + `material-symbols(?:-outlined)?[^>]*>\\s*(${ICON_NAME})\\s*<`, + 'g', + ); + const materialInHtml = new RegExp( + `material-symbols(?:-outlined)?[^>]*>(${ICON_NAME})<`, + 'g', + ); + const iconProp = new RegExp(`\\bicon="(${ICON_NAME})"`, 'g'); + const ternaryIcons = new RegExp( + `\\?\\s*["'](${ICON_NAME})["']\\s*:\\s*["'](${ICON_NAME})["']`, + 'g', + ); + + for (const file of files) { + const content = fs.readFileSync(file, 'utf8'); + for (const match of content.matchAll(materialTag)) addIcon(icons, match[1]); + for (const match of content.matchAll(materialInHtml)) addIcon(icons, match[1]); + for (const match of content.matchAll(iconProp)) addIcon(icons, match[1]); + for (const match of content.matchAll(ternaryIcons)) { + addIcon(icons, match[1]); + addIcon(icons, match[2]); + } + } +} + +function scanIconMapLiterals(icons) { + for (const rel of ICON_MAP_FILES) { + const content = fs.readFileSync(path.join(srcDir, rel), 'utf8'); + const block = content.match(/const icons = \{([^}]+)\}/s); + if (!block) continue; + for (const match of block[1].matchAll(/["']([a-z][a-z0-9_]*)["']/g)) { + addIcon(icons, match[1]); + } + } +} + +function scanMimetype(icons) { + const content = fs.readFileSync(path.join(srcDir, 'utils/mimetype.js'), 'utf8'); + const materialSymbol = new RegExp(`materialSymbol:\\s*["'](${ICON_NAME})["']`, 'g'); + for (const match of content.matchAll(materialSymbol)) addIcon(icons, match[1]); +} + +function scanConstants(icons) { + const content = fs.readFileSync(path.join(srcDir, 'utils/constants.js'), 'utf8'); + const iconField = new RegExp(`\\bicon:\\s*["'](${ICON_NAME})["']`, 'g'); + for (const match of content.matchAll(iconField)) addIcon(icons, match[1]); +} + +function scanPlaybackQueue(icons) { + const content = fs.readFileSync(path.join(srcDir, 'utils/playbackQueue.js'), 'utf8'); + const switchReturn = new RegExp(`return\\s+['"](${ICON_NAME})['"]`, 'g'); + for (const match of content.matchAll(switchReturn)) addIcon(icons, match[1]); +} + +function scanErrors(icons) { + const content = fs.readFileSync(path.join(srcDir, 'views/Errors.vue'), 'utf8'); + const errorIcon = new RegExp(`\\bicon:\\s*["'](${ICON_NAME})["']`, 'g'); + for (const match of content.matchAll(errorIcon)) addIcon(icons, match[1]); +} + +function scanSearchFilters(icons) { + const content = fs.readFileSync(path.join(srcDir, 'components/Search.vue'), 'utf8'); + const filterIcon = new RegExp(`\\bicon:\\s*["'](${ICON_NAME})["']`, 'g'); + for (const match of content.matchAll(filterIcon)) addIcon(icons, match[1]); +} + +function scanMarkdownViewer(icons) { + const content = fs.readFileSync(path.join(srcDir, 'views/files/MarkdownViewer.vue'), 'utf8'); + const materialInHtml = new RegExp( + `material-symbols(?:-outlined)?[^>]*>(${ICON_NAME})<`, + 'g', + ); + for (const match of content.matchAll(materialInHtml)) addIcon(icons, match[1]); +} + +function collectIcons() { + const icons = new Set(EXTRA_ICONS); + scanVueAndTemplates(icons); + scanIconMapLiterals(icons); + scanMimetype(icons); + scanConstants(icons); + scanPlaybackQueue(icons); + scanErrors(icons); + scanSearchFilters(icons); + scanMarkdownViewer(icons); + icons.delete('close_back'); + return [...icons].sort(); +} + +function readInventory() { + if (!fs.existsSync(inventoryPath)) return null; + return fs.readJsonSync(inventoryPath); +} + +function writeInventory(icons) { + fs.writeJsonSync(inventoryPath, icons, { spaces: 2 }); +} + +function inventoriesMatch(a, b) { + if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false; + return a.every((icon, index) => icon === b[index]); +} + +function coreFontExists() { + return fs.existsSync(coreFontPath); +} + +async function fetchGoogleSubsetCss(iconNames) { + const family = 'Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,1,0'; + const iconNamesParam = iconNames.join(','); + const url = `https://fonts.googleapis.com/css2?family=${family}&icon_names=${iconNamesParam}`; + const response = await fetch(url, { + headers: { 'User-Agent': 'Mozilla/5.0 (compatible; filebrowser-icon-build/1.0)' }, + }); + if (!response.ok) { + throw new Error(`Google Fonts API returned ${response.status} for core filled subset`); + } + return response.text(); +} + +function extractFontUrl(css) { + const match = css.match(/src:\s*url\(([^)]+)\)\s*format\('truetype'\)/); + if (!match) { + throw new Error('Could not find font URL in Google Fonts CSS response'); + } + return match[1]; +} + +async function downloadTtf(url) { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`Failed to download subset font (${response.status})`); + } + return Buffer.from(await response.arrayBuffer()); +} + +async function convertTtfToWoff2(ttfBuffer, outputPath) { + const woff2Buffer = await wawoff2.compress(ttfBuffer); + fs.writeFileSync(outputPath, woff2Buffer); +} + +async function buildCoreFont(icons) { + const css = await fetchGoogleSubsetCss(icons); + const fontUrl = extractFontUrl(css); + const ttfBuffer = await downloadTtf(fontUrl); + await convertTtfToWoff2(ttfBuffer, coreFontPath); +} + +async function main() { + const icons = collectIcons(); + const existing = readInventory(); + + if (checkOnly) { + if (!existing) { + console.error('❌ Missing icon-inventory-core.json. Run: make sync-icons'); + process.exit(1); + } + if (!coreFontExists()) { + console.error('❌ Missing material-symbols-core-filled.woff2. Run: make sync-icons'); + process.exit(1); + } + if (!inventoriesMatch(existing, icons)) { + const existingSet = new Set(existing); + const missing = icons.filter((icon) => !existingSet.has(icon)); + const extra = existing.filter((icon) => !new Set(icons).has(icon)); + console.error('❌ Core icon inventory is out of date. Run: make sync-icons'); + if (missing.length) console.error(` Missing from inventory (${missing.length}): ${missing.join(', ')}`); + if (extra.length) console.error(` Stale in inventory (${extra.length}): ${extra.join(', ')}`); + process.exit(1); + } + console.log(`✅ Core icon inventory up to date (${icons.length} icons).`); + process.exit(0); + } + + if (existing && inventoriesMatch(existing, icons) && coreFontExists()) { + const coreKb = Math.round(fs.statSync(coreFontPath).size / 1024); + console.log(`✅ Core icon inventory unchanged (${icons.length} icons, ${coreKb} KB font)`); + return; + } + + writeInventory(icons); + await buildCoreFont(icons); + const coreKb = Math.round(fs.statSync(coreFontPath).size / 1024); + console.log(`✅ Generated ${icons.length} core icons → filled ${coreKb} KB`); +} + +main().catch((error) => { + console.error('❌ Icon subset build failed:', error); + process.exit(1); +}); diff --git a/frontend/scripts/sync-translations.js b/frontend/scripts/sync-translations.js index 15e19555bb..a8ffba7287 100644 --- a/frontend/scripts/sync-translations.js +++ b/frontend/scripts/sync-translations.js @@ -2,9 +2,9 @@ // scripts/sync-translations.js import path from 'node:path'; import { fileURLToPath } from 'node:url'; -import * as deepl from 'deepl-node'; +import { Translator } from 'deepl-node'; import fs from 'fs-extra'; -import * as glob from 'glob'; +import { sync } from 'glob'; // Parse command line arguments const args = process.argv.slice(2); @@ -18,9 +18,8 @@ const __dirname = path.dirname(__filename); const localesDir = path.resolve(__dirname, '../src/i18n'); const masterLocaleFile = path.join(localesDir, 'en.json'); const masterLanguageCode = 'en'; -const targetLocaleFiles = glob.sync(path.join(localesDir, '*.json')) +const targetLocaleFiles = sync(path.join(localesDir, '*.json')) .filter(file => path.basename(file) !== `${masterLanguageCode}.json`) - .filter(file => path.basename(file) !== 'is.json'); // Exclude Icelandic - DeepL doesn't support it const requireApiKey = !checkOnly && !enforceOrder && !cleanupOnly; const DEEPL_API_KEY = process.env.DEEPL_API_KEY; @@ -29,7 +28,7 @@ if (requireApiKey && !DEEPL_API_KEY) { process.exit(1); } -const translator = requireApiKey ? new deepl.Translator(DEEPL_API_KEY) : null; +const translator = requireApiKey ? new Translator(DEEPL_API_KEY) : null; const deeplLangMap = { 'zh-cn': 'ZH-HANS', @@ -42,8 +41,8 @@ const deeplLangMap = { 'sv-se': 'SV', 'ua': 'UK', 'nl-be': 'NL', - 'is': 'IS', 'cz': 'CS', + 'bg': 'BG', // Add more as needed }; diff --git a/frontend/src/App.vue b/frontend/src/App.vue index b8815ac119..3033a82426 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -5,19 +5,29 @@ diff --git a/frontend/src/components/MenuOptionList.vue b/frontend/src/components/MenuOptionList.vue new file mode 100644 index 0000000000..909ba2a541 --- /dev/null +++ b/frontend/src/components/MenuOptionList.vue @@ -0,0 +1,193 @@ + + + + + + + diff --git a/frontend/src/components/Notifications.vue b/frontend/src/components/Notifications.vue index b4777a4cda..46c2e92e4e 100644 --- a/frontend/src/components/Notifications.vue +++ b/frontend/src/components/Notifications.vue @@ -4,9 +4,15 @@
close @@ -54,15 +60,42 @@ import { notify } from "@/notify"; export default { name: "notifications", data: () => ({ - notifications: [] + notifications: [], + swipe: new Map(), + swipeDistance: 180, // in px + pause: new Map(), + selectionId: null }), + computed: { + swipeCommitDistance() { + return this.swipeDistance / 15; + } + }, mounted() { // Initialize notifications this.notifications = notify.getNotifications(); // Register callback to receive notification updates notify.setUpdateCallback((notifications) => { this.notifications = notifications; + const activeIds = new Set(notifications.map(n => n.id)); + for (const id of this.pause.keys()) { + if (!activeIds.has(id)) this.pause.delete(id); + } + for (const id of this.swipe.keys()) { + if (!activeIds.has(id)) this.swipe.delete(id); + } + if (this.selectionId && !activeIds.has(this.selectionId)) { + this.selectionId = null; + } }); + window.addEventListener('pointerup', this.handleWindowPointerEnd); + window.addEventListener('pointercancel', this.handleWindowPointerEnd); + document.addEventListener('selectionchange', this.handleSelectionChange); + }, + beforeUnmount() { + window.removeEventListener('pointerup', this.handleWindowPointerEnd); + window.removeEventListener('pointercancel', this.handleWindowPointerEnd); + document.removeEventListener('selectionchange', this.handleSelectionChange); }, methods: { closeNotification(notificationId) { @@ -82,6 +115,134 @@ export default { }, resumeAutoClose(notificationId) { notify.resumeAutoClose(notificationId); + }, + // Notifications timer can be paused by hover, text selection and in-progress swipe + pauseTimer(notificationId, reason) { + if (!notificationId) return; + if (!this.pause.has(notificationId)) { + this.pause.set(notificationId, new Set()); + } + this.pause.get(notificationId).add(reason); + this.pauseAutoClose(notificationId); + }, + resumeTimer(notificationId, reason) { + if (!notificationId) return; + const reasons = this.pause.get(notificationId); + if (!reasons) return; + reasons.delete(reason); + if (reasons.size === 0) { + this.pause.delete(notificationId); + this.resumeAutoClose(notificationId); + } + }, + handleSelectionChange() { + const selection = window.getSelection(); + const hasText = !!selection && selection.toString().length > 0; + let activeId = null; + + if (hasText && selection.anchorNode) { + const anchorEl = selection.anchorNode.nodeType === Node.TEXT_NODE + ? selection.anchorNode.parentElement + : selection.anchorNode; + activeId = anchorEl?.closest?.('.notification-item')?.dataset.notificationId || null; + } + if (activeId === this.selectionId) return; + if (this.selectionId) this.resumeTimer(this.selectionId, 'selection'); + if (activeId) this.pauseTimer(activeId, 'selection'); + this.selectionId = activeId; + }, + // A swipe only commits if there's no active text selection and the swipe is (obviously) horizontal. + isSwiping(notificationId) { + return !!this.swipe.get(notificationId)?.dragging; + }, + swipeStyle(notificationId) { + const swipeState = this.swipe.get(notificationId); + if (!swipeState || (!swipeState.dragging && !swipeState.deltaX)) return {}; + const distance = Math.abs(swipeState.deltaX); + const fade = Math.max(0, 1 - distance / (swipeState.width || 240)); + return { + transform: `translateX(${swipeState.deltaX}px)`, + opacity: fade + }; + }, + onPointerDown(event, notificationId) { + if (event.button !== undefined && event.button !== 0) return; + this.swipe.set(notificationId, { + element: event.currentTarget, + startX: event.clientX, + startY: event.clientY, + deltaX: 0, + dragging: false, + rejected: false, + width: event.currentTarget.offsetWidth || 240, + pointerId: event.pointerId + }); + }, + onPointerMove(event, notificationId) { + const swipeState = this.swipe.get(notificationId); + if (!swipeState || swipeState.rejected) return; + + const deltaX = event.clientX - swipeState.startX; + const deltaY = event.clientY - swipeState.startY; + + if (!swipeState.dragging) { + // If the browser has already started highlighting text let it continue + const hasSelection = (window.getSelection?.()?.toString() || '').length > 0; + if (hasSelection) { + swipeState.rejected = true; + this.swipe.set(notificationId, swipeState); + return; + } + const isHorizontal = Math.abs(deltaX) > Math.abs(deltaY) * 1.2; + if (isHorizontal && Math.abs(deltaX) > this.swipeCommitDistance) { + swipeState.element.setPointerCapture?.(swipeState.pointerId); + this.pauseTimer(notificationId, 'swipe'); + swipeState.dragging = true; + } else if (!isHorizontal && Math.abs(deltaY) > this.swipeCommitDistance) { + swipeState.rejected = true; + this.swipe.set(notificationId, swipeState); + return; + } + } + if (swipeState.dragging) { + event.preventDefault(); + swipeState.deltaX = deltaX; + } + this.swipe.set(notificationId, swipeState); + }, + onPointerUp(_event, notificationId) { + const swipeState = this.swipe.get(notificationId); + if (!swipeState || swipeState.closing) return; + if (!swipeState.dragging) { + this.swipe.delete(notificationId); + return; + } + swipeState.element.releasePointerCapture?.(swipeState.pointerId); + const threshold = Math.max(this.swipeDistance, swipeState.width * 0.55); + if (Math.abs(swipeState.deltaX) > threshold) { + const direction = swipeState.deltaX > 0 ? 1 : -1; + swipeState.dragging = false; + swipeState.closing = true; + swipeState.deltaX = direction * swipeState.width * 1.2; + this.swipe.set(notificationId, swipeState); + this.pause.delete(notificationId); + this.closeNotification(notificationId); + setTimeout(() => { + this.swipe.delete(notificationId); + }, 250); + } else { + swipeState.dragging = false; + swipeState.deltaX = 0; + this.swipe.set(notificationId, swipeState); + this.resumeTimer(notificationId, 'swipe'); + } + }, + handleWindowPointerEnd(event) { + for (const [notificationId, swipeState] of this.swipe) { + if (swipeState.pointerId === event.pointerId) { + this.onPointerUp(event, notificationId); + } + } } }, }; @@ -105,7 +266,6 @@ export default { } .notification-item { - border-radius: 1em; color: #fff; position: relative; max-width: 90vw; @@ -115,11 +275,17 @@ export default { display: flex; padding: 0.5em; align-items: center; - transition: right 1s ease; + transition: right 1s ease, transform 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.35s ease; z-index: 21; pointer-events: all; user-select: text; overflow: hidden; + touch-action: pan-y; +} + +.notification-item.swiping { + transition: none; + cursor: grabbing; } /* selection color for better visibility (since the selection color is the same as --primaryColor) */ diff --git a/frontend/src/components/Search.vue b/frontend/src/components/Search.vue index 045f533815..1e7d9e2fb0 100644 --- a/frontend/src/components/Search.vue +++ b/frontend/src/components/Search.vue @@ -16,13 +16,17 @@
- +
{{ $t("search.searchContext", { context: getContext }) }}
@@ -39,19 +43,24 @@ @toggle="advancedOptionsExpanded = $event" >
- - +
+ + +

{{ $t("search.smallerThan") }}

@@ -140,6 +149,7 @@ import { resourcesApi, toolsApi } from "@/api"; import Icon from "@/components/files/Icon.vue"; import LoadingSpinner from "@/components/LoadingSpinner.vue"; import SettingsItem from "@/components/settings/SettingsItem.vue"; +import ExpandDropdown from "@/components/settings/ExpandDropdown.vue"; import ToggleSwitch from "@/components/settings/ToggleSwitch.vue"; import router from "@/router"; import { getters, mutations, state } from "@/store"; @@ -147,7 +157,6 @@ import { url } from "@/utils/"; import { globalVars } from "@/utils/constants"; import { getHumanReadableFilesize } from "@/utils/filesizes"; import { utcStartOfDaySecondsFromDateInput } from "@/utils/moment"; -import ButtonGroup from "./ButtonGroup.vue"; const boxes = { folder: { label: "folders", icon: "folder" }, @@ -161,11 +170,11 @@ const boxes = { export default { components: { - ButtonGroup, Icon, ToggleSwitch, SettingsItem, LoadingSpinner, + ExpandDropdown, }, name: "search", data: function () { @@ -175,22 +184,11 @@ export default { modifiedOlderThan: "", modifiedNewerThan: "", noneMessage: this.$t("search.typeToSearch", { minSearchLength: globalVars.minSearchLength }), - searchTypes: "", - isTypeSelectDisabled: false, + entryTypeFilter: "all", + selectedMediaTypes: [], showPreviewImages: false, useWildcardSearch: false, caseExactSearch: false, - folderSelect: [ - { label: this.$t("search.onlyFolders"), value: "type:folder" }, - { label: this.$t("search.onlyFiles"), value: "type:file" }, - ], - typeSelect: [ - { label: this.$t("general.photos"), value: "type:image" }, - { label: this.$t("general.audio"), value: "type:audio" }, - { label: this.$t("general.videos"), value: "type:video" }, - { label: this.$t("general.documents"), value: "type:doc" }, - { label: this.$t("general.archives"), value: "type:archive" }, - ], value: "", ongoing: 0, results: [], @@ -222,9 +220,19 @@ export default { caseExactSearch() { this.submit(); }, - searchTypes() { + entryTypeFilter(newValue) { + if (newValue === "type:folder" && this.selectedMediaTypes.length > 0) { + this.selectedMediaTypes = []; + return; + } this.submit(); }, + selectedMediaTypes: { + deep: true, + handler() { + this.submit(); + }, + }, value() { if (this.results.length) { this.ongoing = 0; @@ -294,7 +302,31 @@ export default { return state.user?.disableSearchOptions; }, foldersOnly() { - return this.isTypeSelectDisabled; + return this.entryTypeFilter === "type:folder"; + }, + searchTypes() { + const parts = []; + if (this.entryTypeFilter !== "all") { + parts.push(this.entryTypeFilter); + } + parts.push(...this.selectedMediaTypes); + return parts.length > 0 ? `${parts.join(" ")} ` : ""; + }, + entryTypeOptions() { + return [ + { value: "all", label: this.$t("search.filesAndFolders") }, + { value: "type:file", label: this.$t("search.onlyFiles") }, + { value: "type:folder", label: this.$t("search.onlyFolders") }, + ]; + }, + mediaTypeOptions() { + return [ + { value: "type:image", label: this.$t("general.photos") }, + { value: "type:audio", label: this.$t("general.audio") }, + { value: "type:video", label: this.$t("general.videos") }, + { value: "type:doc", label: this.$t("general.documents") }, + { value: "type:archive", label: this.$t("general.archives") }, + ]; }, active() { return state.isSearchActive; @@ -342,6 +374,16 @@ export default { multipleSources() { return Object.keys(state.sources.info).length > 1; }, + searchSourceOptions() { + const sources = Object.keys(this.sourceInfo).map((name) => ({ + value: name, + label: name, + })); + return [ + { value: "__all__", label: this.$t("general.all") }, + ...sources, + ]; + }, isSearchingMultipleSources() { return this.selectedSource === "__all__" || (this.selectedSource === "" && this.multipleSources); }, @@ -411,8 +453,8 @@ export default { this.cancelContext(); // Clear timeout this.isSwipe = false; // Reset swipe state }, - updateSource(event) { - this.selectedSource = event.target.value; + updateSource(value) { + this.selectedSource = value; void this.submit(); }, getItemUrl(s) { @@ -460,35 +502,12 @@ export default { return; } }, - addToTypes(string) { - if (this.searchTypes.includes(string)) { - return true; - } - if (string === null || string === "") { - return false; - } - this.searchTypes = `${this.searchTypes + string} `; - }, resetSearchFilters() { - this.searchTypes = ""; + this.entryTypeFilter = "all"; + this.selectedMediaTypes = []; this.advancedOptionsExpanded = false; this.showPreviewImages = false; }, - removeFromTypes(string) { - if (string === null || string === "") { - return false; - } - this.searchTypes = this.searchTypes.replaceAll(`${string} `, ""); - if (state.isMobile) { - this.$refs.input.focus(); - } - }, - folderSelectClicked() { - this.isTypeSelectDisabled = true; // Disable the other ButtonGroup - }, - resetButtonGroups() { - this.isTypeSelectDisabled = false; - }, async submit(event) { this.results = []; if (event !== undefined) { @@ -553,7 +572,10 @@ export default { } }, showHelpTooltip(event) { - const helpText = `${this.$t("search.helpText1", { minSearchLength: globalVars.minSearchLength })}\n\n${this.$t("search.helpText2")}`; + const helpText = [ + this.$t("search.helpText1", { minSearchLength: globalVars.minSearchLength }), + this.$t("search.helpText2"), + ].join("\n\n"); mutations.showTooltip({ content: helpText, x: event.clientX, @@ -640,7 +662,7 @@ export default { if (this.caseExactSearch) { query.caseExact = "1"; } - if (this.isTypeSelectDisabled) { + if (this.foldersOnly) { query.typeLock = "1"; } @@ -699,24 +721,130 @@ export default { \ No newline at end of file + +.tab-visualizer { + position: relative; + display: flex; + align-items: center; + justify-content: center; + height: 100%; + padding: 0.5em; + box-sizing: border-box; +} + +.visualizer-canvas { + width: 100%; + height: 100%; + border-radius: 0.8em; + background: rgba(0, 0, 0, 0.12); + display: block; +} + diff --git a/frontend/src/components/files/Breadcrumbs.vue b/frontend/src/components/files/Breadcrumbs.vue index a62bcbe9d4..cdbaa6c310 100644 --- a/frontend/src/components/files/Breadcrumbs.vue +++ b/frontend/src/components/files/Breadcrumbs.vue @@ -71,7 +71,7 @@ export default { return state.req.hasUpdate; }, isDroppable() { - return getters.permissions().modify + return getters.sourcePermissions().modify }, homeLink() { return { diff --git a/frontend/src/components/files/ExtendedImage.vue b/frontend/src/components/files/ExtendedImage.vue index be80aec5bf..e87fa26ad1 100644 --- a/frontend/src/components/files/ExtendedImage.vue +++ b/frontend/src/components/files/ExtendedImage.vue @@ -41,6 +41,7 @@ import { getters, mutations, state } from '@/store'; import { globalVars } from "@/utils/constants"; import { getBestCachedImage } from "@/utils/imageCache"; import { isRawImageMimeType } from "@/utils/mimetype"; +import { refreshViewToken, requestViewIdentity } from "@/api/viewToken.js"; import throttle from "@/utils/throttle"; export default { @@ -96,6 +97,7 @@ export default { edgeCommitY: 110, edgeRubberMax: 100, pinchActive: false, + viewTokenRetried: false, }; }, computed: { @@ -117,8 +119,8 @@ export default { } // Don't use thumbnail when we show original embedded preview (HEIC/HEIF or raw) const isHeicOrHeif = state.req?.type === "image/heic" || state.req?.type === "image/heif"; - const useOriginalForHeic = isHeicOrHeif && (state.isSafari || (globalVars.mediaAvailable && globalVars.enableHeicConversion) || globalVars.exiftoolAvailable); - const useOriginalForRaw = isRawImageMimeType(state.req?.type) && globalVars.exiftoolAvailable; + const useOriginalForHeic = isHeicOrHeif && (state.isSafari || (globalVars.mediaAvailable && globalVars.enableHeicConversion)); + const useOriginalForRaw = isRawImageMimeType(state.req?.type); if (useOriginalForHeic || useOriginalForRaw) { return null; } @@ -265,7 +267,25 @@ export default { return; // Let it retry with fixed URL } } + + if (!this.viewTokenRetried && state.req?.source) { + this.viewTokenRetried = true; + const viewIdentity = requestViewIdentity(state.req); + void refreshViewToken(state.req.source, state.req.viewToken) + .then((data) => { + if (requestViewIdentity(state.req) === viewIdentity) { + mutations.setRequestViewToken(data.viewToken); + } + }) + .catch(() => { + this.finishImageError(img); + }); + return; + } + this.finishImageError(img); + }, + finishImageError(img) { this.imageLoaded = true; this.fullImageLoaded = true; mutations.setLoading("preview-img", false); @@ -749,6 +769,7 @@ export default { } // Reset and reload when src changes + this.viewTokenRetried = false; this.fullImageLoaded = false; this.imageLoaded = false; this.isTiff = this.checkIfTiff(newSrc); diff --git a/frontend/src/components/files/FileList.vue b/frontend/src/components/files/FileList.vue index eb628d7ba9..4ed4e5c97e 100644 --- a/frontend/src/components/files/FileList.vue +++ b/frontend/src/components/files/FileList.vue @@ -5,11 +5,12 @@ - +
@@ -58,6 +59,7 @@ import { url } from "@/utils"; import { resourcesApi } from "@/api"; import ListingItem from "@/components/files/ListingItem.vue"; import LoadingSpinner from "@/components/LoadingSpinner.vue"; +import ExpandDropdown from "@/components/settings/ExpandDropdown.vue"; import { sortedItems } from "@/utils/sort.js"; export default { @@ -65,6 +67,7 @@ export default { components: { ListingItem, LoadingSpinner, + ExpandDropdown, }, props: { browseSource: { @@ -150,6 +153,12 @@ export default { // Get all available sources from state.sources.info return state.sources.info ? Object.keys(state.sources.info) : [state.req.source]; }, + sourceOptions() { + return this.availableSources.map((source) => ({ + value: source, + label: source, + })); + }, showSourceSelector() { if (this.hideDestinationSource) { return false; @@ -484,9 +493,6 @@ export default { }, }); }, - onSourceChange() { - this.resetToSource(this.currentSource); - }, /** * Jump listing to a source/path (e.g. after PathPickerButton confirms). * Normalizes to a directory path with trailing slash (except root). diff --git a/frontend/src/components/files/FileTree.vue b/frontend/src/components/files/FileTree.vue index 48a8957c71..764ae62097 100644 --- a/frontend/src/components/files/FileTree.vue +++ b/frontend/src/components/files/FileTree.vue @@ -138,7 +138,7 @@ export default { return this.isRootInstance ? this.rootNodes : this.nodes; }, canModify() { - return getters.permissions().modify; + return getters.sourcePermissions().modify; }, showFiles() { // Defaults to true diff --git a/frontend/src/components/files/Icon.vue b/frontend/src/components/files/Icon.vue index 03252f019d..28ce6ccd36 100644 --- a/frontend/src/components/files/Icon.vue +++ b/frontend/src/components/files/Icon.vue @@ -1,6 +1,6 @@ + + diff --git a/frontend/src/components/prompts/AnalyticsDiagnostic.vue b/frontend/src/components/prompts/AnalyticsDiagnostic.vue new file mode 100644 index 0000000000..729a29d68d --- /dev/null +++ b/frontend/src/components/prompts/AnalyticsDiagnostic.vue @@ -0,0 +1,64 @@ + + + + + diff --git a/frontend/src/components/prompts/Archive.vue b/frontend/src/components/prompts/Archive.vue index 830968f482..c09df1eb27 100644 --- a/frontend/src/components/prompts/Archive.vue +++ b/frontend/src/components/prompts/Archive.vue @@ -32,10 +32,11 @@ :placeholder="defaultArchiveName" />

{{ $t("general.format", { suffix: ":" }) }}

- +

{{ $t("prompts.archiveCompression") }}