diff --git a/.dockerignore b/.dockerignore index 7838254..6826209 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,9 @@ .git .github +.claude +.jj +ref +vendor .vscode build **/build @@ -17,6 +21,16 @@ install-util.sh install.sh LICENSE README.md -docker-compose.yml.example +docker-compose.example.yml +docker-compose.yml +Makefile .project +.classpath +bin/ +test/ .settings/ +.note.xnote +.env +.env.* +**/.env +**/.env.* diff --git a/.gitattributes b/.gitattributes index 93c61a2..922296b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,5 @@ /gradlew text eol=lf *.bat text eol=crlf *.jar binary +src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java linguist-language=SQL diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..3ed2bbd --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,31 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG]: " +labels: [ 'Type: Bug', 'Status: Needs Triage' ] + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Device(s) (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..7e6c25b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,39 @@ +name: Feature Request +description: Suggest an idea for this project +title: "[FEAT]: " +labels: ['Type: Feature', 'Status: Needs Triage'] +body: +- type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please search to see if an open or closed issue already exists for the feature you are requesting. If a request exists and is closed note that it may only be fixed in an unstable branch. + options: + - label: I have searched the existing open and closed issues + required: true +- type: textarea + attributes: + label: Is your feature request related to a problem? Please describe + description: A clear and concise description of what the problem is. + validations: + required: true +- type: textarea + attributes: + label: Describe the solution you'd like + description: A clear and concise description of what you want to happen. + validations: + required: true +- type: textarea + attributes: + label: Describe alternatives you've considered + description: A clear and concise description of any alternative solutions or features you've considered. + validations: + required: true +- type: textarea + attributes: + label: Anything else? + description: | + Links? References? Mockups? Anything that will give us more context about the feature you are encountering! + + Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. + validations: + required: true diff --git a/.github/workflows/integration-dev.yml b/.github/workflows/integration-dev.yml new file mode 100644 index 0000000..f9e7557 --- /dev/null +++ b/.github/workflows/integration-dev.yml @@ -0,0 +1,17 @@ +name: Integration Test Dev Branch with Client + +on: + push: + branches: + - dev + pull_request: + +jobs: + integration-test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: MediaGarrd/MediaGarrd-Stack-Testing@main + with: + server-branch: ${{ github.head_ref || github.ref_name }} + client-branch: main diff --git a/.github/workflows/integration-main.yml b/.github/workflows/integration-main.yml new file mode 100644 index 0000000..d2846e7 --- /dev/null +++ b/.github/workflows/integration-main.yml @@ -0,0 +1,16 @@ +name: Integration Test Main Branch with Client + +on: + push: + branches: + - main + +jobs: + integration-test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: MediaGarrd/MediaGarrd-Stack-Testing@main + with: + server-branch: main + client-branch: main diff --git a/.github/workflows/issue_handling.yml b/.github/workflows/issue_handling.yml new file mode 100644 index 0000000..8458fab --- /dev/null +++ b/.github/workflows/issue_handling.yml @@ -0,0 +1,56 @@ +name: Handle duplicate status label + +on: + issues: + types: [labeled, unlabeled] + +jobs: + correct-status-labels: + runs-on: ubuntu-latest + steps: + - name: Ensure one Status label per issue + uses: actions/github-script@v7 + with: + github-token: ${{ secrets.MEDIAGARRD_SERVER_ACTIONS_TOKEN }} + script: | + const issueNumber = context.payload.issue.number; + const statusLabelsToCheck = [ + "Status: Needs Triage", + "Status: Approved", + "Status: Waiting on Child Issues", + "Status: Waiting on Client Update", + "Status: Waiting on Recovery Update" + ]; + + const existingLabels = context.payload.issue.labels.map(label => label.name); + const existingStatusLabels = existingLabels.filter(label => statusLabelsToCheck.includes(label)); + const addedLabel = context.payload.action === "labeled" ? context.payload.label.name : null; + + let keep = null; + if (statusLabelsToCheck.includes(addedLabel)) { + keep = addedLabel; + } else if (existingStatusLabels.length == 1) { + keep = existingStatusLabels[0]; + } + + for (const label of existingStatusLabels.filter(label => label !== keep)) { + await github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + name: label + }); + console.log(`Removed label "${label}" from issue #${issueNumber}`); + } + + if (keep) { + console.log(`Status label: "${keep}" is set correctly`); + } else { + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + labels: ["Status: Needs Triage"] + }); + } + diff --git a/.github/workflows/pr_handling.yml b/.github/workflows/pr_handling.yml new file mode 100644 index 0000000..fe9016a --- /dev/null +++ b/.github/workflows/pr_handling.yml @@ -0,0 +1,46 @@ +name: Require approved issue + +on: + pull_request: + types: [opened, edited, reopened, synchronize] + +jobs: + require-approved-issue: + if: github.head_ref != 'dev' + runs-on: ubuntu-latest + permissions: + issues: read + pull-requests: read + steps: + - name: Ensure every linked issue is approved + uses: actions/github-script@v7 + with: + script: | + const { repository } = await github.graphql(` + query($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + closingIssuesReferences(first: 25) { + nodes { number labels(first: 25) { nodes { name } } } + } + } + } + }`, { + owner: context.repo.owner, + repo: context.repo.repo, + number: context.payload.pull_request.number + }); + + const issues = repository.pullRequest.closingIssuesReferences.nodes; + if (issues.length === 0) { + core.setFailed("Link the approved issue this pull request resolves, e.g. \"Closes #12\" in the description"); + return; + } + + const unapproved = issues.filter(issue => !issue.labels.nodes.some(label => label.name === "Status: Approved")); + if (unapproved.length > 0) { + core.setFailed(`Linked issues without "Status: Approved": ${unapproved.map(issue => `#${issue.number}`).join(", ")}`); + return; + } + + console.log(`All linked issues are approved: ${issues.map(issue => `#${issue.number}`).join(", ")}`); diff --git a/.gitignore b/.gitignore index 6703b86..be73259 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ .gradle .settings/ build -gradle/ **/.settings/ **/.project **/.classpath @@ -13,9 +12,14 @@ gradle/ .env.* .env.example .env.test.example +vendor/**/*.jar +.factorypath # Prod artifacts secrets/ +dockerenv/ .env data/ docker-compose.yml +ref/structurizr/*.json +ref/structurizr/.structurizr/ diff --git a/CHANGELOG b/CHANGELOG index 140a7e5..479b93e 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,10 +1,123 @@ # CHANGELOG -## TBD -- Adding more detailed logging for service runners -- Renaming QBittorrent's "graveyard" directory to "saved-torrents" to make it less ambiguous +Everything in this file is part of version 0.1.0, the first release. Entries are grouped by the date they were made. + +## 11-24-26 +- Archives are ordered, listed and pruned by the UTC timestamp in their file name (`yyyyMMdd-HHmmss-SSS-media-backup.zip`) instead of the file's last-modified time, so copying or restoring files no longer changes which archive is the newest or gets deleted by retention; `createdAt` in `GET /api/v1/backups` comes from the same timestamp (millisecond precision), and an archive whose name has no valid timestamp still uses its last-modified time +- If the database is found corrupt while the server is running, it is moved aside and replaced as before, and now setup also reopens without a restart: a new Setup PIN is logged, `/config` works again, paired Clients must pair again (they get `401` until then), open event streams are closed and unconfirmed pairings are dropped, and the backup location, retention and schedule go back to the defaults until set again +- The API docs list the `409` answers for `POST /backups/run` (a run is already in progress, or no services are configured), for `PUT /config` and the service endpoints while a backup is running, and for a service name that already exists +- The start page says the `/config` setup page is only available until setup is finished +- `.dockerignore` skips `bin/`, `.classpath` and `test/` + +## 11-22-26 +- Backup run scratch space is now `.mediagarrd-runs/` inside the backup folder instead of `runs/`, and startup cleanup only removes folders in it and `*-media-backup.zip.tmp` files; a `runs/` folder or other `.zip.tmp` files you keep in the backup folder are left alone +- A finished archive is flushed to disk before it is moved into place and the backup folder is flushed after the move, both before retention deletes any older archive, so a power loss cannot leave a truncated newest archive next to an already deleted good one +- The image has a health check against `/api/v1/health` on `SERVER_PORT` (default `8080`) and `.dockerignore` skips `.claude`, `.jj`, `ref`, `vendor` and the compose files +- Restore docs use `sudo` for `mgrecover` and `bsdtar`, because archives belong to root +- The backup interval must be between 15 minutes and 365 days: `PUT /api/v1/schedule` answers `400` for a missing, zero, negative, shorter or longer value and saves nothing; a stored or `MEDIAGARRD_BACKUP_INTERVAL` value outside that range is ignored with a warning (the default is `PT12H`); the setup page limits the hours field to 0.25 to 8760 +- The pair-before-setup `409` now says `This server has not finished setup yet. Finish it on the server's /config page, then pair.` +- Setup page: the Setup PIN error is red and Finish Setup sits under Configured Services +- `POST /api/v1/setup/complete` answers `200` with `{"pairingPin": "NNNNNN"}` instead of an empty `204` (`pairingPin` is `null` when no PIN applies), and the setup page shows the Pairing PIN with a copy button after Finish Setup; it is still printed in the logs +- Pairing is confirmed by the Client's first request with its token: `POST /pair` creates a pending pairing in memory, and only the first authenticated request with that token stores the client and closes PIN pairing or spends the pairing code. A Client whose reply was lost can pair again with the same PIN or code +- A pending pairing expires after 5 minutes, at most 10 are kept, a restart drops them, and they are not listed or counted as paired clients; if several pair with one PIN or code, the first to confirm wins and the others get `401` +- A pairing code that confirms the first stored client also closes PIN pairing; `POST /setup/complete` answers `410` for a second concurrent finish instead of rotating the PIN, and the setup page disables Finish while it is in flight +- Pairing PIN is checked without resetting the wrong-attempt counter until pairing closes +- Older Clients keep working: they store the token without confirming, and their first request with it (within 5 minutes) confirms the pairing. A new Client confirms against any Server straight away +- No database change + +## 11-21-26 +- Added an optional failure webhook: when a backup run fails or only partly succeeds (scheduled or manual), the server posts a message to a URL you set, so a failed scheduled backup (which only retries after the next interval) is noticed. Set it on the setup page, with `PUT /api/v1/notifications/webhook`, or from the Client; `GET` reports only `configured` and `scheme://host`, and `POST /api/v1/notifications/webhook/test` sends a test (one every 10 seconds, `429` with `Retry-After` otherwise) +- The message is a Discord body (with `allowed_mentions` blocking pings), a Slack body, or a generic JSON body with `event`, `time`, `error`, `failedServices`, `archiveId`, `content` and `text`, chosen by host; it is sent in the background with timeouts, no redirects and no retry, and a failed delivery is only a warning that names the host +- The webhook URL is never returned, logged or echoed in an error, and is kept in plain text in the settings database, so it is also inside backup archives +- Fixed scheduled backups never running on a server restarted more often than its backup interval: the next backup is now due one interval after the last completed or partial backup, and an overdue one runs within about 30 seconds of start +- A server with no completed backup runs its first one soon after setup is finished; while setup is still open, and for installs that never finished setup and have no backup yet, it waits one interval from start +- Changing the backup interval counts from the last completed or partial backup instead of from the change +- Fixed the setup page being wider than a phone screen: grid columns, form rows and notes shrink to the screen and the webhook buttons wrap + +## 11-19-26 +- Every error answers `{"error": ""}`, including `404`, `405` and the missing-backup and delete cases that used Spring's default body; a `5xx` says `Internal error`, except a failed `POST /backups/run`, which keeps the run's failure reason in the `500` body for the Client dashboard +- Request bodies over 64 KiB answer `413`, a service may have at most 32 paths of 4096 characters, and a PIN, code or backup location has a length limit +- Responses carry `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, a `default-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'` Content-Security-Policy and `Cache-Control: no-store` (not on the setup page's css and js) +- The setup cookie is `Secure` over HTTPS or `X-Forwarded-Proto: https`, and a setup session expires after 30 minutes without use +- Backup folders and the data folder the server creates are `0700`, archives and the database file `0600`; restore with `sudo` +- Retention deletes only archives the server has a record of; others are kept and listed +- Unpairing the last Client reopens pairing and logs a fresh `Pairing PIN`; opening or closing pairing no longer clears a lockout +- Before setup is finished the `401` message says so +- Fixed a helper container left behind when a stale one was listed after the matching one, and archive ids that dropped every `.zip` in a name +- The setup page keeps the workspace hidden when unlocking fails, shows the lockout wait, labels its path fields and table, shows a visible focus outline and scrolls its table on narrow screens +- Log values from requests have line breaks removed +- After setup, every `/api/v1` endpoint except `GET /health` (reduced), `GET /version`, `GET /setup`, `POST /setup/session` and `POST /pair` needs `Authorization: Bearer `, and anything not on that list is refused by default, including `/events` and backup downloads +- A client gets its token with `POST /api/v1/pair` and the PIN printed in the logs as `Pairing PIN`; the token is returned once, only its SHA-256 hash is stored (new `paired_clients` table), and it is never logged +- When setup is finished the PIN is replaced with a fresh `Pairing PIN`, and it stops working as soon as one client pairs; an install with no paired client (including every install upgraded from an earlier version) prints a `Pairing PIN` on start +- `MEDIAGARRD_OPEN_PAIRING=true` opens pairing with a new PIN on start even when clients are paired, and logs a warning on every start while it is set +- A paired client can create a single-use pairing code valid for 10 minutes (`POST /api/v1/pairing-codes`), list paired clients (`GET /api/v1/clients`), and unpair any client including itself (`DELETE /api/v1/clients/{id}`), which also closes that client's event streams +- Five wrong PINs lock the setup PIN and the pairing PIN together for 10 minutes (`429` with `Retry-After`), and ten wrong pairing codes lock codes separately; the setup PIN had no time lock before +- `GET /api/v1/health` returns only `healthy` and `backupInterval` without a token, the full status with one, and `401` for a token that is not valid +- Setup page endpoints accept the setup session only until setup is finished, and the check no longer depends on the raw URL, so path variants such as `/api/v1/services;x` no longer bypass it +- A request body that is missing or not JSON is answered with `400` and `{"error": "..."}` +- Every response carries `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'`, so the setup page cannot be embedded in another page +- An unexpected failure (HTTP 500) answers with `{"error": "Internal error"}` and keeps the details in the log; a backup run where every service failed still reports its reason +- New `docs/https.md` for running the Server behind nginx or Caddy + +## 11-12-26 +- A run rejected before it starts (such as no services configured) publishes no run events +- A scheduled check with nothing to back up now waits one full interval instead of retrying every 30 seconds, and adding or editing a service makes the schedule due again right away +- `GET /api/v1/events` also sends `backups-changed` (backup deleted, backup location changed) and `config-changed` (schedule, settings, or services changed), each as `{"at":""}` +- `GET /api/v1/health` and `GET /api/v1/backups` are logged at DEBUG, so polling no longer fills the log +- An archive's SHA-256 is now computed while it is written instead of by reading the finished file again, which saves a full pass over every backup +- Archives are compressed at a lighter level by default (`MEDIAGARRD_COMPRESSION_LEVEL`, `0` to `9`, default `1`), and already-compressed files (images, video, audio, zip, gz and similar) are stored as they are +- Backups use a fixed amount of memory regardless of how many files or how much data they hold: archives are written as a stream with an on-disk index, so any backup that fits on disk completes +- The archive writer is our own: zip64 is used automatically for entries over 4 GB, archives over 4 GB, and more than 65,535 entries, and entries now also carry an exact UTC modification time +- Entry owners are always written as a 4-byte uid/gid (`0x7875`), because bsdtar reads only 2- or 4-byte widths and ignored the shorter form, so `bsdtar -xp` now restores small uids such as 33 (www-data) correctly; the NTFS extra (`0x000A`) is no longer written +- A symlink inside a copied path that is also configured as its own path is not stored; the configured path is copied from its real content instead, so restoring that path no longer hits a link-versus-directory conflict and the merge never sees a duplicate name +- A path nested inside another configured path is no longer copied twice: it is skipped when the outer copy includes it, and copied on its own if the outer copy failed, and each service's result reflects its own outcome +- The database snapshot is taken first, and the live database and its `-journal`, `-wal`, and `-shm` files are left out of service copies only when the snapshot succeeded +- The container image is pinned to `eclipse-temurin:21.0.13_9-jre` and starts the JVM with G1, a small starting heap, periodic heap trimming, and `-XX:+ExitOnOutOfMemoryError`; the heap cap follows the container memory (`JAVA_TOOL_OPTIONS`, see `docs/settings.md`), and lazy initialization is no longer used + +## 11-11-26 +- `GET /api/v1/events` is a live Server-Sent Events stream that needs no setup session: `state` on connect, `run-started` and `run-finished` (`COMPLETED`, `PARTIAL`, or `FAILED`) the moment a run begins and ends, and a `ping` every 20 seconds +- At most 16 listeners are served (more get `503`), a slow or dead listener is dropped without slowing a backup, and each stream ends cleanly after 4.5 minutes so clients reconnect without errors in the log +- Fixed a failed delete of a run's temporary directory leaving the server stuck on "running" and rejecting configuration changes until restart +- The server knows its version (`0.1.0`) and checks GitHub for the latest `MediaGarrd/Server` release shortly after starting and then daily +- `GET /api/v1/version` (no setup session needed) reports the current and latest version, whether an update is available, the release link, when the last check ran, and its state (`OK`, `NO_RELEASES`, `ERROR`, or `NOT_CHECKED`) +- A failed check (offline, rate limited, no release yet) is logged once, shown as a state, and never affects backups +- `MEDIAGARRD_UPDATE_REPOSITORY`, `MEDIAGARRD_GITHUB_API_URL`, and `MEDIAGARRD_UPDATE_CHECK_INTERVAL` change the repository, API address, and check interval (at least `PT1H`, or the server refuses to start) +- Scheduled tasks run on two threads (`spring.task.scheduling.pool.size: 2`), so a slow GitHub check cannot delay backups + +## 11-05-26 +- Every archive includes a consistent snapshot of the server's own database (settings, services, backup records) at its absolute host path, so the future recovery tool and `bsdtar -xpf -C /` restore it in place +- The host path is found by inspecting the server's own container. If that or the snapshot fails, the run is partial with the error logged, and a corrupt or missing database is never replaced by an empty one +- Database operations wait while the snapshot is taken, so nothing is written mid-copy +- The snapshot appears as `_mediagarrd-server` in service results and service names, and a service copy of the database file or its `-journal`, `-wal`, and `-shm` files no longer replaces or sits next to it +- Documented how to restore the database from an archive + +## 10-26-26 +- Services are stored in the database and managed from `/config` or `/api/v1/services`, and any service can be backed up +- Backup location can be changed at runtime from `/config` or `PUT /api/v1/config` +- Backup interval and retention count are stored in the database, retention is settable through `PUT /api/v1/config`, and `GET /api/v1/config` returns every setting +- Configuration changes are rejected while a backup is running, so a run never sees its services change +- One runner now copies each service's paths through a cached, read-only helper container via the Docker socket, replacing the per-service runners +- Added first-time web setup reachable from the network, unlocked with a single-use PIN printed in the server logs and disabled once setup is finished +- `docker-compose.example.yml` works without `install.sh` +- Archives are laid out by absolute host path with no per-service folder, so `bsdtar -xpf -C /` restores them +- Archives keep permissions, owners, modification times, symbolic links, and empty directories, and a path that fails to copy leaves no partial files +- Fixed special files (pipes, devices) being archived as empty regular files +- Fixed checksums loading the whole archive into memory and dropping leading zeros, and archive sizes over 2 GB being recorded incorrectly +- Every API endpoint returns errors as `{"error": "..."}` with a matching status code +- The database schema is verified once and then re-checked with one query per call, rebuilding or upgrading the database when it is deleted, altered, or replaced, and moving a corrupt one aside +- Fixed migration versioning +- Added Structurizr diagrams, Lombok for model classes, integration test and issue label workflows, and a pull request check that requires every linked issue to be approved + +## 9-23-26 +- Added a database for backup records, with thorough tests +- Added issue templates +- Removed auto-routing to `appdata/` within archives so configs keep their actual paths + +## 9-16-26 +- More detailed logging for service runners +- Renamed QBittorrent's "graveyard" directory to "saved-torrents" ## 9-6-26 -- Abstracting services to make adding new ones easier -- Adding new tests -- Project renaming +- Abstracted services to make adding new ones easier +- Added new tests +- Renamed the project diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..1a83d1d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,12 @@ +# Contributing to the MediaGarrd Server + +## Submitting Issues +Open an issue [here](https://github.com/MediaGarrd/Server/issues) using the template that best fits the issue. + +The `Status: Needs Triage` label will automatically be applied. Once this issue has been reviewed/approved, the `Status: Approved` label will be added and Pull Requests can be opened referencing this issue. + +## Pull Requests +Pull requests should only be opened for issues that have the `Status: Approved` label. + +## AI Usage +See [AGENTS.md](https://github.com/MediaGarrd/Server/blob/main/AGENTS.md) for a more in-depth overview of the way AI is permitted in code submissions. If a signature is not present on a commit that even *appears* to be generated by an LLM, the PR will be closed. This is strictly for the continued maintainability of the project. diff --git a/Dockerfile b/Dockerfile index c57db07..85ec6f6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,19 +1,25 @@ FROM gradle:9.4.0-jdk21 AS build WORKDIR /workspace COPY . . -RUN --mount=type=cache,target=/home/gradle/.gradle \ - gradle :bootJar --no-daemon +RUN --mount=type=cache,target=/home/gradle/.gradle gradle :bootJar --no-daemon --stacktrace --info --warning-mode all -FROM eclipse-temurin:21-jre +FROM eclipse-temurin:21.0.13_9-jre WORKDIR /app COPY --from=build /workspace/build/libs/*.jar app.jar EXPOSE 8080 +ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=50" + +HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \ + CMD curl -fsS -o /dev/null http://127.0.0.1:${SERVER_PORT:-8080}/api/v1/health + ENTRYPOINT ["java", \ - "-Xms32m", \ - "-XX:+UseZGC", \ - "-XX:+ZUncommit", \ - "-XX:ZUncommitDelay=30", \ - "-XX:+UseContainerSupport", \ - "-Dspring.main.lazy-initialization=true", \ + "-XX:+UseG1GC", \ + "-Xms16m", \ + "-XX:MinHeapFreeRatio=10", \ + "-XX:MaxHeapFreeRatio=30", \ + "-XX:G1PeriodicGCInterval=60000", \ + "-XX:-G1PeriodicGCInvokesConcurrent", \ + "-XX:TrimNativeHeapInterval=10000", \ + "-XX:+ExitOnOutOfMemoryError", \ "-jar", "/app/app.jar"] diff --git a/LICENSE b/LICENSE index f288702..ba28e3b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,21 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. +MIT License + +Copyright (c) 2026 Jackson Swindell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..7d6fe79 --- /dev/null +++ b/Makefile @@ -0,0 +1,16 @@ +.PHONY: test lint-test full-test + +JF=./gradlew +JF_ARGS=test --warning-mode all + +SHELL=bash + +test: + $(JF) $(JF_ARGS) + +lint-test: + cd vendor/dry4java && mvn -q -DskipTests package + ./scripts/dry_test.sh + @echo "Passable amount of duplicate code" + +full-test: lint-test test diff --git a/README.md b/README.md index b8a331d..9d816f7 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,47 @@ # Server -This is the official server for [MediaGarrd](https://github.com/MediaGarrd/MediaGarrd). +The official server for [MediaGarrd](https://github.com/MediaGarrd/MediaGarrd). It backs up the configuration of the services on its host into a single zip archive on a schedule, and the [MediaGarrd Client](https://github.com/MediaGarrd/Client) manages it and downloads the archives to another machine. + +Full documentation, including configuration, archives and restoring, is on the [MediaGarrd website](https://mediagarrd.github.io/MediaGarrd/). + +## Docs +- [settings.md](./docs/settings.md): every environment variable and its default. +- [API.md](./docs/API.md): every HTTP endpoint and what it returns. +- [database.md](./docs/database.md): recovering the server's database from a backup. +- [https.md](./docs/https.md): serving the API over HTTPS behind nginx or Caddy. + +## Requirements +- A Linux host running Docker with Compose v2 ## Installation ```bash git clone --depth 1 https://github.com/MediaGarrd/Server.git cd Server -./install.sh # Drops .env, client.env, and docker-compose.yml +cp docker-compose.example.yml docker-compose.yml +docker compose up --build -d +``` + +Then get the single-use setup PIN from the logs: +```bash +docker logs mediagarrd-server 2>&1 | grep "Setup PIN" +``` +Open `http://:38471/config`, enter the PIN, add the services to back up, and finish setup. + +Then pair the [MediaGarrd Client](https://github.com/MediaGarrd/Client). When you press Finish Setup, the page shows a `Pairing PIN` once, with a copy button, and the logs show it too: +```bash +docker logs mediagarrd-server 2>&1 | grep "Pairing PIN" +``` +Enter it in the Client when it asks. The Client receives a token, uses it once to confirm the pairing and sends it with every request, and the PIN stops working once that is done. To pair another Client, create a pairing code from a paired one, or restart the server with `MEDIAGARRD_OPEN_PAIRING=true` to print a new PIN (remove it afterwards). If you are upgrading from a version without pairing, the logs show a `Pairing PIN` on the first start. + +## Updating +```bash +git pull docker compose up --build -d ``` +> **Security:** the server mounts `/var/run/docker.sock`, which gives it root-equivalent access to the host. After setup its API needs a token from pairing, but the PIN and token travel in plain text over HTTP, so put it behind HTTPS ([docs/https.md](./docs/https.md)) before exposing it beyond a trusted network. +> +> A paired Client is treated as the owner of the host: it can choose which host paths are backed up and where archives are written. Only pair Clients you trust. Backup folders and archives created by the server are readable by their owner only (the server runs as root), so restore with `sudo`. See [docs/settings.md](./docs/settings.md#security-notes). + ## License -[GPLv3](./LICENSE) +[MIT](./LICENSE) diff --git a/build.gradle.kts b/build.gradle.kts index 7273d91..afffa02 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,18 +1,27 @@ plugins { java - id("org.springframework.boot") version "3.3.5" - id("io.spring.dependency-management") version "1.1.6" + id("org.springframework.boot") version "4.1.3" + id("io.spring.dependency-management") version "1.1.7" } +version = "0.1.0" + repositories { mavenCentral() } dependencies { testImplementation("org.springframework.boot:spring-boot-starter-test") + testImplementation("org.springframework.boot:spring-boot-starter-webmvc-test") testRuntimeOnly("org.junit.platform:junit-platform-launcher") - implementation("org.springframework.boot:spring-boot-starter-web") + implementation("org.springframework.boot:spring-boot-starter-webmvc") implementation("org.springframework.boot:spring-boot-starter") + implementation("org.xerial:sqlite-jdbc:3.54.1.0") + implementation("com.github.docker-java:docker-java-core:3.5.1") + implementation("com.github.docker-java:docker-java-transport-httpclient5:3.5.1") + implementation("org.apache.commons:commons-compress:1.27.1") + compileOnly("org.projectlombok:lombok:1.18.48") + annotationProcessor("org.projectlombok:lombok:1.18.48") } java { @@ -21,25 +30,38 @@ java { } } +springBoot { + buildInfo() +} + tasks.test { useJUnitPlatform { - excludeTags("real-runners") + excludeTags("scale") } } -tasks.register("realRunnersPromptCheck") { - description = "Runs interactive real-environment runner checks (prompts for credentials and endpoints)." - group = "verification" - classpath = sourceSets["test"].runtimeClasspath - mainClass.set("wellatleastitried.mediagarrd.service.RealRunnersInteractiveCheck") - standardInput = System.`in` - dependsOn(tasks.testClasses) -} - -tasks.register("realRunnersEnvTest") { - description = "Runs env-backed real runner integration test using .env.test or .env values." +tasks.register("scaleTest") { group = "verification" + description = "Builds very large archives under a small heap" + testClassesDirs = sourceSets.test.get().output.classesDirs + classpath = sourceSets.test.get().runtimeClasspath useJUnitPlatform { - includeTags("real-runners") + includeTags("scale") + } + val scratch = layout.buildDirectory.dir("scale-tmp").get().asFile + maxHeapSize = "64m" + jvmArgs("-XX:+UseG1GC", "-Xms16m", "-XX:MinHeapFreeRatio=10", "-XX:MaxHeapFreeRatio=30", "-XX:+ExitOnOutOfMemoryError") + systemProperty("java.io.tmpdir", scratch.absolutePath) + doFirst { + scratch.deleteRecursively() + scratch.mkdirs() + } + doLast { + scratch.deleteRecursively() + } + testLogging { + showStandardStreams = true + events("passed", "failed", "skipped") } + shouldRunAfter(tasks.test) } diff --git a/docker-compose.example.yml b/docker-compose.example.yml index 9f93f22..14dc853 100644 --- a/docker-compose.example.yml +++ b/docker-compose.example.yml @@ -1,16 +1,17 @@ -# Auto-generated docker-compose.yml by install.sh services: mediagarrd-server: build: context: . dockerfile: Dockerfile container_name: mediagarrd-server - env_file: - - ./secrets/server.env + environment: + - SERVER_PORT=38471 + - MEDIAGARRD_BACKUP_INTERVAL=PT12H + - MEDIAGARRD_RETENTION_COUNT=10 ports: - "38471:38471" volumes: - "./data/server/backups:/var/lib/mediagarrd/backups" - - "/srv/jellyfin:/srv/sources/jellyfin:ro" - - "/home/user/sonarr:/srv/sources/sonarr:ro" + - "./data/server/db:/var/lib/mediagarrd/db" + - /var/run/docker.sock:/var/run/docker.sock restart: unless-stopped diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..f23cef3 --- /dev/null +++ b/docs/API.md @@ -0,0 +1,107 @@ +# Server API + +All endpoints are under `/api/v1`. Every error is returned as `{"error": ""}` with a matching status code: a 4xx carries the reason, and a 5xx carries `{"error": "Internal error"}` (the detail is only in the server log), with one exception: a failed `POST /backups/run` answers 500 with the run's failure reason in `error`, because the Client dashboard shows it and a paired Client is the owner. This includes `404` and `405` from the framework (`{"error": "Not Found"}`, `{"error": "Method Not Allowed"}` with an `Allow` header) and `413` for a request body over 64 KiB. Missing backups answer `404` with `Backup not found` or `No backup archives found`. + +Every response carries `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer` and a `Content-Security-Policy` of `default-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'`, and everything except the setup page's `/css` and `/js` files is sent with `Cache-Control: no-store`. Request limits: 64 KiB per body, 32 paths of at most 4096 characters per service, a backup location of at most 4096 characters, and a PIN or pairing code of at most 64 characters (`400` otherwise). + +## Authentication +After setup, every endpoint except the ones marked open needs the header `Authorization: Bearer `. A client gets its token by pairing (see below). Before setup is finished the `401` message says setup is not finished. A missing, malformed, unknown or revoked token is answered with `401`, `WWW-Authenticate: Bearer` and `{"error": "..."}`. Tokens are never logged and are only ever sent in the reply to `POST /pair`. + +Open endpoints (no token): `GET /health` (reduced, see below), `GET /version`, `GET /setup`, `POST /setup/session`, `POST /pair`. Everything else under `/api/v1`, including paths that do not exist, answers `401` without a token, except that a wrong method on an existing path answers `405` (it reveals only that the route exists). + +Before setup is finished, the setup page's endpoints (`/config`, `/schedule`, `/services`, `/notifications/webhook`, `/setup/complete`) also accept the setup session cookie instead of a token. After setup is finished that cookie is ignored. + +## Pairing +| Endpoint | Auth | Returns | +|---|---|---| +| `POST /pair` | open | `{"token": "...", "id": "...", "name": "..."}` when the body's `pin` is the current pairing PIN or a valid pairing code. The pairing is pending until the token is used (see below). | +| `POST /pairing-codes` | token | `{"code": "ABCDE-FGHJK", "expiresAt": ""}`, a single-use code for pairing another client. | +| `GET /clients` | token | Every paired client as `{"id", "name", "createdAt", "lastUsedAt", "current"}`; `current` is true for the caller. `lastUsedAt` is `null` until first use and is updated at most once a minute. | +| `DELETE /clients/{id}` | token | An empty `204` once that client is unpaired, or `404` for an unknown id. A client may unpair itself with its own id. | + +`POST /pair` takes `{"pin": "<6-digit PIN or pairing code>", "name": ""}`. The label is 1 to 64 characters (letters, digits, spaces and `. _ - ( ) ' @ +`); one is generated when it is left out. The reply carries the token once and the server keeps only its SHA-256 hash. + +The PIN is the one printed in the logs as `Pairing PIN: NNNNNN`. The setup PIN only unlocks the setup page. When setup is finished a new PIN is printed as `Pairing PIN` and is also returned by `POST /setup/complete`, and it works until one client has paired. A server that finished setup earlier prints one on start while no client is paired. A pairing code is created by an already paired client, expires after 10 minutes and works once. + +A successful `POST /pair` creates a pending pairing, kept in memory only. The first authenticated request with the new token (any endpoint, for example `GET /health` with the `Authorization` header) confirms it: only then is the client stored and listed, and only then does the PIN stop working or the pairing code get spent. Until then the same PIN or code can be used again, so a client whose reply was lost simply pairs again. A pending pairing that is not confirmed within 5 minutes is dropped, at most 10 are kept (the oldest is dropped first), and a restart drops them all. Pending pairings are not listed by `GET /clients`, do not count as a paired client, and `DELETE /clients/{id}` answers `404` for them. If several clients pair with the same PIN before any confirms, the first to confirm wins and the others' tokens are then answered with `401`; the same holds for a pairing code. A pairing made with a code is still confirmed if the code expired in the meantime, but not if the code was dropped because 10 newer codes were created. A PIN pairing confirmed after pairing was closed and reopened (the last client was unpaired) is refused. A code pairing that inserts the first confirmed client also closes PIN pairing. + +Statuses of `POST /pair`: +| Status | Meaning | +|---|---| +| `200` | Pairing started. Use the token once to confirm it. | +| `400` | The body is missing, is not JSON, has no `pin`, or has an invalid `name`. | +| `401` | The PIN or code is wrong, expired or already used. | +| `403` | Pairing is closed: a client has already confirmed a pairing with the PIN. Use a pairing code, or restart the server with `MEDIAGARRD_OPEN_PAIRING=true`. | +| `409` | Setup is not finished. Finish it at `/config` first. | +| `429` | Locked after too many wrong attempts. `Retry-After` gives the seconds left. | + +Five wrong PINs lock PIN entry (setup page and pairing share this counter) for 10 minutes. Ten wrong pairing codes lock code entry, separately, for 10 minutes. The locks are global, not per address, and a restart clears them. Opening or closing pairing never clears a lock. Anything that is not exactly six digits is treated as a pairing code. + +Unpairing the last paired client reopens pairing: a fresh `Pairing PIN` is logged and `POST /pair` accepts it. This does not clear a lockout, which is independent of whether pairing is open. + +Revoking a client takes effect on its next request and closes that client's open `/events` streams at once. + +## Status +| Endpoint | Auth | Returns | +|---|---|---| +| `GET /health` | open, token optional | Without a token: `{"healthy", "backupInterval"}`. With a valid token: `{"healthy", "running", "backupRetentionCount", "backupInterval"}`. A token that is present but invalid answers `401`. | +| `GET /version` | open | The running version and the result of the daily check for a newer GitHub release. | +| `GET /events` | token | A Server-Sent Events stream that reports when backup runs start and finish and when archives or configuration change. | + +## Setup +| Endpoint | Auth | Returns | +|---|---|---| +| `GET /setup` | open | Whether first-time setup is finished and whether the caller holds a setup session. | +| `POST /setup/session` | open | An empty `204` and a setup session cookie (`HttpOnly`, `SameSite=Strict`, `Secure` over HTTPS or with `X-Forwarded-Proto: https`; the session ends after 30 minutes without use) when the posted PIN is correct, `401` for a wrong PIN, `410` once setup is finished, `429` while locked. | +| `POST /setup/complete` | setup session | `200` and `{"pairingPin": "NNNNNN"}` once setup is finished, after which the setup page is disabled. A second finish answers `410`, and finishing with no service configured answers `409` with `Add at least one service before finishing setup`. `pairingPin` is `null` when no PIN applies, for example when a client is already paired. The same PIN is printed in the logs as `Pairing PIN`. The reply is the only place the PIN is returned and is sent with `Cache-Control: no-store`. | + +The setup page itself is served at `GET /config` until setup is finished. + +## Configuration +Setup session before setup is finished, token afterwards. + +| Endpoint | Returns | +|---|---| +| `GET /config` | The backup location, the number of backups to keep, and the time between backups. | +| `PUT /config` | The updated configuration after changing the backup location and/or the number of backups to keep. | +| `PUT /schedule` | The server status after changing the time between backups. The interval is an ISO-8601 duration or a number of seconds and must be between 15 minutes and 365 days, both inclusive. A missing, `null`, zero, negative, shorter or longer interval answers `400` with `Backup interval must be between 15 minutes and 365 days` and nothing is saved. | +| `GET /services` | Every configured service with its host paths. | +| `POST /services` | The added service, with `201`. | +| `PUT /services/{name}` | The updated service. | +| `DELETE /services/{name}` | An empty `204` once the service is removed. | + +Statuses: +| Status | Meaning | +|---|---| +| `409` | `PUT /config`, `POST /services`, `PUT /services/{name}` and `DELETE /services/{name}` answer `Configuration cannot be changed while a backup is running, try again once it finishes` while a backup run is going. `POST /services` also answers `409` with `Service already exists: ` when the name is taken, and so does `PUT /services/{name}` when it renames the service to a name that is taken (the comparison ignores case). | + +## Failure webhook +Setup session before setup is finished, token afterwards. An optional webhook URL that receives a message when a backup run fails or only partly succeeds (scheduled and manual runs). The full URL is a secret (Discord and Slack webhook URLs carry a token), so no endpoint ever returns it: only whether one is set and its `scheme://host[:port]`. + +| Endpoint | Returns | +|---|---| +| `GET /notifications/webhook` | `{"configured": true, "target": "https://discord.com"}`, or `{"configured": false, "target": null}`. | +| `PUT /notifications/webhook` | The same shape as `GET`, after saving. The body is `{"url": "https://..."}`; an empty string, `null` or a missing `url` clears the webhook. | +| `POST /notifications/webhook/test` | `{"delivered": true, "status": 200, "error": null}` after sending a `test` event to the saved URL and waiting up to 5 seconds. When it is not delivered, `delivered` is `false`, `status` is the receiver's HTTP status or `null`, and `error` is a short reason: `Webhook answered 404`, `Timed out`, `Could not connect` or `Delivery failed`. The reply never contains the URL or the receiver's body. | + +Statuses: +| Status | Meaning | +|---|---| +| `200` | Saved, or the test was attempted (check `delivered`). | +| `400` | The URL is not valid (`Webhook URL is not a valid URL`, `must use http or https`, `must not contain user info`, `must not contain a fragment`, `must not contain spaces or control characters`, `must have a valid host name`, `is too long`), or a test was requested with no webhook configured (`No webhook is configured`). | +| `429` | A test was sent less than 10 seconds ago. The limit is global, counts attempts, and `Retry-After` gives the seconds left. | + +A URL must be absolute `http` or `https`, at most 2048 characters, with a host name, without user info (`user:pass@`), a fragment (`#`), or whitespace. A host name with an underscore (for example `http://home_assistant:8123`) is refused: use the IP address or a DNS name. The three message shapes are described in [settings.md](./settings.md#failure-webhook). + +## Backups +Token required. + +| Endpoint | Returns | +|---|---| +| `GET /backups` | Every archive with its id, file name, size, and creation time, newest first. Both the order and the creation time come from the timestamp in the file name (`yyyyMMdd-HHmmss-SSS`, UTC); only an archive whose name has no valid timestamp uses the file's last-modified time. | +| `GET /backups/latest` | The newest archive's details. | +| `GET /backups/{id}` | One archive's details. | +| `GET /backups/latest/download` | The newest archive as a zip file. | +| `GET /backups/{id}/download` | One archive as a zip file. | +| `DELETE /backups/{id}` | An empty `204` once the archive is deleted. | +| `POST /backups/run` | The run id, start and end time, services that ran, and the new archive, once the backup finishes. If the run fails, `500` with the failure reason in `error` (the one 5xx that is not `Internal error`). `409` when a run is already in progress (`A backup run is already in progress`) or when no services are configured (`No services are configured for backup`). | diff --git a/docs/database.md b/docs/database.md new file mode 100644 index 0000000..acbe951 --- /dev/null +++ b/docs/database.md @@ -0,0 +1,53 @@ +# Recovering the database + +Every backup archive contains a consistent copy of the server's own database: its settings, services, and backup records. The copy is taken while no other database operation runs, so it is never half written. It does not contain the record of the run that created it. + +The database also holds the paired clients (name, creation and last-use time, and a SHA-256 hash of each token). Tokens themselves are never stored, so an archive cannot be used to sign in, but it does keep clients that were paired when it was taken. Restoring an old copy therefore brings back clients that were unpaired since, and their tokens work again. After a restore, check `GET /api/v1/clients` and unpair anything that should be gone, or pair again with `MEDIAGARRD_OPEN_PAIRING=true`. + +## Where the copy is in the archive +The copy sits at the database file's absolute host path, without the leading `/`. With the example `docker-compose.yml`, which mounts `./data/server/db` at `/var/lib/mediagarrd/db`, that is something like: +``` +home/you/Server/data/server/db/mediagarrd.db +``` +To find it in an archive: +```bash +bsdtar -tf .zip | grep 'mediagarrd\.db$' +``` +If the copy could not be taken, the archive has no database entry and the run was reported as partial with the error listed under `_mediagarrd-server`. + +On Docker Desktop (macOS and Windows) the path is one inside Docker's VM, so it will not match your real host path. The file name is still `mediagarrd.db`. + +## Restoring it +Never restore over the database of a running server. + +1. Stop the server: + ```bash + docker compose stop + ``` +2. Restore the archive into a new directory with [mgrecover](https://github.com/MediaGarrd/Recovery): + ```bash + curl -fLO https://github.com/MediaGarrd/Recovery/releases/latest/download/mgrecover.sh + chmod +x mgrecover.sh + sudo ./mgrecover.sh -C restore .zip + ``` + `-C` restores the whole archive under `restore` (created if missing), so it can be large. It prints a plan and asks for confirmation (`-y` skips it and is required without a terminal). It creates no symbolic links and writes nothing outside that directory. With `-C`, files are restored without their original owners (with `sudo` they belong to root); step 3 copies the database back as root into the server's existing directory, which keeps its owner and mode. + + To extract only the database instead (this needs the directory to exist): + ```bash + mkdir restore + sudo bsdtar -xpf .zip -C restore '' + ``` +3. Copy it over the current database in the mounted database directory (`./data/server/db` with the example compose file): + ```bash + sudo cp restore/ ./data/server/db/mediagarrd.db + sudo rm -f ./data/server/db/mediagarrd.db-journal ./data/server/db/mediagarrd.db-wal ./data/server/db/mediagarrd.db-shm + ``` +4. Start the server again: + ```bash + docker compose start + ``` + +mgrecover needs `bsdtar` (the `libarchive-tools` package on Debian and Ubuntu). A full restore with `sudo ./mgrecover.sh .zip` puts back every file in the archive, not only the database, and writes the database to its host path. That is only safe while the server is stopped; remove the `-journal`, `-wal` and `-shm` files as in step 3 before starting the server. + +## If the database is damaged +The server checks its database on startup. A missing or outdated database is rebuilt or upgraded automatically. A corrupt one is moved aside to `mediagarrd.db.corrupt-` and replaced with an empty database, so the server carries on with no settings, services or paired clients. This also happens while the server is running: the server then behaves as it does on a first start, without a restart. Setup opens again, a new `Setup PIN` is written to the log (look for the `The database was damaged` line), pairing and the web setup page at `/config` work as on a fresh install, and every Client that was paired gets `401` until it is paired again. The backup location, retention count and backup schedule are read again from the new database, so they go back to the defaults (or the `MEDIAGARRD_` environment values) until you set them again. Open event streams are closed, pairings that had not been confirmed are dropped, and a backup that is running at that moment is not stopped. Restore a copy from the newest archive as above to get your settings back (stop the server first), or use the new Setup PIN to configure the server again. diff --git a/docs/https.md b/docs/https.md new file mode 100644 index 0000000..6fe251d --- /dev/null +++ b/docs/https.md @@ -0,0 +1,84 @@ +# HTTPS + +The Server speaks plain HTTP. To serve it over HTTPS, put a reverse proxy in front of it. This matters because the PIN and the token travel in plain text over HTTP. On a network you do not control, use HTTPS. The Client has its own page for the dashboard side: [Client docs/https.md](https://github.com/MediaGarrd/Client/blob/main/docs/https.md). + +The Server has no built-in TLS settings. + +## 1. Keep the plain port private +`docker-compose.example.yml` publishes the Server with `"38471:38471"`. Remove that mapping so the plain port is not reachable from outside, and put the Server and the proxy on a shared Docker network. The proxy reaches it by container name. + +```yaml +services: + mediagarrd-server: + build: + context: . + dockerfile: Dockerfile + container_name: mediagarrd-server + environment: + - SERVER_PORT=38471 + - MEDIAGARRD_BACKUP_INTERVAL=PT12H + - MEDIAGARRD_RETENTION_COUNT=10 + volumes: + - "./data/server/backups:/var/lib/mediagarrd/backups" + - "./data/server/db:/var/lib/mediagarrd/db" + - /var/run/docker.sock:/var/run/docker.sock + networks: + - proxy + restart: unless-stopped + +networks: + proxy: + name: proxy +``` + +Run the proxy on the same network (`proxy`) and send traffic to `mediagarrd-server:38471`. The Server's `/config` setup page is also served through the proxy, so do the first setup over HTTPS too. + +## 2. Reverse proxy examples +Both examples assume the proxy is a container on the `proxy` network and the Server is reached at `https://mediagarrd.example.com`. + +### Caddy +Caddy gets and renews a certificate by itself for a public domain. +``` +mediagarrd.example.com { + reverse_proxy mediagarrd-server:38471 { + flush_interval -1 + } +} +``` +`flush_interval -1` sends the live event stream (`/api/v1/events`) through immediately. Caddy sets no time limit on a response, so large backup downloads are not cut off. + +### nginx +```nginx +server { + listen 443 ssl http2; + server_name mediagarrd.example.com; + + ssl_certificate /etc/ssl/mediagarrd/fullchain.pem; + ssl_certificate_key /etc/ssl/mediagarrd/privkey.pem; + + location / { + proxy_pass http://mediagarrd-server:38471; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_buffering off; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + } +} +``` +- On nginx 1.25.1 or newer, `http2 on;` as its own directive replaces the `http2` parameter on `listen`; the parameter still works there but is deprecated. +- `proxy_buffering off` lets the event stream through and avoids writing multi-gigabyte archives to the proxy's disk. +- The one-hour timeouts keep a slow download from being cut off, and a backup run started through the API (`POST /api/v1/backups/run`) waits for the backup to finish, which can take a while. Raise them if your backups take longer. +- The Authorization header is passed to the Server by default. + +## 3. Connect the Client +Give the Client the `https://` address, for example `https://mediagarrd.example.com`. Without a port it uses 443. A token is tied to the exact address it was paired on, so switching from `http://:38471` to `https://...` means pairing again with a PIN or a pairing code. + +The Client does not follow redirects when it talks to the Server, so a proxy rule that redirects HTTP to HTTPS makes an `http://` address fail. For a Server that is already selected the dashboard reports the address the redirect points to; while connecting ("Connect by IP" or `MEDIAGARRD_SERVER_IP`) you only see that no server was found. Use the `https://` address. + +### Certificates from your own authority or self-signed +A certificate from a public authority (Let's Encrypt, Caddy's automatic certificates, Tailscale) needs nothing extra. For a private or self-signed certificate, give the Client the certificate authority with `MEDIAGARRD_SERVER_CA`, described in the Client's [docs/https.md](https://github.com/MediaGarrd/Client/blob/main/docs/https.md). If you reach the Server by IP address, the certificate needs that IP in its Subject Alternative Names. + +## Tailscale +If both machines are on the same tailnet, `tailscale serve` or a Tailscale certificate for the machine name gives you HTTPS without exposing anything to the internet. diff --git a/docs/settings.md b/docs/settings.md new file mode 100644 index 0000000..01605a2 --- /dev/null +++ b/docs/settings.md @@ -0,0 +1,82 @@ +# Settings + +Set these in `environment` in `docker-compose.yml`. Durations use ISO-8601, for example `PT12H`. + +| Variable | Default | What it does | +|---|---|---| +| `SERVER_PORT` | `8080` (`38471` in the example compose file) | The port of the API and setup page. Change the `ports` mapping to match. | +| `MEDIAGARRD_BACKUP_INTERVAL` | `PT12H` | The time between scheduled backups, from `PT15M` (15 minutes) to `P365D` (365 days). A value outside that range is ignored with a warning and `PT12H` is used, and a stored value outside it is ignored the same way. Only the initial value: once it is saved through setup, the API, or the client, the stored value is used. The next backup is due one interval after the last completed or partial backup (a failed run does not count), so restarting the server does not postpone it: an overdue backup runs within about 30 seconds of start. A server with no completed backup yet runs its first one soon after setup is finished, or one interval after start while setup is still open. Deleting the newest archive also removes its record, so after a restart or an interval change the schedule counts from the previous backup. | +| `MEDIAGARRD_RETENTION_COUNT` | `10` | How many backups to keep. Only the initial value, like the interval. | +| `MEDIAGARRD_BACKUP_ROOT` | `/var/lib/mediagarrd/backups` | Where archives are stored, inside the container. Only the initial value. It must be on a mounted volume. | +| `MEDIAGARRD_DATABASE_PATH` | `/var/lib/mediagarrd/db/mediagarrd.db` | The database file, inside the container. It must be on a mounted volume. | +| `MEDIAGARRD_COMPRESSION_LEVEL` | `1` | How hard files are compressed in archives, from `0` (store, no compression) to `9` (smallest, slowest). Files that are already compressed (zip, gz, tgz, bz2, xz, zst, 7z, rar, jpg, jpeg, png, gif, webp, mp4, mkv, mp3, flac, ogg, mov, avi, webm, m4v, m4a, aac, opus, heic, avif, lz4, zstd, jar, docx, xlsx, pptx) are always stored. The server refuses to start with a value outside 0 to 9. | +| `MEDIAGARRD_OPEN_PAIRING` | `false` | Set to `true` to open pairing on start and print a new `Pairing PIN` in the logs even when clients are already paired. A warning is logged on every start while it is set, so remove it once the new client is paired. | +| `MEDIAGARRD_HELPER_IMAGE` | `busybox:stable` | The image used for the helper containers that read each service's files. | +| `MEDIAGARRD_UPDATE_REPOSITORY` | `MediaGarrd/Server` | The GitHub repository checked for new releases. | +| `MEDIAGARRD_GITHUB_API_URL` | `https://api.github.com` | The GitHub API used for the release check. | +| `MEDIAGARRD_UPDATE_CHECK_INTERVAL` | `PT24H` | How often the release check runs. Minimum `PT1H`. | + +## Failure webhook +An optional URL that gets a message when a backup run ends `failed` or `partial`, so a failed scheduled backup (which only retries after the next interval) does not go unnoticed. Set it on the setup page, through `PUT /api/v1/notifications/webhook` (see [API.md](./API.md#failure-webhook)), or from the Client dashboard. It is stored in the settings table; empty means disabled. Use the **Send Test** button or `POST /api/v1/notifications/webhook/test` to check it. + +When it is sent: +- `backup.failed`: every service failed (no archive), a run ended with no service completed, or the run threw after it started (for example the archive could not be written; the message is the exception text). +- `backup.partial`: some services, or only the database snapshot, failed. The archive was created. +- Not sent on a successful run, on a run that is rejected (one already running, no services configured), or on an error before the run starts (for example the service list could not be read). +- `test`: only from the test endpoint. + +The message is sent once, in the background, so it never slows or fails the backup: one attempt, 5 seconds to connect, 10 seconds in total, redirects are not followed, and a failed delivery is only logged as a warning with the host name (never the path or query). At most 16 messages wait in the queue; more are dropped with a warning. Clearing the webhook stops messages not yet sent. + +The body depends on the host, because Discord and Slack do not document how they treat unknown fields: +- `discord.com`, `discordapp.com` and their subdomains: `{"content": "...", "allowed_mentions": {"parse": []}}`. The reason is placed in an inline code span, and `allowed_mentions` stops `@everyone`, `@here` and role or user pings. +- `hooks.slack.com`, and a Discord URL whose path ends in `/slack` (Discord's Slack-compatible endpoint): `{"text": "..."}` with `&`, `<` and `>` escaped. Discord's `/github` endpoint expects GitHub's payloads and is not supported; use the plain webhook URL. +- Any other host (n8n, Home Assistant, ntfy and so on): `{"event", "time", "error", "failedServices", "archiveId", "content", "text"}`. `event` is `backup.failed`, `backup.partial` or `test`, `time` is ISO-8601 UTC (the run's end time, or the moment of the event for an error or a test), `error` is the run's failure reason (one line per service joined with `; `, at most 1000 characters, `null` for a test), `failedServices` lists the service names (empty when not applicable), `archiveId` is present whenever the run created an archive (a partial run, or a failed one that still produced an archive) and omitted otherwise, and `content` and `text` hold the same short message. There is no server name field. + +Every message is at most 1900 characters, has line breaks removed, and has `@` and `<` followed by a zero-width space so no mention or link markup is active. + +Security notes for the webhook: +- **The URL is a secret.** It is never returned by the API (only `scheme://host`), never logged and never part of an error message. It is stored in plain text in the settings database, which is included in the database snapshot inside every backup archive. If an archive leaks, rotate the webhook. +- **Private addresses are allowed on purpose.** Only the owner (the setup session or a paired Client) can set the URL, and people run ntfy or Home Assistant on their LAN, so the server does not block loopback, private or link-local addresses. Redirects are not followed and the test reply carries only the status code, so the test cannot be used to read a response from an internal service. +- **Error text goes to the receiver.** Service names and failure reasons (paths, Docker messages) are sent to whatever you configure. +- The test is limited to one every 10 seconds. +- Host names with an underscore are refused because the JDK HTTP client cannot reach them either. + +## Pairing +Once setup is finished the API needs a token, which a client gets by pairing with a PIN (see [API.md](./API.md#pairing)). +- A new install prints a `Setup PIN` for the `/config` page. When setup is finished, a fresh `Pairing PIN` is shown on the setup page (with a copy button, once) and printed in the logs. It works until one client has paired: the pairing is confirmed when the Client first uses its token, which the Client does straight away. +- An install that finished setup before pairing existed, or that has no paired client, prints a `Pairing PIN` on every start until a client pairs. +- To pair another client, either create a pairing code from a paired client (valid for 10 minutes, one use), or restart the server with `MEDIAGARRD_OPEN_PAIRING=true` and read the new PIN from the logs: `docker logs mediagarrd-server 2>&1 | grep "Pairing PIN"`. Remove the variable afterwards. +- Five wrong PINs lock PIN entry for 10 minutes. Restarting the server clears the lock. +- A paired client can be unpaired from the API (`DELETE /api/v1/clients/{id}`) or the Client. When the last client is unpaired, pairing reopens and a fresh `Pairing PIN` is logged. + +Serve the API over HTTPS when it is reachable beyond a network you trust, because the token and the PIN travel in plain text over HTTP. See [https.md](./https.md). + +## Security notes +- **A paired Client is the owner.** Once paired, a Client can add services with any absolute host path (except `/`), which the server bind-mounts read-only into a helper container and archives, and it can set the backup location to any path the server can write. Treat a pairing PIN or code like a root credential for the host, and unpair Clients you no longer use. +- **The server runs as root** and mounts `/var/run/docker.sock`, which is root-equivalent on the host. This is by design and is not changed by the app. +- **Permissions.** Directories the server creates (the backup folder, `.mediagarrd-runs/`, the data folder) are `0700`, and archives and the database file are `0600`, where the file system supports POSIX permissions. Existing directories you chose are never changed, and archives made by earlier versions keep their mode. Because the files belong to root, read or restore them with `sudo` (for example `sudo mgrecover ...` or `sudo bsdtar -xf `). +- **Retention only deletes archives the server recorded.** An old archive with no database record (left from before an upgrade, or after a database was moved aside as corrupt) is kept and still listed. The same applies to an archive whose record could not be written (the server logs "this archive will not be pruned"); such archives are never deleted automatically. Delete it by hand or with `DELETE /api/v1/backups/{id}`. +- **SQLite side files.** The database file is `0600`, but its `-journal` and `-wal` files follow the process umask, and a data folder that already existed keeps its mode. They hold token hashes and settings only; restrict the data folder itself (`chmod 700`) if others share the host. +- **PINs are logged** in plain text by design, so protect the container logs. The Pairing PIN is also returned once in the reply to Finish Setup. +- **The PIN stays usable until a Client confirms.** After a correct PIN it keeps working; an unconfirmed pairing is dropped after 5 minutes. Several Clients may pair meanwhile and only the first to confirm is kept. The Client stores its token before confirming, so a confirmation whose replies were lost is completed by its next request and never leaves the Client unpaired; if the pending pairing expired first, the Client is asked to pair again and the PIN is still open. A correct PIN does not reset the wrong-attempt counter until pairing closes. A lockout that rotates the PIN does not cancel a pairing already started with the old one. +- **Lockouts are global.** Anyone who can reach the port can lock PIN entry for 10 minutes by sending wrong PINs, and the PIN is replaced when that happens. This is an accepted trade-off; restart the server or wait to recover. +- **Unpairing the last Client reopens pairing** and prints a fresh `Pairing PIN` in the logs, so the server is never stranded. +- **Limits.** Request bodies over 64 KiB are refused with `413`. A service has at most 32 paths of at most 4096 characters, and a PIN or code is at most 64 characters. +- **Setup sessions** expire after 30 minutes without use, and the setup cookie is `Secure` when the request is HTTPS or carries `X-Forwarded-Proto: https`. +- **Pairing codes:** creating one when 10 are open drops the oldest, so a paired Client can invalidate another's code. + +To change where data is kept on the host, change the left side of the volumes in `docker-compose.yml`: +- `./data/server/backups`: the archives. +- `./data/server/db`: the database, which holds every setting and service. Keep it on persistent storage. + +The server also needs `/var/run/docker.sock` mounted to run its helper containers. + +## Memory + +The server idles at roughly 100 to 150 MB and uses a fixed amount of memory while backing up, however many files or however much data a backup holds. Archives are written to disk as a stream, so the only requirement is free disk space: about twice the size of the archive while a run is in progress (the per-path parts plus the merged archive). + +The JVM is tuned in the `Dockerfile`: G1 with a small starting heap that shrinks back after a backup, native memory trimming, and `-XX:+ExitOnOutOfMemoryError` so the container restarts instead of hanging. + +The heap cap defaults to half of the container's memory limit (`JAVA_TOOL_OPTIONS=-XX:MaxRAMPercentage=50`). Without a memory limit on the container this is half of the host's RAM. To change it, set `JAVA_TOOL_OPTIONS` in `environment`, for example `JAVA_TOOL_OPTIONS=-XX:MaxRAMPercentage=70` or `JAVA_TOOL_OPTIONS=-Xmx256m`. Setting it replaces the whole default value, and the JVM prints `Picked up JAVA_TOOL_OPTIONS` at startup when it is in effect. + +The image is pinned to `eclipse-temurin:21.0.13_9-jre` because `-XX:TrimNativeHeapInterval` needs Java 21.0.3 or newer. To check the flags against another image, run `docker run --rm java -XX:TrimNativeHeapInterval=10000 -XX:+UseG1GC -version`. diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d997cfc Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..dbc3ce4 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/install.sh b/install.sh deleted file mode 100755 index 85d0458..0000000 --- a/install.sh +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail -source ./scripts/install-util.sh - -prompt server_port "MediaGarrd-Server host port [$PORT_DEFAULT]: " "$PORT_DEFAULT" -prompt backup_interval "Server automatic backup interval in ISO-8601 format [$INTERVAL_DEFAULT]: " "$INTERVAL_DEFAULT" -prompt backup_root_host "Server backup host path [$BACKUP_LOC_DEFAULT]: " "$BACKUP_LOC_DEFAULT" -prompt backup_retention "Maximum number of backups to keep [$BACKUP_RETENTION_DEFAULT]: " "$BACKUP_RETENTION_DEFAULT" - -yes_no jellyfin_enabled "Enable Jellyfin backups? [Y/n]: " "y" -if [[ "$jellyfin_enabled" == "true" ]]; then - prompt jellyfin_path "Jellyfin source base directory [$DEFAULT_APPDATA_DIR/jellyfin]: " "$DEFAULT_APPDATA_DIR/jellyfin" -fi - -yes_no radarr_enabled "Enable Radarr backups? [Y/n]: " "y" -if [[ "$radarr_enabled" == "true" ]]; then - prompt radarr_path "Radarr source base directory [$DEFAULT_APPDATA_DIR/radarr]: " "$DEFAULT_APPDATA_DIR/radarr" -fi - -yes_no sonarr_enabled "Enable Sonarr backups? [Y/n]: " "y" -if [[ "$sonarr_enabled" == "true" ]]; then - prompt sonarr_path "Sonarr source base directory [$DEFAULT_APPDATA_DIR/sonarr]: " "$DEFAULT_APPDATA_DIR/sonarr" -fi - -yes_no prowlarr_enabled "Enable Prowlarr backups? [Y/n]: " "y" -if [[ "$prowlarr_enabled" == "true" ]]; then - prompt prowlarr_path "Prowlarr source base directory [$DEFAULT_APPDATA_DIR/prowlarr]: " "$DEFAULT_APPDATA_DIR/prowlarr" -fi - -yes_no tdarr_enabled "Enable Tdarr backups? [Y/n]: " "y" -if [[ "$tdarr_enabled" == "true" ]]; then - prompt tdarr_path "Tdarr source base directory [$DEFAULT_APPDATA_DIR/tdarr]: " "$DEFAULT_APPDATA_DIR/tdarr" -fi - -yes_no qbittorrent_enabled "Enable qBittorrent backups? [Y/n]: " "y" -if [[ "$qbittorrent_enabled" == "true" ]]; then - prompt qbittorrent_path "qBittorrent source base directory [$DEFAULT_APPDATA_DIR/qbittorrent]: " "$DEFAULT_APPDATA_DIR/qbittorrent" - - yes_no has_saved_torrents "Would you like to add an additional path for stored .torrent files? [Y/n]: " "n" - if [[ "$has_saved_torrents" == "true" ]]; then - prompt qbittorrent_saved_torrents_path "qBittorrent saved-torrents source directory [$MNT_DIR/torrents]: " "$MNT_DIR/torrents" - fi -fi - -{ - cat < "$ENV_FILE" - - cat > "$SERVER_ENV_FILE" < "$COMPOSE_FILE" - -echo "" -echo "Created: $COMPOSE_FILE" -echo "Created: $ENV_FILE" -echo "Created: $SERVER_ENV_FILE" -echo "" -echo "Next steps:" -echo "1. Review .env" -echo "2. Review secrets/server.env" -echo "3. Review docker-compose.yml" -echo "4. Start services with: docker compose up --build -d" diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..a0f2434 --- /dev/null +++ b/mise.toml @@ -0,0 +1,2 @@ +[tools] +java = "21.0.0" diff --git a/ref/ADD_NEW_SERVICE.md b/ref/ADD_NEW_SERVICE.md deleted file mode 100644 index 8a111bd..0000000 --- a/ref/ADD_NEW_SERVICE.md +++ /dev/null @@ -1,7 +0,0 @@ -# Adding a new service - -When adding a new service to the project, doing the following will make it easy: -```bash -rg //@ADD_NEW_SERVICE -``` -in the repository root to identify the files that require changes to support a new service. These files will always require modification when adding a new service, but there may be more to do depending on the implementation. diff --git a/ref/SUPPORTED_SERVICES b/ref/SUPPORTED_SERVICES deleted file mode 100644 index c816d7f..0000000 --- a/ref/SUPPORTED_SERVICES +++ /dev/null @@ -1,10 +0,0 @@ -//@ADD_NEW_SERVICE -// All support services will be listed here - alphabetic order -// Coming soon - Gitea, Lidarr - -Jellyfin -Prowlarr -QBittorrent -Radarr -Sonarr -Tdarr diff --git a/ref/structurizr/workspace.dsl b/ref/structurizr/workspace.dsl new file mode 100644 index 0000000..72d89de --- /dev/null +++ b/ref/structurizr/workspace.dsl @@ -0,0 +1,102 @@ +workspace "MediaGarrd Server" "Automated backups for self-hosted services" { + + !identifiers hierarchical + + model { + u = softwareSystem "MediaGarrd-Client" "MediaGarrd-Client service running on a separate machine" { + tags "External" + } + + docker = softwareSystem "Docker Engine" "Runs short-lived backup containers" { + tags "External" + } + + targets = softwareSystem "Self-hosted Services" "Services being backed up" { + tags "External" + } + + ss = softwareSystem "MediaGarrd" "Automated backups for self-hosted services" { + server = container "Backup Server" "Serves API, schedules and orchestrates backups" "Java" { + api = component "API" "Handles HTTP requests" "REST" { + tags "Api" + } + schedule = component "Scheduler" "Triggers scheduled runs" { + tags "Schedule" + } + bo = component "Orchestrator" "Coordinates runs, prunes stale backups" { + tags "Management" + } + ir = component "Runners" "Launch one backup container per service" { + tags "Runner" + } + } + job = container "Backup Job" "Short-lived container that archives one service" "Docker image" { + tags "Job" + } + db = container "Database" "Config and backup history" { + tags "Database" + } + fs = container "Backup Storage" "Compressed backup archives" { + tags "Filesystem" + } + } + + u -> ss.server.api "Manages config/backups via" + ss.server.api -> ss.db "Reads config/history" + ss.server.api -> ss.fs "Reads backup data" + ss.server.api -> ss.server.bo "Triggers run" + + ss.server.schedule -> ss.server.bo "Triggers run" + ss.server.bo -> ss.server.ir "Delegates per-service backups" + ss.server.bo -> ss.fs "Deletes stale backups" + + ss.server.ir -> ss.db "Reads service config path, logs run results" + ss.server.ir -> docker "Starts and monitors containers" "Docker API" + docker -> ss.job "Runs" + ss.job -> targets "Reads data from" + ss.job -> ss.fs "Writes compressed archive" + } + + views { + systemContext ss "Context" { + include * + autolayout lr + } + + container ss "Containers" { + include * + autolayout lr + } + + component ss.server "Components" { + include * + autolayout lr + } + + styles { + element "Element" { + color #0773af + stroke #0773af + strokeWidth 7 + shape roundedbox + } + element "Database" { + shape cylinder + } + element "External" { + stroke #999999 + color #999999 + } + element "Boundary" { + strokeWidth 5 + } + relationship "Relationship" { + thickness 4 + } + } + } + + configuration { + scope softwaresystem + } +} diff --git a/scripts/dry_test.sh b/scripts/dry_test.sh new file mode 100755 index 0000000..55e5d7f --- /dev/null +++ b/scripts/dry_test.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash + +DRY_DIR=vendor/dry4java + +JAR="$DRY_DIR/target/dry4java-0.1.0-SNAPSHOT.jar" +LONG_THRESHOLD=10 +read -r groups locations long < <( + java -jar "$JAR" ./src | tee /dev/stderr | awk -v thr="$LONG_THRESHOLD" ' + /^DUPLICATE/ { g++; next } + match($0, /:[0-9]+-[0-9]+/) { + split(substr($0, RSTART+1, RLENGTH-1), r, "-") + if (r[2] - r[1] + 1 > thr) l++ + n++ + } + END { print g+0, n+0, l+0 }' +) +echo "duplicate groups: $groups, long blocks: $long" +GROUP_THRESHOLD=5 +(( groups > GROUP_THRESHOLD )) && { echo "Too many duplicate groups"; exit 1; } +(( long > LONG_THRESHOLD )) && { echo "Too many long duplicates"; exit 2; } +exit 0 diff --git a/scripts/install-util.sh b/scripts/install-util.sh deleted file mode 100644 index 75062bf..0000000 --- a/scripts/install-util.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env bash - -ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -SECRETS_DIR="$ROOT_DIR/secrets" -COMPOSE_FILE="$ROOT_DIR/docker-compose.yml" -ENV_FILE="$ROOT_DIR/.env" -SERVER_ENV_FILE="$SECRETS_DIR/server.env" -CLIENT_ENV_FILE="$SECRETS_DIR/client.env" - -PORT_DEFAULT="38471" -INTERVAL_DEFAULT="PT12H" -BACKUP_LOC_DEFAULT="./data/server/backups" -BACKUP_RETENTION_DEFAULT="10" - -MNT_DIR="/mnt" -DEFAULT_APPDATA_DIR="$MNT_DIR/appdata" - -mkdir -p "$SECRETS_DIR" - -prompt() { - local var_name="$1" - local prompt_text="$2" - local default_value="${3:-}" - local value="" - - read -r -p "$prompt_text" value - if [[ -z "$value" ]]; then - value="$default_value" - fi - - printf -v "$var_name" '%s' "$value" -} - -yes_no() { - local var_name="$1" - local prompt_text="$2" - local default_value="${3:-y}" - local response - - read -r -p "$prompt_text" response - response="${response:-$default_value}" - if [[ "$response" =~ ^[Yy]([Ee][Ss])?$ ]]; then - printf -v "$var_name" 'true' - else - printf -v "$var_name" 'false' - fi -} - diff --git a/src/main/java/wellatleastitried/mediagarrd/Constants.java b/src/main/java/wellatleastitried/mediagarrd/Constants.java deleted file mode 100644 index 94aeca9..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/Constants.java +++ /dev/null @@ -1,30 +0,0 @@ -package wellatleastitried.mediagarrd; - -import java.util.EnumMap; - -//@ADD_NEW_SERVICE -public final class Constants { - - public enum Services { - JELLYFIN, - RADARR, - SONARR, - PROWLARR, - TDARR, - QBITTORRENT - } - - public static final EnumMap SUPPORTED_SERVICES; - - static { - SUPPORTED_SERVICES = new EnumMap<>(Services.class); - SUPPORTED_SERVICES.put(Services.JELLYFIN, "Jellyfin"); - SUPPORTED_SERVICES.put(Services.RADARR, "Radarr"); - SUPPORTED_SERVICES.put(Services.SONARR, "Sonarr"); - SUPPORTED_SERVICES.put(Services.PROWLARR, "Prowlarr"); - SUPPORTED_SERVICES.put(Services.TDARR, "Tdarr"); - SUPPORTED_SERVICES.put(Services.QBITTORRENT, "QBittorrent"); - } - - private Constants() {} -} diff --git a/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java b/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java deleted file mode 100644 index fbe9798..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/MediaGarrd.java +++ /dev/null @@ -1,16 +0,0 @@ -package wellatleastitried.mediagarrd; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.scheduling.annotation.EnableScheduling; - -@SpringBootApplication -@EnableScheduling -@EnableConfigurationProperties(MediaGarrdProperties.class) -public class MediaGarrd { - - public static void main(String[] args) { - SpringApplication.run(MediaGarrd.class, args); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java deleted file mode 100644 index 598fc10..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/MediaGarrdProperties.java +++ /dev/null @@ -1,56 +0,0 @@ -package wellatleastitried.mediagarrd; - -import java.time.Duration; -import java.util.EnumMap; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -import static wellatleastitried.mediagarrd.Constants.*; -import wellatleastitried.mediagarrd.services.config.AbstractServiceConfig; - -@ConfigurationProperties(prefix = "mediagarrd") -public class MediaGarrdProperties { - - private Duration backupInterval = Duration.ofHours(12); - private String backupRoot = "./data/server/backups"; - private int retentionCount = 10; - private ServicesProperties services = new ServicesProperties(); - - public Duration getBackupInterval() { - return backupInterval; - } - - public void setBackupInterval(Duration backupInterval) { - this.backupInterval = backupInterval; - } - - public String getBackupRoot() { - return backupRoot; - } - - public void setBackupRoot(String backupRoot) { - this.backupRoot = backupRoot; - } - - public int getRetentionCount() { - return retentionCount; - } - - public void setRetentionCount(int retentionCount) { - this.retentionCount = retentionCount; - } - - public ServicesProperties getServices() { - return services; - } - - public void setServices(ServicesProperties services) { - this.services = services; - } - - public EnumMap getServiceConfigs() { - return services.toRuntimeConfigs(); - } - - -} diff --git a/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java b/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java deleted file mode 100644 index d7081dc..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/ServicesProperties.java +++ /dev/null @@ -1,83 +0,0 @@ -package wellatleastitried.mediagarrd; - -import java.util.EnumMap; - -import static wellatleastitried.mediagarrd.Constants.*; -import wellatleastitried.mediagarrd.services.config.*; - -public class ServicesProperties { - - //@ADD_NEW_SERVICE - private CommonServiceConfig jellyfin; - private CommonServiceConfig radarr; - private CommonServiceConfig sonarr; - private CommonServiceConfig prowlarr; - private CommonServiceConfig tdarr; - private QBittorrentServiceConfig qbittorrent; - - public EnumMap toRuntimeConfigs() { - EnumMap configs = new EnumMap<>(Services.class); - put(configs, Services.JELLYFIN, jellyfin); - put(configs, Services.RADARR, radarr); - put(configs, Services.SONARR, sonarr); - put(configs, Services.PROWLARR, prowlarr); - put(configs, Services.TDARR, tdarr); - put(configs, Services.QBITTORRENT, qbittorrent); - return configs; - } - - private static void put(EnumMap configs, Services service, AbstractServiceConfig config) { - if (config != null) { - configs.put(service, config); - } - } - - public CommonServiceConfig getJellyfin() { - return jellyfin; - } - - public void setJellyfin(CommonServiceConfig jellyfin) { - this.jellyfin = jellyfin; - } - - public CommonServiceConfig getRadarr() { - return radarr; - } - - public void setRadarr(CommonServiceConfig radarr) { - this.radarr = radarr; - } - - public CommonServiceConfig getSonarr() { - return sonarr; - } - - public void setSonarr(CommonServiceConfig sonarr) { - this.sonarr = sonarr; - } - - public CommonServiceConfig getProwlarr() { - return prowlarr; - } - - public void setProwlarr(CommonServiceConfig prowlarr) { - this.prowlarr = prowlarr; - } - - public CommonServiceConfig getTdarr() { - return tdarr; - } - - public void setTdarr(CommonServiceConfig tdarr) { - this.tdarr = tdarr; - } - - public QBittorrentServiceConfig getQbittorrent() { - return qbittorrent; - } - - public void setQbittorrent(QBittorrentServiceConfig qbittorrent) { - this.qbittorrent = qbittorrent; - } - -} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java b/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java deleted file mode 100644 index 3f6300e..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/model/BackupArchive.java +++ /dev/null @@ -1,13 +0,0 @@ -package wellatleastitried.mediagarrd.model; - -import java.nio.file.Path; -import java.time.Instant; - -public record BackupArchive( - String id, - String fileName, - Path path, - long sizeBytes, - Instant createdAt -) { -} diff --git a/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java b/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java deleted file mode 100644 index 18849bb..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/model/BackupRunResult.java +++ /dev/null @@ -1,13 +0,0 @@ -package wellatleastitried.mediagarrd.model; - -import java.time.Instant; -import java.util.List; - -public record BackupRunResult( - String runId, - Instant startedAt, - Instant finishedAt, - List servicesRan, - BackupArchive archive -) { -} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java deleted file mode 100644 index b90dc03..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupArchiveService.java +++ /dev/null @@ -1,282 +0,0 @@ -package wellatleastitried.mediagarrd.service; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.util.Comparator; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import jakarta.annotation.PostConstruct; - -import org.springframework.stereotype.Service; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import wellatleastitried.mediagarrd.MediaGarrdProperties; -import wellatleastitried.mediagarrd.model.BackupArchive; - -@Service -public class BackupArchiveService { - - private static final Logger LOGGER = LoggerFactory.getLogger(BackupArchiveService.class); - - private static final DateTimeFormatter FILE_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss-SSS") - .withZone(ZoneOffset.UTC); - private static final long ARCHIVE_CACHE_TTL_MS = 60_000; // Cache archive list for 60 seconds - - private final MediaGarrdProperties properties; - private final AtomicReference> cachedArchives = new AtomicReference<>(null); - private final AtomicLong cacheLastUpdatedMs = new AtomicLong(0); - - public BackupArchiveService(MediaGarrdProperties properties) { - this.properties = properties; - } - - @PostConstruct - public void cleanupStaleArtifactsOnStartup() { - Path root = rootDirectory(); - Path runsRoot = root.resolve("runs"); - - try { - Files.createDirectories(root); - - try (var stream = Files.list(root)) { - stream - .filter(Files::isRegularFile) - .filter(path -> path.getFileName().toString().endsWith(".zip.tmp")) - .forEach(path -> { - try { - Files.deleteIfExists(path); - LOGGER.info("Startup cleanup: removed stale temporary archive {}", path.getFileName()); - } catch (IOException e) { - LOGGER.warn("Startup cleanup: failed to remove stale temporary archive {}", path, e); - } - }); - } - - if (Files.exists(runsRoot)) { - try (var stream = Files.list(runsRoot)) { - stream - .filter(Files::isDirectory) - .forEach(runDir -> { - try { - removeRunDirectory(runDir); - LOGGER.info("Startup cleanup: removed stale run directory {}", runDir.getFileName()); - } catch (RuntimeException e) { - LOGGER.warn("Startup cleanup: failed to remove stale run directory {}", runDir, e); - } - }); - } - } - - enforceRetention(); - LOGGER.info("Startup cleanup: retention policy enforced"); - } catch (IOException e) { - LOGGER.warn("Startup cleanup: unable to initialize backup root {}", root, e); - } catch (RuntimeException e) { - LOGGER.warn("Startup cleanup: failed while enforcing retention policy", e); - } - } - - public Path rootDirectory() { - return Path.of(properties.getBackupRoot()).toAbsolutePath().normalize(); - } - - public BackupArchive createArchive(Path runDirectory) { - Instant createdAt = Instant.now(); - String fileName = FILE_DATE_FORMAT.format(createdAt) + "-media-backup.zip"; - Path root = rootDirectory(); - Path archivePath = root.resolve(fileName); - - LOGGER.info("Creating backup archive: {} from runDir={}", fileName, runDirectory); - try { - Files.createDirectories(root); - zipDirectory(runDirectory, archivePath); - enforceRetention(); - long size = Files.size(archivePath); - LOGGER.info("Archive created: {} ({} bytes)", fileName, size); - - // Invalidate cache after new archive created - cacheLastUpdatedMs.set(0); - cachedArchives.set(null); - - return new BackupArchive(toId(fileName), fileName, archivePath, size, createdAt); - } catch (IOException e) { - LOGGER.error("Failed to create backup archive: {}", fileName, e); - throw new IllegalStateException("Failed to create backup archive", e); - } - } - - public List listArchives() { - long now = System.currentTimeMillis(); - long lastUpdate = cacheLastUpdatedMs.get(); - - if (now - lastUpdate < ARCHIVE_CACHE_TTL_MS) { - List cached = cachedArchives.get(); - if (cached != null) { - LOGGER.debug("Returning cached archive list ({}ms old)", now - lastUpdate); - return cached; - } - } - - // Cache miss -> rebuild list - Path root = rootDirectory(); - List archives; - if (!Files.exists(root)) { - archives = List.of(); - } else { - try (var stream = Files.list(root)) { - archives = stream - .filter(path -> path.getFileName().toString().endsWith(".zip")) - .sorted(Comparator.comparing(this::lastModified).reversed()) - .map(this::toArchive) - .toList(); - } catch (IOException e) { - throw new IllegalStateException("Failed to list archives", e); - } - } - - cachedArchives.set(archives); - cacheLastUpdatedMs.set(now); - LOGGER.debug("Rebuilt archive cache with {} archives", archives.size()); - return archives; - } - - public Optional latest() { - return listArchives().stream().findFirst(); - } - - public Optional byId(String id) { - return listArchives().stream().filter(archive -> archive.id().equals(id)).findFirst(); - } - - public boolean deleteById(String id) { - Optional archive = byId(id); - if (archive.isEmpty()) { - return false; - } - - try { - Files.deleteIfExists(archive.get().path()); - LOGGER.info("Archive deleted: {}", id); - cacheLastUpdatedMs.set(0); - - cachedArchives.set(null); - return true; - - } catch (IOException e) { - LOGGER.error("Failed to delete archive: {}", id, e); - throw new IllegalStateException("Failed to delete archive " + id, e); - } - } - - public Path createRunDirectory() { - Path runDir = rootDirectory().resolve("runs").resolve(UUID.randomUUID().toString()); - try { - Files.createDirectories(runDir); - return runDir; - } catch (IOException e) { - throw new IllegalStateException("Failed to create run directory", e); - } - } - - public void removeRunDirectory(Path runDirectory) { - if (runDirectory == null || !Files.exists(runDirectory)) { - return; - } - - try (var walk = Files.walk(runDirectory)) { - walk.sorted(Comparator.reverseOrder()).forEach(path -> { - try { - Files.deleteIfExists(path); - } catch (IOException e) { - throw new IllegalStateException("Failed to clean up run directory", e); - } - }); - } catch (IOException e) { - throw new IllegalStateException("Failed to walk run directory", e); - } - } - - private void enforceRetention() throws IOException { - int retain = Math.max(1, properties.getRetentionCount()); - List archives; - try (var stream = Files.list(rootDirectory())) { - archives = stream - .filter(path -> path.getFileName().toString().endsWith(".zip")) - .sorted(Comparator.comparing(this::lastModified).reversed()) - .toList(); - } - for (int i = retain; i < archives.size(); i++) { - Path toDelete = archives.get(i); - LOGGER.info("Retention: deleting old archive: {}", toDelete.getFileName()); - Files.deleteIfExists(toDelete); - } - } - - private void zipDirectory(Path sourceDir, Path zipPath) throws IOException { - Path tempZip = zipPath.resolveSibling(zipPath.getFileName() + ".tmp"); - try (OutputStream fileOut = Files.newOutputStream(tempZip, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); - ZipOutputStream zipOut = new ZipOutputStream(fileOut); - var paths = Files.walk(sourceDir)) { - - paths.filter(Files::isRegularFile).forEach(path -> { - Path relative = sourceDir.relativize(path); - try { - zipOut.putNextEntry(new ZipEntry(relative.toString())); - try (InputStream in = Files.newInputStream(path)) { - in.transferTo(zipOut); - } - zipOut.closeEntry(); - } catch (IOException e) { - throw new IllegalStateException("Failed to zip file " + path, e); - } - }); - } - Files.move(tempZip, zipPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); - } - - private BackupArchive toArchive(Path path) { - String fileName = path.getFileName().toString(); - return new BackupArchive( - toId(fileName), - fileName, - path, - fileSize(path), - lastModified(path) - ); - } - - private String toId(String fileName) { - return fileName.replace(".zip", ""); - } - - private long fileSize(Path path) { - try { - return Files.size(path); - } catch (IOException e) { - return 0L; - } - } - - private Instant lastModified(Path path) { - try { - return Files.getLastModifiedTime(path).toInstant(); - } catch (IOException e) { - return Instant.EPOCH; - } - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java deleted file mode 100644 index 17b49bc..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupOrchestratorService.java +++ /dev/null @@ -1,166 +0,0 @@ -package wellatleastitried.mediagarrd.service; - -import java.nio.file.Path; -import java.util.ArrayList; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicBoolean; - -import jakarta.annotation.PreDestroy; - -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import wellatleastitried.mediagarrd.MediaGarrdProperties; -import wellatleastitried.mediagarrd.model.BackupArchive; -import wellatleastitried.mediagarrd.model.BackupRunResult; -import wellatleastitried.mediagarrd.services.runner.Runner; - -@Service -public class BackupOrchestratorService { - - private static final Logger LOGGER = LoggerFactory.getLogger(BackupOrchestratorService.class); - - private final MediaGarrdProperties properties; - private final RunnerFactory runnerFactory; - private final BackupArchiveService archiveService; - private final BackupScheduleService scheduleService; - private final AtomicBoolean running = new AtomicBoolean(false); - private final ExecutorService runnerExecutor = new ThreadPoolExecutor( - 1, // core threads - 6, // max threads - 30, // keep-alive time - TimeUnit.SECONDS, - new LinkedBlockingQueue<>() - ); - - public BackupOrchestratorService( - MediaGarrdProperties properties, - RunnerFactory runnerFactory, - BackupArchiveService archiveService, - BackupScheduleService scheduleService - ) { - this.properties = properties; - this.runnerFactory = runnerFactory; - this.archiveService = archiveService; - this.scheduleService = scheduleService; - } - - @Scheduled(fixedDelay = 10000) - public void scheduledRun() { - if (running.get()) { - LOGGER.debug("Scheduled check skipped, backup already in progress"); - return; - } - if (!scheduleService.dueNow()) { - return; - } - LOGGER.info("Scheduled backup triggered, next run at {}", scheduleService.getNextRun()); - try { - runBackup(); - } catch (RuntimeException ex) { - LOGGER.error("Scheduled backup run failed", ex); - } - } - - public BackupRunResult runBackup() { - if (!running.compareAndSet(false, true)) { - LOGGER.warn("runBackup() called while backup already in progress, rejecting"); - throw new IllegalStateException("A backup run is already in progress"); - } - - scheduleService.markRunStarted(); - - Path runDirectory = archiveService.createRunDirectory(); - Instant startedAt = Instant.now(); - List runners = runnerFactory.build(properties.getServiceConfigs()); - List servicesCompleted = new ArrayList<>(); - - LOGGER.info("Backup run started: runDir={}, services={}", runDirectory, runners.stream().map(Runner::getServiceName).toList()); - - try { - List> futures = new ArrayList<>(); - for (Runner runner : runners) { - LOGGER.info("Submitting runner for service: {}", runner.getServiceName()); - futures.add(runnerExecutor.submit(() -> runSingleRunner(runner, runDirectory))); - } - - for (Future future : futures) { - try { - RunnerOutcome outcome = future.get(); - if (outcome.success()) { - servicesCompleted.add(outcome.serviceName()); - LOGGER.info("Runner succeeded: {}", outcome.serviceName()); - } else { - LOGGER.warn("Runner failed (non-fatal): {}", outcome.serviceName()); - } - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Backup run interrupted", ex); - } catch (ExecutionException ex) { - LOGGER.warn("Unexpected failure while waiting for runner task", ex.getCause()); - } - } - - LOGGER.info("All runners finished: succeeded={}/{}", servicesCompleted.size(), runners.size()); - BackupArchive archive = archiveService.createArchive(runDirectory); - long durationMs = Instant.now().toEpochMilli() - startedAt.toEpochMilli(); - LOGGER.info("Backup run complete: archive={}, size={}B, duration={}ms, services={}", - archive.fileName(), archive.sizeBytes(), durationMs, servicesCompleted); - return new BackupRunResult( - archive.id(), - startedAt, - Instant.now(), - servicesCompleted, - archive - ); - } finally { - archiveService.removeRunDirectory(runDirectory); - running.set(false); - LOGGER.debug("Run directory cleaned up: {}", runDirectory); - } - } - - public boolean isRunning() { - return running.get(); - } - - public Duration getInterval() { - return scheduleService.getInterval(); - } - - public Duration updateInterval(Duration duration) { - return scheduleService.updateInterval(duration); - } - - @PreDestroy - public void shutdownRunnerExecutor() { - runnerExecutor.shutdownNow(); - } - - private RunnerOutcome runSingleRunner(Runner runner, Path runDirectory) { - LOGGER.info("[{}] Runner starting", runner.getServiceName()); - long start = System.currentTimeMillis(); - try { - runner.run(runDirectory); - LOGGER.info("[{}] Runner finished in {}ms", runner.getServiceName(), System.currentTimeMillis() - start); - return new RunnerOutcome(runner.getServiceName(), true); - } catch (RuntimeException ex) { - LOGGER.error("[{}] Runner failed after {}ms, continuing with remaining services", - runner.getServiceName(), System.currentTimeMillis() - start, ex); - return new RunnerOutcome(runner.getServiceName(), false); - } - } - - private record RunnerOutcome(String serviceName, boolean success) { - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java b/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java deleted file mode 100644 index 0d5f824..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/service/BackupScheduleService.java +++ /dev/null @@ -1,63 +0,0 @@ -package wellatleastitried.mediagarrd.service; - -import java.time.Duration; -import java.time.Instant; -import java.util.concurrent.atomic.AtomicReference; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import wellatleastitried.mediagarrd.MediaGarrdProperties; - -@Service -public class BackupScheduleService { - - private static final Logger LOGGER = LoggerFactory.getLogger(BackupScheduleService.class); - - private final AtomicReference currentInterval; - private final AtomicReference nextRun; - - public BackupScheduleService(MediaGarrdProperties properties) { - Duration interval = safe(properties.getBackupInterval()); - this.currentInterval = new AtomicReference<>(interval); - this.nextRun = new AtomicReference<>(Instant.now().plus(interval)); - LOGGER.info("Backup schedule initialized: interval={}, firstRunAt={}", interval, nextRun.get()); - } - - public Duration getInterval() { - return currentInterval.get(); - } - - public Instant getNextRun() { - return nextRun.get(); - } - - public Duration updateInterval(Duration interval) { - Duration safe = safe(interval); - currentInterval.set(safe); - Instant next = Instant.now().plus(safe); - nextRun.set(next); - LOGGER.info("Backup interval updated: newInterval={}, nextRunAt={}", safe, next); - return safe; - } - - public boolean dueNow() { - Instant now = Instant.now(); - Instant current = nextRun.get(); - return !now.isBefore(current); - } - - public void markRunStarted() { - Instant next = Instant.now().plus(currentInterval.get()); - nextRun.set(next); - LOGGER.info("Backup run started: nextScheduledRun={}", next); - } - - private Duration safe(Duration interval) { - if (interval == null || interval.isNegative() || interval.isZero()) { - return Duration.ofHours(12); - } - return interval; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java b/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java deleted file mode 100644 index 60646f3..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/service/RunnerFactory.java +++ /dev/null @@ -1,112 +0,0 @@ -package wellatleastitried.mediagarrd.service; - -import java.util.ArrayList; -import java.util.List; -import java.util.EnumMap; - -import org.springframework.stereotype.Component; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static wellatleastitried.mediagarrd.Constants.*; -import wellatleastitried.mediagarrd.services.config.*; -import wellatleastitried.mediagarrd.services.runner.*; - -@Component -public class RunnerFactory { - - private static final Logger LOGGER = LoggerFactory.getLogger(RunnerFactory.class); - - public List build(EnumMap serviceConfigMap) { - List runners = new ArrayList<>(); - - for (EnumMap.Entry entry : serviceConfigMap.entrySet()) { - AbstractServiceConfig config = entry.getValue(); - if (config == null || !config.isEnabled()) { - LOGGER.debug("Service '{}' is disabled or unconfigured, skipping", entry.getKey()); - continue; - } - - validate(entry.getKey(), config); - - Services key = entry.getKey(); - - //@ADD_NEW_SERVICE - @SuppressWarnings("unused") - Object exhaustive = switch (key) { - case JELLYFIN -> { - runners.add(new JellyfinRunner(config)); - LOGGER.info("Registered runner: " + SUPPORTED_SERVICES.get(Services.JELLYFIN)); - yield null; - } - case RADARR -> { - runners.add(new RadarrRunner(config)); - LOGGER.info("Registered runner: radarr"); - yield null; - } - case SONARR -> { - runners.add(new SonarrRunner(config)); - LOGGER.info("Registered runner: sonarr"); - yield null; - } - case PROWLARR -> { - runners.add(new ProwlarrRunner(config)); - LOGGER.info("Registered runner: prowlarr"); - yield null; - } - case TDARR -> { - runners.add(new TdarrRunner(config)); - LOGGER.info("Registered runner: tdarr"); - yield null; - } - case QBITTORRENT -> { - runners.add(new QBittorrentRunner((QBittorrentServiceConfig) config)); - LOGGER.info("Registered runner: qbittorrent"); - yield null; - } - }; - } - - LOGGER.info("RunnerFactory built {} runner(s): {}", runners.size(), runners.stream().map(Runner::getServiceName).toList()); - return runners; - } - - private void validate(Services key, AbstractServiceConfig config) { - boolean supported = SUPPORTED_SERVICES.entrySet() - .stream() - .anyMatch(value -> value.getValue().equalsIgnoreCase(SUPPORTED_SERVICES.get(key))); - String serviceName = SUPPORTED_SERVICES.get(key); - if (!supported) { - throw new IllegalArgumentException("Unsupported service configured: " + serviceName); - } - - //@ADD_NEW_SERVICE - @SuppressWarnings("unused") - Object exhaustive = switch (key) { - case JELLYFIN -> { - requirePath(serviceName, "configPath", config.getConfigPath()); - yield null; - } - case RADARR, SONARR, PROWLARR, TDARR -> { - requirePath(serviceName, "path", config.getPath()); - yield null; - } - case QBITTORRENT -> { - if (!(config instanceof QBittorrentServiceConfig)) { - throw new IllegalArgumentException("Invalid configuration for QBittorrent: " + config.getConfigPath()); - } - - QBittorrentServiceConfig qbConfig = (QBittorrentServiceConfig) config; - requirePath(serviceName, "path", qbConfig.getPath()); - requirePath(serviceName, "savedTorrentsPath", qbConfig.getSavedTorrentsPath()); - yield null; - } - }; - } - - private void requirePath(String serviceName, String fieldName, String value) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException("Service " + serviceName + " requires " + fieldName); - } - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java deleted file mode 100644 index e4954f8..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/AbstractServiceConfig.java +++ /dev/null @@ -1,37 +0,0 @@ -package wellatleastitried.mediagarrd.services.config; - -//import java.util.List; - -//@ADD_NEW_SERVICE -abstract public class AbstractServiceConfig { - - private boolean enabled; - private String path; - private String configPath; - - //private List configPaths; - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public String getConfigPath() { - return configPath; - } - - public void setConfigPath(String configPath) { - this.configPath = configPath; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java deleted file mode 100644 index ba9eb66..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/CommonServiceConfig.java +++ /dev/null @@ -1,5 +0,0 @@ -package wellatleastitried.mediagarrd.services.config; - -// For services that require only one path to backup, this can be used. -// Otherwise, create a new config for a service-specific config. -public class CommonServiceConfig extends AbstractServiceConfig {} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java b/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java deleted file mode 100644 index 10a9ff4..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/config/QBittorrentServiceConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package wellatleastitried.mediagarrd.services.config; - -public class QBittorrentServiceConfig extends AbstractServiceConfig { - - private String savedTorrentsPath; - - // public QBittorrentServiceConfig(ServiceConfig) {} - - public String getSavedTorrentsPath() { - return savedTorrentsPath; - } - - public void setSavedTorrentsPath(String savedTorrentsPath) { - this.savedTorrentsPath = savedTorrentsPath; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java deleted file mode 100644 index df60230..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/AbstractLocalCopyRunner.java +++ /dev/null @@ -1,143 +0,0 @@ -package wellatleastitried.mediagarrd.services.runner; - -import java.io.IOException; -import java.nio.file.FileVisitResult; -import java.nio.file.FileVisitor; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.StandardCopyOption; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.List; -import java.util.Locale; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -//@ADD_NEW_SERVICE -public abstract class AbstractLocalCopyRunner implements Runner { - - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractLocalCopyRunner.class); - - private final String serviceName; - - protected AbstractLocalCopyRunner(String serviceName) { - this.serviceName = serviceName; - } - - @Override - public String getServiceName() { - return serviceName; - } - - @Override - public void run(Path outputDirectory) { - Path serviceDirectory = outputDirectory.resolve(serviceName.toLowerCase(Locale.ROOT)); - try { - Files.createDirectories(serviceDirectory); - } catch (IOException e) { - throw new IllegalStateException("Unable to create output directory for " + serviceName, e); - } - - List specs = copySpecs(); - LOGGER.info("[{}] Starting copy: {} spec(s) to {}", serviceName, specs.size(), serviceDirectory); - int succeeded = 0; - for (CopySpec spec : specs) { - try { - copySpec(spec, serviceDirectory); - succeeded++; - } catch (RuntimeException ex) { - LOGGER.warn("[{}] Failed spec '{}' (source={}). Continuing.", serviceName, spec.targetName(), spec.sourcePath(), ex); - } - } - LOGGER.info("[{}] Copy complete: {}/{} specs succeeded", serviceName, succeeded, specs.size()); - } - - protected abstract List copySpecs(); - - protected CopySpec dir(String sourcePath, String targetName) { - return new CopySpec(sourcePath, targetName, true); - } - - protected CopySpec file(String sourcePath, String targetName) { - return new CopySpec(sourcePath, targetName, false); - } - - private void copySpec(CopySpec spec, Path serviceDirectory) { - if (spec.sourcePath() == null || spec.sourcePath().isBlank()) { - throw new IllegalArgumentException(serviceName + " runner missing source path for " + spec.targetName()); - } - - Path source = Path.of(spec.sourcePath()).toAbsolutePath().normalize(); - if (!Files.exists(source)) { - throw new IllegalStateException(serviceName + " source path not found: " + source); - } - - Path target = serviceDirectory.resolve(spec.targetName()); - - try { - if (spec.directory()) { - if (!Files.isDirectory(source)) { - throw new IllegalStateException(serviceName + " expected directory path: " + source); - } - copyDirectory(source, target); - } else { - if (!Files.isRegularFile(source)) { - throw new IllegalStateException(serviceName + " expected file path: " + source); - } - Path parent = target.getParent(); - if (parent != null) { - Files.createDirectories(parent); - } - Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); - LOGGER.debug("[{}] Copied file: {}", serviceName, target); - } - } catch (IOException e) { - throw new IllegalStateException(serviceName + " runner failed while copying " + source, e); - } - } - - - private void copyDirectory(Path source, Path target) throws IOException { - Files.createDirectories(target); - FileVisitor visitor = new SimpleFileVisitor<>() { - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - Path relative = source.relativize(dir); - Path destination = target.resolve(relative); - Files.createDirectories(destination); - LOGGER.debug("[{}] Created dir: {}", serviceName, destination); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Path relative = source.relativize(file); - Path destination = target.resolve(relative); - Path parent = destination.getParent(); - if (parent != null) { - Files.createDirectories(parent); - } - - // This will be used on all files including databases. There is a risk of corruption - // when copying a database as it could be in-use, but this is unlikely AND the fact - // that multiple backups will be retained mitigates this risk. This may be changed - // in the future with an OPTION to stop services during backup, but for now it will - // be a basic copy. - Files.copy(file, destination, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); - LOGGER.debug("[{}] Copied: {}", serviceName, destination); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) { - LOGGER.warn("[{}] Failed to read: {}. Continuing.", serviceName, file, exc); - return FileVisitResult.CONTINUE; - } - }; - Files.walkFileTree(source, visitor); - } - - protected record CopySpec(String sourcePath, String targetName, boolean directory) {} -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java deleted file mode 100644 index cea92d2..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/JellyfinRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrd.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrd.services.config.*; - -import static wellatleastitried.mediagarrd.Constants.*; - -public class JellyfinRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public JellyfinRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.JELLYFIN)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getConfigPath(), "config")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java deleted file mode 100644 index f98c771..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/ProwlarrRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrd.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrd.services.config.*; - -import static wellatleastitried.mediagarrd.Constants.*; - -public class ProwlarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public ProwlarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.PROWLARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java deleted file mode 100644 index 0679f0f..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/QBittorrentRunner.java +++ /dev/null @@ -1,38 +0,0 @@ -package wellatleastitried.mediagarrd.services.runner; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; - -import wellatleastitried.mediagarrd.services.config.*; - -import static wellatleastitried.mediagarrd.Constants.*; - -public class QBittorrentRunner extends AbstractLocalCopyRunner { - - private final QBittorrentServiceConfig config; - - public QBittorrentRunner(QBittorrentServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.QBITTORRENT)); - this.config = config; - } - - @Override - protected List copySpecs() { - List specs = new ArrayList<>(); - specs.add(dir(config.getPath(), "appdata")); - - String savedTorrentPath = config.getSavedTorrentsPath(); - if (savedTorrentPath != null && !savedTorrentPath.isEmpty()) { - specs.add(dir(savedTorrentPath, "saved-torrents")); - } - - Path compose = Path.of(config.getPath()).resolve("docker-compose.yml"); - if (Files.isRegularFile(compose)) { - specs.add(file(compose.toString(), "docker-compose.yml")); - } - - return specs; - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java deleted file mode 100644 index b55c477..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/RadarrRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrd.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrd.services.config.*; - -import static wellatleastitried.mediagarrd.Constants.*; - -public class RadarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public RadarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.RADARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java deleted file mode 100644 index 44747c7..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/Runner.java +++ /dev/null @@ -1,10 +0,0 @@ -package wellatleastitried.mediagarrd.services.runner; - -import java.nio.file.Path; - -public interface Runner { - - String getServiceName(); - - void run(Path outputDirectory); -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java deleted file mode 100644 index beaa063..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/SonarrRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrd.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrd.services.config.*; - -import static wellatleastitried.mediagarrd.Constants.*; - -public class SonarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public SonarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.SONARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java b/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java deleted file mode 100644 index b84cd99..0000000 --- a/src/main/java/wellatleastitried/mediagarrd/services/runner/TdarrRunner.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrd.services.runner; - -import java.util.List; - -import wellatleastitried.mediagarrd.services.config.*; - -import static wellatleastitried.mediagarrd.Constants.*; - -public class TdarrRunner extends AbstractLocalCopyRunner { - - private final AbstractServiceConfig config; - - public TdarrRunner(AbstractServiceConfig config) { - super(SUPPORTED_SERVICES.get(Services.TDARR)); - this.config = config; - } - - @Override - protected List copySpecs() { - return List.of(dir(config.getPath(), "appdata")); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java new file mode 100644 index 0000000..261d170 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrd.java @@ -0,0 +1,32 @@ +package wellatleastitried.mediagarrdServer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.scheduling.annotation.EnableScheduling; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.core.DefaultDockerClientConfig; +import com.github.dockerjava.core.DockerClientImpl; +import com.github.dockerjava.httpclient5.ApacheDockerHttpClient; + +@SpringBootApplication +@EnableScheduling +@EnableConfigurationProperties(MediaGarrdProperties.class) +public class MediaGarrd { + + public static void main(String[] args) { + SpringApplication.run(MediaGarrd.class, args); + } + + @Bean + DockerClient dockerClient() { + var config = DefaultDockerClientConfig.createDefaultConfigBuilder().build(); + var httpClient = new ApacheDockerHttpClient.Builder() + .dockerHost(config.getDockerHost()) + .sslConfig(config.getSSLConfig()) + .build(); + return DockerClientImpl.getInstance(config, httpClient); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java new file mode 100644 index 0000000..b9a7254 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -0,0 +1,25 @@ +package wellatleastitried.mediagarrdServer; + +import java.time.Duration; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@ConfigurationProperties(prefix = "mediagarrd") +public class MediaGarrdProperties { + + private Duration backupInterval = Duration.ofHours(12); + private String backupRoot = "/var/lib/mediagarrd/backups"; + private int retentionCount = 10; + private String databasePath = "/var/lib/mediagarrd/db/mediagarrd.db"; + private int compressionLevel = 1; + private String helperImage = "busybox:stable"; + private String updateRepository = "MediaGarrd/Server"; + private String githubApiBaseUrl = "https://api.github.com"; + private Duration updateCheckInterval = Duration.ofHours(24); + private boolean openPairing = false; +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/WebMvcConfig.java b/src/main/java/wellatleastitried/mediagarrdServer/WebMvcConfig.java new file mode 100644 index 0000000..7d9e83c --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/WebMvcConfig.java @@ -0,0 +1,32 @@ +package wellatleastitried.mediagarrdServer; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import wellatleastitried.mediagarrdServer.api.ApiAuthInterceptor; +import wellatleastitried.mediagarrdServer.api.SetupInterceptor; + +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + + private final SetupInterceptor setupInterceptor; + private final ApiAuthInterceptor apiAuthInterceptor; + + public WebMvcConfig(SetupInterceptor setupInterceptor, ApiAuthInterceptor apiAuthInterceptor) { + this.setupInterceptor = setupInterceptor; + this.apiAuthInterceptor = apiAuthInterceptor; + } + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/config").setViewName("forward:/config.html"); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(setupInterceptor).addPathPatterns(SetupInterceptor.SETUP_PAGE_PATTERNS); + registry.addInterceptor(apiAuthInterceptor).addPathPatterns("/api/v1/**"); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/ApiAuthInterceptor.java b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiAuthInterceptor.java new file mode 100644 index 0000000..0b16d7b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiAuthInterceptor.java @@ -0,0 +1,93 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.io.IOException; +import java.util.Locale; +import java.util.Map; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerInterceptor; + +import tools.jackson.databind.json.JsonMapper; + +import jakarta.servlet.DispatcherType; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import wellatleastitried.mediagarrdServer.model.PairedClient; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@Component +public class ApiAuthInterceptor implements HandlerInterceptor { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + static final String CLIENT_ID_ATTRIBUTE = "mediagarrd.clientId"; + private static final String BEARER_PREFIX = "bearer "; + private static final String SETUP_MESSAGE = "Setup session required, reload /config and enter the PIN from the server logs"; + private static final String UNFINISHED_MESSAGE = "Setup is not finished, open /config and finish it first, then pair this client"; + private static final String MISSING_MESSAGE = "Authorization required, pair this client and send Authorization: Bearer "; + private static final String INVALID_MESSAGE = "Invalid or revoked token, pair this client again"; + + private final SetupService setup; + private final PairingService pairing; + + public ApiAuthInterceptor(SetupService setup, PairingService pairing) { + this.setup = setup; + this.pairing = pairing; + } + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { + if (request.getDispatcherType() != DispatcherType.REQUEST) { + return true; + } + HandlerMethod method = handler instanceof HandlerMethod handlerMethod ? handlerMethod : null; + PublicEndpoint open = method == null ? null : method.getMethodAnnotation(PublicEndpoint.class); + boolean setupAllowed = method != null && method.hasMethodAnnotation(SetupSessionAllowed.class); + String header = request.getHeader(HttpHeaders.AUTHORIZATION); + + if (open != null && (!open.tokenOptional() || header == null)) { + return true; + } + boolean setupOpen = setupAllowed && !setup.isCompleted(); + if (setupOpen && setup.canConfigure(SetupInterceptor.sessionToken(request))) { + return true; + } + if (header == null) { + return reject(response, rejection(setupAllowed, MISSING_MESSAGE)); + } + String token = bearerToken(header); + PairedClient client = token == null ? null : pairing.authenticate(token).orElse(null); + if (client == null) { + return reject(response, INVALID_MESSAGE); + } + request.setAttribute(CLIENT_ID_ATTRIBUTE, client.id()); + return true; + } + + private String rejection(boolean setupAllowed, String pairedMessage) { + if (setup.isCompleted()) { + return pairedMessage; + } + return setupAllowed ? SETUP_MESSAGE : UNFINISHED_MESSAGE; + } + + private static String bearerToken(String header) { + String value = header.strip(); + if (value.length() <= BEARER_PREFIX.length() || !value.toLowerCase(Locale.ROOT).startsWith(BEARER_PREFIX)) { + return null; + } + return value.substring(BEARER_PREFIX.length()).strip(); + } + + private static boolean reject(HttpServletResponse response, String message) throws IOException { + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer"); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.getWriter().write(JSON.writeValueAsString(Map.of("error", message))); + return false; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/ApiErrorController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiErrorController.java new file mode 100644 index 0000000..c6d4ca6 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiErrorController.java @@ -0,0 +1,30 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.util.Map; + +import org.springframework.boot.webmvc.error.ErrorController; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.http.HttpServletRequest; + +@RestController +public class ApiErrorController implements ErrorController { + + @RequestMapping("/error") + public ResponseEntity> error(HttpServletRequest request) { + HttpStatus status = statusOf(request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)); + return ApiExceptionHandler.error(status, status.is4xxClientError() ? status.getReasonPhrase() : ApiExceptionHandler.INTERNAL_ERROR); + } + + private static HttpStatus statusOf(Object code) { + if (code == null) { + return HttpStatus.NOT_FOUND; + } + HttpStatus status = code instanceof Integer value ? HttpStatus.resolve(value) : null; + return status != null && status.isError() ? status : HttpStatus.INTERNAL_SERVER_ERROR; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandler.java b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandler.java new file mode 100644 index 0000000..33c4dc6 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandler.java @@ -0,0 +1,148 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.io.EOFException; +import java.time.Duration; +import java.util.Map; +import java.util.Objects; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.beans.TypeMismatchException; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.ErrorResponse; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.async.AsyncRequestNotUsableException; +import org.springframework.web.context.request.async.AsyncRequestTimeoutException; + +import jakarta.servlet.http.HttpServletResponse; + +import wellatleastitried.mediagarrdServer.service.BackupFailedException; +import wellatleastitried.mediagarrdServer.service.BackupInProgressException; +import wellatleastitried.mediagarrdServer.service.BackupNotFoundException; +import wellatleastitried.mediagarrdServer.service.LockedOutException; +import wellatleastitried.mediagarrdServer.service.PairingException; +import wellatleastitried.mediagarrdServer.service.RateLimitedException; +import wellatleastitried.mediagarrdServer.service.RunRejectedException; +import wellatleastitried.mediagarrdServer.service.ServiceConflictException; +import wellatleastitried.mediagarrdServer.service.ServiceNotFoundException; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; + +@RestControllerAdvice +public class ApiExceptionHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(ApiExceptionHandler.class); + static final String INTERNAL_ERROR = "Internal error"; + + @ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class}) + public ResponseEntity> handle(RuntimeException e) { + HttpStatus status = e instanceof IllegalArgumentException ? HttpStatus.BAD_REQUEST + : e instanceof RunRejectedException || e instanceof BackupInProgressException ? HttpStatus.CONFLICT + : HttpStatus.INTERNAL_SERVER_ERROR; + if (e instanceof BackupFailedException) { + LOGGER.error("Request failed: {}", e.getMessage()); + return error(status, e.getMessage()); + } + if (status.is5xxServerError()) { + LOGGER.error("Request failed", e); + return error(status, INTERNAL_ERROR); + } + LOGGER.warn("Rejected request: {}", LogSanitizer.clean(e.getMessage())); + return error(status, e.getMessage()); + } + + @ExceptionHandler(ServiceConflictException.class) + public ResponseEntity> serviceConflict(ServiceConflictException e) { + LOGGER.warn("Rejected request: {}", LogSanitizer.clean(e.getMessage())); + return error(HttpStatus.CONFLICT, e.getMessage()); + } + + @ExceptionHandler({ServiceNotFoundException.class, BackupNotFoundException.class}) + public ResponseEntity> notFound(RuntimeException e) { + LOGGER.warn("Rejected request: {}", LogSanitizer.clean(e.getMessage())); + return error(HttpStatus.NOT_FOUND, e.getMessage()); + } + + @ExceptionHandler(LockedOutException.class) + public ResponseEntity> locked(LockedOutException e) { + LOGGER.warn("Rejected request: {}", e.getMessage()); + return tooManyRequests(e.getMessage(), e.retryAfter()); + } + + @ExceptionHandler(RateLimitedException.class) + public ResponseEntity> rateLimited(RateLimitedException e) { + LOGGER.warn("Rejected request: {}", e.getMessage()); + return tooManyRequests(e.getMessage(), e.retryAfter()); + } + + private static ResponseEntity> tooManyRequests(String message, Duration retryAfter) { + return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS) + .header(HttpHeaders.RETRY_AFTER, String.valueOf(Math.max(1, retryAfter.toSeconds()))) + .contentType(MediaType.APPLICATION_JSON) + .body(Map.of("error", message)); + } + + @ExceptionHandler(PairingException.class) + public ResponseEntity> pairingRejected(PairingException e) { + HttpStatus status = switch (e.reason()) { + case SETUP_INCOMPLETE -> HttpStatus.CONFLICT; + case CLOSED -> HttpStatus.FORBIDDEN; + case INVALID -> HttpStatus.UNAUTHORIZED; + }; + LOGGER.warn("Rejected pairing request: {}", LogSanitizer.clean(e.getMessage())); + return error(status, e.getMessage()); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseEntity> unreadableBody(HttpMessageNotReadableException e) { + return error(HttpStatus.BAD_REQUEST, "Request body is missing or not valid JSON"); + } + + @ExceptionHandler(TypeMismatchException.class) + public ResponseEntity> badParameter(TypeMismatchException e) { + return error(HttpStatus.BAD_REQUEST, "Request parameter is not valid"); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity> unexpected(Exception e, HttpServletResponse response) { + if (response.isCommitted()) { + if (isClientGone(e)) { + LOGGER.debug("Request ended after the response was started: {}", e.toString()); + } else { + LOGGER.warn("Request failed after the response was started", e); + } + return null; + } + if (e instanceof ErrorResponse rejected && rejected.getStatusCode().is4xxClientError()) { + HttpStatus status = HttpStatus.valueOf(rejected.getStatusCode().value()); + LOGGER.warn("Rejected request: {}", status.getReasonPhrase()); + return ResponseEntity.status(status) + .headers(rejected.getHeaders()) + .contentType(MediaType.APPLICATION_JSON) + .body(Map.of("error", status.getReasonPhrase())); + } + LOGGER.error("Request failed", e); + HttpStatus status = e instanceof ErrorResponse failed && failed.getStatusCode().is5xxServerError() + ? HttpStatus.valueOf(failed.getStatusCode().value()) + : HttpStatus.INTERNAL_SERVER_ERROR; + return error(status, INTERNAL_ERROR); + } + + private static boolean isClientGone(Throwable e) { + for (Throwable cause = e; cause != null; cause = cause.getCause() == cause ? null : cause.getCause()) { + if (cause instanceof AsyncRequestNotUsableException || cause instanceof AsyncRequestTimeoutException + || cause instanceof EOFException || cause.getClass().getSimpleName().equals("ClientAbortException")) { + return true; + } + } + return false; + } + + static ResponseEntity> error(HttpStatus status, String message) { + return ResponseEntity.status(status).contentType(MediaType.APPLICATION_JSON).body(Map.of("error", Objects.requireNonNullElse(message, status.getReasonPhrase()))); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java similarity index 50% rename from src/main/java/wellatleastitried/mediagarrd/api/BackupController.java rename to src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java index 92d11d0..1008f52 100644 --- a/src/main/java/wellatleastitried/mediagarrd/api/BackupController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java @@ -1,13 +1,17 @@ -package wellatleastitried.mediagarrd.api; +package wellatleastitried.mediagarrdServer.api; + +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.getDurationMs; import java.io.IOException; import java.time.Duration; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; +import org.springframework.http.ContentDisposition; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; @@ -15,23 +19,23 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ResponseStatusException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import wellatleastitried.mediagarrd.MediaGarrdProperties; -import wellatleastitried.mediagarrd.dto.BackupDto; -import wellatleastitried.mediagarrd.dto.BackupRunDto; -import wellatleastitried.mediagarrd.dto.ScheduleUpdateRequest; -import wellatleastitried.mediagarrd.dto.ServerStatusDto; -import wellatleastitried.mediagarrd.model.BackupArchive; -import wellatleastitried.mediagarrd.model.BackupRunResult; -import wellatleastitried.mediagarrd.service.BackupArchiveService; -import wellatleastitried.mediagarrd.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.dto.BackupDto; +import wellatleastitried.mediagarrdServer.dto.BackupRunDto; +import wellatleastitried.mediagarrdServer.dto.PublicHealthDto; +import wellatleastitried.mediagarrdServer.dto.ScheduleUpdateRequest; +import wellatleastitried.mediagarrdServer.dto.ServerStatusDto; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupNotFoundException; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; @RestController @RequestMapping("/api/v1") @@ -41,92 +45,83 @@ public class BackupController { private final BackupArchiveService archiveService; private final BackupOrchestratorService orchestratorService; - private final MediaGarrdProperties properties; + private final RunStatusBroadcaster broadcaster; - public BackupController( - BackupArchiveService archiveService, - BackupOrchestratorService orchestratorService, - MediaGarrdProperties properties - ) { + public BackupController(BackupArchiveService archiveService, BackupOrchestratorService orchestratorService, RunStatusBroadcaster broadcaster) { this.archiveService = archiveService; this.orchestratorService = orchestratorService; - this.properties = properties; + this.broadcaster = broadcaster; } + @PublicEndpoint(tokenOptional = true) @GetMapping("/health") - public ServerStatusDto health() { - LOGGER.info("GET /api/v1/health, running={}, interval={}", orchestratorService.isRunning(), orchestratorService.getInterval()); - return new ServerStatusDto( - true, - orchestratorService.isRunning(), - properties.getRetentionCount(), - orchestratorService.getInterval() - ); + public Object health(@RequestAttribute(name = ApiAuthInterceptor.CLIENT_ID_ATTRIBUTE, required = false) String clientId) { + LOGGER.debug("GET /api/v1/health, running={}, interval={}", orchestratorService.isRunning(), orchestratorService.getInterval()); + if (clientId == null) { + return new PublicHealthDto(true, orchestratorService.getInterval()); + } + return status(orchestratorService.getInterval()); } + @SetupSessionAllowed @PutMapping("/schedule") public ServerStatusDto updateSchedule(@RequestBody ScheduleUpdateRequest request) { LOGGER.info("PUT /api/v1/schedule, requestedInterval={}", request.backupInterval()); Duration updated = orchestratorService.updateInterval(request.backupInterval()); LOGGER.info("Schedule updated: newInterval={}", updated); - return new ServerStatusDto( - true, - orchestratorService.isRunning(), - properties.getRetentionCount(), - updated - ); + broadcaster.publishConfigChanged(); + return status(updated); } @GetMapping("/backups") public List listBackups() { - LOGGER.info("GET /api/v1/backups"); + LOGGER.debug("GET /api/v1/backups"); List backups = archiveService.listArchives().stream().map(this::toDto).toList(); - LOGGER.info("Returning {} backup(s)", backups.size()); + LOGGER.debug("Returning {} backup(s)", backups.size()); return backups; } @GetMapping("/backups/latest") public BackupDto latestBackup() { - LOGGER.info("GET /api/v1/backups/latest"); + LOGGER.debug("GET /api/v1/backups/latest"); BackupArchive archive = archiveService.latest() - .orElseThrow(() -> notFound("No backup archives found")); - LOGGER.info("Latest backup: {}", archive.fileName()); + .orElseThrow(() -> new BackupNotFoundException("No backup archives found")); + LOGGER.debug("Latest backup: {}", archive.fileName()); return toDto(archive); } @GetMapping("/backups/{id}") public BackupDto backupById(@PathVariable String id) { - LOGGER.info("GET /api/v1/backups/{}", id); + LOGGER.debug("GET /api/v1/backups/{}", LogSanitizer.clean(id)); return archiveService.byId(id) .map(this::toDto) - .orElseThrow(() -> notFound("Backup not found: " + id, "Backup not found")); + .orElseThrow(() -> new BackupNotFoundException("Backup not found")); } @GetMapping("/backups/{id}/download") public ResponseEntity downloadById(@PathVariable String id) { - LOGGER.info("GET /api/v1/backups/{}/download", id); + LOGGER.debug("GET /api/v1/backups/{}/download", LogSanitizer.clean(id)); BackupArchive archive = archiveService.byId(id) - .orElseThrow(() -> notFound("Download requested for missing backup: " + id, "Backup not found")); + .orElseThrow(() -> new BackupNotFoundException("Backup not found")); return downloadResponse(archive); } @GetMapping("/backups/latest/download") public ResponseEntity downloadLatest() { - LOGGER.info("GET /api/v1/backups/latest/download"); + LOGGER.debug("GET /api/v1/backups/latest/download"); BackupArchive archive = archiveService.latest() - .orElseThrow(() -> notFound("Download requested but no archives exist", "No backup archives found")); + .orElseThrow(() -> new BackupNotFoundException("No backup archives found")); return downloadResponse(archive); } @DeleteMapping("/backups/{id}") public ResponseEntity deleteBackup(@PathVariable String id) { - LOGGER.info("DELETE /api/v1/backups/{}", id); - boolean deleted = archiveService.deleteById(id); - if (!deleted) { - LOGGER.warn("Delete failed: backup not found: {}", id); - return ResponseEntity.notFound().build(); + LOGGER.info("DELETE /api/v1/backups/{}", LogSanitizer.clean(id)); + if (!archiveService.deleteById(id)) { + throw new BackupNotFoundException("Backup not found"); } - LOGGER.info("Backup deleted: {}", id); + LOGGER.info("Backup deleted: {}", LogSanitizer.clean(id)); + broadcaster.publishBackupsChanged(); return ResponseEntity.noContent().build(); } @@ -134,14 +129,15 @@ public ResponseEntity deleteBackup(@PathVariable String id) { public BackupRunDto runBackup() { LOGGER.info("POST /api/v1/backups/run, triggering manual backup"); BackupRunResult result = orchestratorService.runBackup(); + var backupDuration = getDurationMs(result.startTime(), result.endTime()); LOGGER.info("Manual backup complete: runId={}, services={}, archive={}, duration={}ms", - result.runId(), result.servicesRan(), result.archive().fileName(), - result.finishedAt().toEpochMilli() - result.startedAt().toEpochMilli()); + result.runId(), result.serviceNames(), result.archive().fileName(), + backupDuration); return new BackupRunDto( result.runId(), - result.startedAt(), - result.finishedAt(), - result.servicesRan(), + result.startTime(), + result.endTime(), + result.serviceNames(), toDto(result.archive()) ); } @@ -149,33 +145,27 @@ public BackupRunDto runBackup() { private ResponseEntity downloadResponse(BackupArchive archive) { Resource file = new FileSystemResource(archive.path()); if (!file.exists()) { - LOGGER.error("Archive file missing on disk: {}", archive.path()); - throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Backup file missing on disk"); + LOGGER.error("Archive file missing on disk: {}", LogSanitizer.clean(archive.path())); + throw new BackupNotFoundException("Backup file missing on disk"); } try { LOGGER.info("Serving download: {} ({} bytes)", archive.fileName(), archive.sizeBytes()); return ResponseEntity.ok() - .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + archive.fileName() + "\"") + .header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment().filename(archive.fileName()).build().toString()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .contentLength(file.contentLength()) .body(file); } catch (IOException e) { - LOGGER.error("Failed to read backup file: {}", archive.path(), e); - throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to read backup file"); + throw new IllegalStateException("Failed to read backup file", e); } } - private BackupDto toDto(BackupArchive archive) { - return new BackupDto(archive.id(), archive.fileName(), archive.sizeBytes(), archive.createdAt()); + private ServerStatusDto status(Duration interval) { + return new ServerStatusDto(true, orchestratorService.isRunning(), archiveService.retentionCount(), interval); } - private ResponseStatusException notFound(String logMessage) { - return notFound(logMessage, logMessage); - } - - private ResponseStatusException notFound(String logMessage, String responseMessage) { - LOGGER.warn(logMessage); - return new ResponseStatusException(HttpStatus.NOT_FOUND, responseMessage); + private BackupDto toDto(BackupArchive archive) { + return new BackupDto(archive.id(), archive.fileName(), archive.sizeBytes(), archive.createdAt()); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java new file mode 100644 index 0000000..f152815 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java @@ -0,0 +1,113 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdServer.dto.ConfigUpdateRequest; +import wellatleastitried.mediagarrdServer.dto.ServerConfigDto; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.service.BackupRunLifecycle; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.ServiceConfigService; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; + +@RestController +@RequestMapping("/api/v1") +public class ConfigController { + + private static final Logger LOGGER = LoggerFactory.getLogger(ConfigController.class); + + private final BackupArchiveService archiveService; + private final BackupOrchestratorService orchestrator; + private final BackupRunLifecycle lifecycle; + private final ServiceConfigService serviceConfig; + private final RunStatusBroadcaster broadcaster; + + public ConfigController( + BackupArchiveService archiveService, + BackupOrchestratorService orchestrator, + BackupRunLifecycle lifecycle, + ServiceConfigService serviceConfig, + RunStatusBroadcaster broadcaster + ) { + this.archiveService = archiveService; + this.orchestrator = orchestrator; + this.lifecycle = lifecycle; + this.serviceConfig = serviceConfig; + this.broadcaster = broadcaster; + } + + @SetupSessionAllowed + @GetMapping("/config") + public ServerConfigDto config() { + LOGGER.debug("GET /api/v1/config"); + return currentConfig(); + } + + @SetupSessionAllowed + @PutMapping("/config") + public ServerConfigDto updateConfig(@RequestBody ConfigUpdateRequest request) { + LOGGER.info("PUT /api/v1/config, backupLocation={}, retentionCount={}", LogSanitizer.clean(request.backupLocation()), request.retentionCount()); + return lifecycle.whileIdle(() -> { + archiveService.updateSettings(request.backupLocation(), request.retentionCount()); + if (request.backupLocation() != null) { + broadcaster.publishBackupsChanged(); + } + broadcaster.publishConfigChanged(); + return currentConfig(); + }); + } + + @SetupSessionAllowed + @GetMapping("/services") + public List services() { + LOGGER.debug("GET /api/v1/services"); + return serviceConfig.list(); + } + + @SetupSessionAllowed + @PostMapping("/services") + public ResponseEntity addService(@RequestBody ServiceDefinition request) { + ServiceDefinition service = request.validate(); + LOGGER.info("POST /api/v1/services, name={}, paths={}", LogSanitizer.clean(service.name()), LogSanitizer.clean(service.paths())); + return ResponseEntity.status(HttpStatus.CREATED).body(serviceConfig.add(service)); + } + + @SetupSessionAllowed + @PutMapping("/services/{name}") + public ResponseEntity updateService(@PathVariable String name, @RequestBody ServiceDefinition request) { + ServiceDefinition service = request.validate(); + LOGGER.info("PUT /api/v1/services/{}, name={}, paths={}", LogSanitizer.clean(name), LogSanitizer.clean(service.name()), LogSanitizer.clean(service.paths())); + return ResponseEntity.ok(serviceConfig.update(name, service)); + } + + @SetupSessionAllowed + @DeleteMapping("/services/{name}") + public ResponseEntity removeService(@PathVariable String name) { + LOGGER.info("DELETE /api/v1/services/{}", LogSanitizer.clean(name)); + serviceConfig.remove(name); + return ResponseEntity.noContent().build(); + } + + private ServerConfigDto currentConfig() { + return new ServerConfigDto( + archiveService.rootDirectory().toString(), + archiveService.retentionCount(), + orchestrator.getInterval() + ); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/PairingController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/PairingController.java new file mode 100644 index 0000000..05e8339 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/PairingController.java @@ -0,0 +1,67 @@ +package wellatleastitried.mediagarrdServer.api; + +import static wellatleastitried.mediagarrdServer.api.ApiExceptionHandler.error; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestAttribute; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdServer.dto.PairRequest; +import wellatleastitried.mediagarrdServer.dto.PairResponse; +import wellatleastitried.mediagarrdServer.dto.PairedClientDto; +import wellatleastitried.mediagarrdServer.dto.PairingCodeDto; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; + +@RestController +@RequestMapping("/api/v1") +public class PairingController { + + private static final Logger LOGGER = LoggerFactory.getLogger(PairingController.class); + + private final PairingService pairing; + + public PairingController(PairingService pairing) { + this.pairing = pairing; + } + + @PublicEndpoint + @PostMapping("/pair") + public PairResponse pair(@RequestBody PairRequest request) { + LOGGER.info("POST /api/v1/pair"); + return pairing.pair(request.pin(), request.name()); + } + + @PostMapping("/pairing-codes") + public PairingCodeDto createCode() { + LOGGER.info("POST /api/v1/pairing-codes"); + return pairing.createCode(); + } + + @GetMapping("/clients") + public List clients(@RequestAttribute(ApiAuthInterceptor.CLIENT_ID_ATTRIBUTE) String currentId) { + return pairing.list().stream() + .map(client -> new PairedClientDto(client.id(), client.name(), client.createdAt(), client.lastUsedAt(), client.id().equals(currentId))) + .toList(); + } + + @DeleteMapping("/clients/{id}") + public ResponseEntity revoke(@PathVariable String id) { + LOGGER.info("DELETE /api/v1/clients/{}", LogSanitizer.clean(id)); + if (!pairing.revoke(id)) { + return error(HttpStatus.NOT_FOUND, "Client not found"); + } + return ResponseEntity.noContent().build(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/PublicEndpoint.java b/src/main/java/wellatleastitried/mediagarrdServer/api/PublicEndpoint.java new file mode 100644 index 0000000..721d8f1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/PublicEndpoint.java @@ -0,0 +1,15 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface PublicEndpoint { + + boolean tokenOptional() default false; +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/RequestBodyLimitFilter.java b/src/main/java/wellatleastitried/mediagarrdServer/api/RequestBodyLimitFilter.java new file mode 100644 index 0000000..631d442 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/RequestBodyLimitFilter.java @@ -0,0 +1,139 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.io.ByteArrayInputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Set; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ReadListener; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletResponse; +import tools.jackson.databind.json.JsonMapper; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE + 1) +public class RequestBodyLimitFilter extends OncePerRequestFilter { + + public static final int MAX_BODY_BYTES = 64 * 1024; + static final String MESSAGE = "Request body is too large"; + static final String UNSUPPORTED_CHARSET_MESSAGE = "Unsupported charset in Content-Type"; + private static final Set BODYLESS_METHODS = Set.of("GET", "HEAD", "OPTIONS", "TRACE"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + return BODYLESS_METHODS.contains(request.getMethod()); + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + if (request.getContentLengthLong() > MAX_BODY_BYTES) { + reject(response); + return; + } + if (request.getCharacterEncoding() != null && charset(request.getCharacterEncoding()) == null) { + response.setStatus(HttpStatus.BAD_REQUEST.value()); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.getWriter().write(JSON.writeValueAsString(Map.of("error", UNSUPPORTED_CHARSET_MESSAGE))); + return; + } + byte[] body = request.getInputStream().readNBytes(MAX_BODY_BYTES + 1); + if (body.length > MAX_BODY_BYTES) { + reject(response); + return; + } + chain.doFilter(new BufferedBodyRequest(request, body), response); + } + + private static Charset charset(String name) { + try { + return Charset.forName(name); + } catch (IllegalArgumentException e) { + return null; + } + } + + private static void reject(HttpServletResponse response) throws IOException { + response.setStatus(HttpStatus.CONTENT_TOO_LARGE.value()); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setHeader("Connection", "close"); + response.getWriter().write(JSON.writeValueAsString(Map.of("error", MESSAGE))); + } + + private static final class BufferedBodyRequest extends HttpServletRequestWrapper { + + private final byte[] body; + + BufferedBodyRequest(HttpServletRequest request, byte[] body) { + super(request); + this.body = body; + } + + @Override + public ServletInputStream getInputStream() { + ByteArrayInputStream source = new ByteArrayInputStream(body); + return new ServletInputStream() { + @Override + public int read() { + return source.read(); + } + + @Override + public int read(byte[] buffer, int offset, int length) { + return source.read(buffer, offset, length); + } + + @Override + public boolean isFinished() { + return source.available() == 0; + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setReadListener(ReadListener listener) { + throw new IllegalStateException("Asynchronous reads are not supported"); + } + }; + } + + @Override + public BufferedReader getReader() { + String encoding = getCharacterEncoding(); + Charset charset = encoding == null ? null : charset(encoding); + if (charset == null) { + charset = StandardCharsets.UTF_8; + } + return new BufferedReader(new InputStreamReader(getInputStream(), charset)); + } + + @Override + public int getContentLength() { + return body.length; + } + + @Override + public long getContentLengthLong() { + return body.length; + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java new file mode 100644 index 0000000..e82f3c0 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java @@ -0,0 +1,56 @@ +package wellatleastitried.mediagarrdServer.api; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.async.AsyncRequestNotUsableException; +import org.springframework.web.context.request.async.AsyncRequestTimeoutException; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import jakarta.servlet.http.HttpServletResponse; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster.SubscriberLimitException; + +@RestController +@RequestMapping("/api/v1") +public class RunEventsController { + + private static final Logger LOGGER = LoggerFactory.getLogger(RunEventsController.class); + + private final RunStatusBroadcaster broadcaster; + private final PairingService pairing; + + public RunEventsController(RunStatusBroadcaster broadcaster, PairingService pairing) { + this.broadcaster = broadcaster; + this.pairing = pairing; + } + + @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public ResponseEntity events(@RequestAttribute(ApiAuthInterceptor.CLIENT_ID_ATTRIBUTE) String clientId) { + try { + SseEmitter emitter = broadcaster.subscribe(clientId); + if (!pairing.isPaired(clientId)) { + broadcaster.closeClient(clientId); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + return ResponseEntity.ok() + .header("X-Accel-Buffering", "no") + .body(emitter); + } catch (SubscriberLimitException e) { + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).build(); + } + } + + @ExceptionHandler({AsyncRequestTimeoutException.class, AsyncRequestNotUsableException.class}) + public void streamEnded(Exception e, HttpServletResponse response) { + LOGGER.debug("Event stream ended: {}", e.toString()); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/SecurityHeadersFilter.java b/src/main/java/wellatleastitried/mediagarrdServer/api/SecurityHeadersFilter.java new file mode 100644 index 0000000..6b8d5c7 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/SecurityHeadersFilter.java @@ -0,0 +1,44 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.io.IOException; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +public class SecurityHeadersFilter extends OncePerRequestFilter { + + static final String CONTENT_SECURITY_POLICY = "default-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"; + private static final String[] CACHEABLE_PREFIXES = {"/css/", "/js/"}; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + response.setHeader("X-Frame-Options", "DENY"); + response.setHeader("Content-Security-Policy", CONTENT_SECURITY_POLICY); + response.setHeader("X-Content-Type-Options", "nosniff"); + response.setHeader("Referrer-Policy", "no-referrer"); + if (!cacheable(request.getRequestURI())) { + response.setHeader(HttpHeaders.CACHE_CONTROL, "no-store"); + } + chain.doFilter(request, response); + } + + private static boolean cacheable(String uri) { + for (String prefix : CACHEABLE_PREFIXES) { + if (uri.startsWith(prefix)) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/SetupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupController.java new file mode 100644 index 0000000..9f95f09 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupController.java @@ -0,0 +1,98 @@ +package wellatleastitried.mediagarrdServer.api; + +import static wellatleastitried.mediagarrdServer.api.ApiExceptionHandler.error; +import static wellatleastitried.mediagarrdServer.api.SetupInterceptor.SESSION_COOKIE; + +import java.util.Optional; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseCookie; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import jakarta.servlet.http.HttpServletRequest; +import wellatleastitried.mediagarrdServer.dto.SetupCompleteDto; +import wellatleastitried.mediagarrdServer.dto.SetupSessionRequest; +import wellatleastitried.mediagarrdServer.dto.SetupStatusDto; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; +import wellatleastitried.mediagarrdServer.service.SetupAlreadyCompleteException; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@RestController +@RequestMapping("/api/v1/setup") +public class SetupController { + + private static final Logger LOGGER = LoggerFactory.getLogger(SetupController.class); + + private final SetupService setup; + private final ServiceRepository services; + + public SetupController(SetupService setup, ServiceRepository services) { + this.setup = setup; + this.services = services; + } + + @PublicEndpoint + @GetMapping + public SetupStatusDto status(HttpServletRequest request) { + return new SetupStatusDto(setup.isCompleted(), setup.canConfigure(SetupInterceptor.sessionToken(request))); + } + + @PublicEndpoint + @PostMapping("/session") + public ResponseEntity startSession(@RequestBody SetupSessionRequest request, HttpServletRequest http) { + LOGGER.info("POST /api/v1/setup/session"); + if (setup.isCompleted()) { + return error(HttpStatus.GONE, "Setup is already complete"); + } + Optional session = setup.startSession(request.pin()); + if (session.isEmpty()) { + return error(HttpStatus.UNAUTHORIZED, "Invalid PIN, check the server logs for the current PIN"); + } + return ResponseEntity.noContent().header(HttpHeaders.SET_COOKIE, cookie(session.get(), -1, http).toString()).build(); + } + + @SetupSessionAllowed + @PostMapping("/complete") + public ResponseEntity complete(HttpServletRequest http) { + LOGGER.info("POST /api/v1/setup/complete"); + if (setup.isCompleted()) { + return error(HttpStatus.GONE, "Setup is already complete"); + } + if (services.fetchServices().isEmpty()) { + return error(HttpStatus.CONFLICT, "Add at least one service before finishing setup"); + } + String pairingPin; + try { + pairingPin = setup.complete(); + } catch (SetupAlreadyCompleteException e) { + return error(HttpStatus.GONE, "Setup is already complete"); + } + return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie("", 0, http).toString()).body(new SetupCompleteDto(pairingPin)); + } + + private static boolean secure(HttpServletRequest request) { + return request.isSecure() || forwardedHttps(request.getHeader("X-Forwarded-Proto")); + } + + private static boolean forwardedHttps(String header) { + return header != null && "https".equalsIgnoreCase(header.split(",")[0].strip()); + } + + private static ResponseCookie cookie(String value, long maxAgeSeconds, HttpServletRequest request) { + return ResponseCookie.from(SESSION_COOKIE, value) + .httpOnly(true) + .secure(secure(request)) + .sameSite("Strict") + .path("/") + .maxAge(maxAgeSeconds) + .build(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java new file mode 100644 index 0000000..5265b88 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java @@ -0,0 +1,47 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.io.IOException; +import java.util.Arrays; + +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@Component +public class SetupInterceptor implements HandlerInterceptor { + + static final String SESSION_COOKIE = "mediagarrd-setup"; + public static final String[] SETUP_PAGE_PATTERNS = {"/config", "/config.html", "/css/**", "/js/**"}; + + private final SetupService setup; + + public SetupInterceptor(SetupService setup) { + this.setup = setup; + } + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { + if (setup.isCompleted()) { + response.sendError(HttpStatus.NOT_FOUND.value()); + return false; + } + return true; + } + + static String sessionToken(HttpServletRequest request) { + Cookie[] cookies = request.getCookies(); + if (cookies == null) { + return null; + } + return Arrays.stream(cookies) + .filter(cookie -> SESSION_COOKIE.equals(cookie.getName())) + .map(Cookie::getValue) + .findFirst() + .orElse(null); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/SetupSessionAllowed.java b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupSessionAllowed.java new file mode 100644 index 0000000..9c14b90 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupSessionAllowed.java @@ -0,0 +1,13 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface SetupSessionAllowed { +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java new file mode 100644 index 0000000..57f640f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java @@ -0,0 +1,25 @@ +package wellatleastitried.mediagarrdServer.api; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdServer.dto.VersionStatusDto; +import wellatleastitried.mediagarrdServer.service.UpdateCheckService; + +@RestController +@RequestMapping("/api/v1") +public class VersionController { + + private final UpdateCheckService updateCheckService; + + public VersionController(UpdateCheckService updateCheckService) { + this.updateCheckService = updateCheckService; + } + + @PublicEndpoint + @GetMapping("/version") + public VersionStatusDto version() { + return updateCheckService.status(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/WebhookController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/WebhookController.java new file mode 100644 index 0000000..4305cc5 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/WebhookController.java @@ -0,0 +1,54 @@ +package wellatleastitried.mediagarrdServer.api; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdServer.dto.WebhookStatusDto; +import wellatleastitried.mediagarrdServer.dto.WebhookTestDto; +import wellatleastitried.mediagarrdServer.dto.WebhookUpdateRequest; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.WebhookService; + +@RestController +@RequestMapping("/api/v1/notifications/webhook") +public class WebhookController { + + private static final Logger LOGGER = LoggerFactory.getLogger(WebhookController.class); + + private final WebhookService webhook; + private final RunStatusBroadcaster broadcaster; + + public WebhookController(WebhookService webhook, RunStatusBroadcaster broadcaster) { + this.webhook = webhook; + this.broadcaster = broadcaster; + } + + @SetupSessionAllowed + @GetMapping + public WebhookStatusDto status() { + LOGGER.debug("GET /api/v1/notifications/webhook"); + return webhook.status(); + } + + @SetupSessionAllowed + @PutMapping + public WebhookStatusDto update(@RequestBody WebhookUpdateRequest request) { + LOGGER.info("PUT /api/v1/notifications/webhook"); + WebhookStatusDto updated = webhook.update(request.url()); + broadcaster.publishConfigChanged(); + return updated; + } + + @SetupSessionAllowed + @PostMapping("/test") + public WebhookTestDto test() { + LOGGER.info("POST /api/v1/notifications/webhook/test"); + return webhook.test(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java similarity index 71% rename from src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java rename to src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java index e3932d2..7753414 100644 --- a/src/main/java/wellatleastitried/mediagarrd/dto/BackupDto.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupDto.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.dto; +package wellatleastitried.mediagarrdServer.dto; import java.time.Instant; @@ -7,5 +7,4 @@ public record BackupDto( String fileName, long sizeBytes, Instant createdAt -) { -} +) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java similarity index 50% rename from src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java rename to src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java index e745805..471af38 100644 --- a/src/main/java/wellatleastitried/mediagarrd/dto/BackupRunDto.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/BackupRunDto.java @@ -1,13 +1,11 @@ -package wellatleastitried.mediagarrd.dto; +package wellatleastitried.mediagarrdServer.dto; -import java.time.Instant; import java.util.List; public record BackupRunDto( String runId, - Instant startedAt, - Instant finishedAt, + String startTime, + String endTime, List servicesRan, BackupDto archive -) { -} +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/CheckState.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/CheckState.java new file mode 100644 index 0000000..96f73ce --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/CheckState.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.dto; + +public enum CheckState { + NOT_CHECKED, + OK, + NO_RELEASES, + ERROR +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/ConfigUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/ConfigUpdateRequest.java new file mode 100644 index 0000000..4e576b1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/ConfigUpdateRequest.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record ConfigUpdateRequest(String backupLocation, Integer retentionCount) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/PairRequest.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairRequest.java new file mode 100644 index 0000000..334df5d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairRequest.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record PairRequest(String pin, String name) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/PairResponse.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairResponse.java new file mode 100644 index 0000000..836ec31 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairResponse.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record PairResponse(String token, String id, String name) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/PairedClientDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairedClientDto.java new file mode 100644 index 0000000..5342358 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairedClientDto.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Instant; + +public record PairedClientDto(String id, String name, Instant createdAt, Instant lastUsedAt, boolean current) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/PairingCodeDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairingCodeDto.java new file mode 100644 index 0000000..c207405 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/PairingCodeDto.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Instant; + +public record PairingCodeDto(String code, Instant expiresAt) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/PublicHealthDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/PublicHealthDto.java new file mode 100644 index 0000000..1484ca9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/PublicHealthDto.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Duration; + +public record PublicHealthDto(boolean healthy, Duration backupInterval) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/ScheduleUpdateRequest.java similarity index 65% rename from src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java rename to src/main/java/wellatleastitried/mediagarrdServer/dto/ScheduleUpdateRequest.java index a0d0486..a3916da 100644 --- a/src/main/java/wellatleastitried/mediagarrd/dto/ScheduleUpdateRequest.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/ScheduleUpdateRequest.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.dto; +package wellatleastitried.mediagarrdServer.dto; import java.time.Duration; diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerConfigDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerConfigDto.java new file mode 100644 index 0000000..028618d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerConfigDto.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Duration; + +public record ServerConfigDto(String backupLocation, int retentionCount, Duration backupInterval) {} diff --git a/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerStatusDto.java similarity index 77% rename from src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java rename to src/main/java/wellatleastitried/mediagarrdServer/dto/ServerStatusDto.java index 8282d37..bd2613f 100644 --- a/src/main/java/wellatleastitried/mediagarrd/dto/ServerStatusDto.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/ServerStatusDto.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrd.dto; +package wellatleastitried.mediagarrdServer.dto; import java.time.Duration; diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupCompleteDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupCompleteDto.java new file mode 100644 index 0000000..5c9be87 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupCompleteDto.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record SetupCompleteDto(String pairingPin) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupSessionRequest.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupSessionRequest.java new file mode 100644 index 0000000..3071eaa --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupSessionRequest.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record SetupSessionRequest(String pin) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupStatusDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupStatusDto.java new file mode 100644 index 0000000..59d6f77 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/SetupStatusDto.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record SetupStatusDto(boolean completed, boolean authorized) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/VersionStatusDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/VersionStatusDto.java new file mode 100644 index 0000000..18fb393 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/VersionStatusDto.java @@ -0,0 +1,13 @@ +package wellatleastitried.mediagarrdServer.dto; + +import java.time.Instant; + +public record VersionStatusDto( + String currentVersion, + String latestVersion, + String releaseUrl, + boolean updateAvailable, + CheckState checkState, + Instant checkedAt, + String message +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookStatusDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookStatusDto.java new file mode 100644 index 0000000..e99e274 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookStatusDto.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record WebhookStatusDto(boolean configured, String target) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookTestDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookTestDto.java new file mode 100644 index 0000000..4f1710d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookTestDto.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record WebhookTestDto(boolean delivered, Integer status, String error) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookUpdateRequest.java new file mode 100644 index 0000000..7ede1a9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/WebhookUpdateRequest.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdServer.dto; + +public record WebhookUpdateRequest(String url) { + + @Override + public String toString() { + return "WebhookUpdateRequest[url=]"; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java new file mode 100644 index 0000000..aab071d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java @@ -0,0 +1,35 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.DigestInputStream; +import java.time.Instant; +import wellatleastitried.mediagarrdServer.utilities.Sha256; + +public record BackupArchive( + String id, + String fileName, + Path path, + long sizeBytes, + Instant createdAt, + String checksum +) { + public BackupArchive(String id, String fileName, Path path, long sizeBytes, Instant createdAt) { + this(id, fileName, path, sizeBytes, createdAt, null); + } + + public String resolvedChecksum() { + return checksum != null ? checksum : generateChecksum(); + } + + public String generateChecksum() { + try (DigestInputStream in = new DigestInputStream(Files.newInputStream(path), Sha256.newDigest())) { + in.transferTo(OutputStream.nullOutputStream()); + return Sha256.hex(in.getMessageDigest().digest()); + } catch (IOException e) { + return ""; + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java new file mode 100644 index 0000000..63cd4cc --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupRunResult.java @@ -0,0 +1,40 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.util.List; + +import lombok.Getter; +import lombok.experimental.Accessors; + +@Accessors(fluent = true) +@Getter +public class BackupRunResult { + private final String runId; + private final String startTime; + private final String endTime; + private final String status; + private final List serviceResults; + private final BackupArchive archive; + private final String errorMessage; + + public BackupRunResult( + String runId, + String startTime, + String endTime, + String status, + List serviceResults, + BackupArchive archive, + String errorMessage + ) { + this.runId = runId; + this.startTime = startTime; + this.endTime = endTime; + this.status = status; + this.serviceResults = serviceResults; + this.archive = archive; + this.errorMessage = errorMessage; + } + + public List serviceNames() { + return serviceResults.stream().map(BackupServiceResult::serviceName).toList(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java new file mode 100644 index 0000000..f4be77f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupServiceResult.java @@ -0,0 +1,35 @@ +package wellatleastitried.mediagarrdServer.model; + +import lombok.Getter; +import lombok.experimental.Accessors; + +@Accessors(fluent = true) +@Getter +public class BackupServiceResult { + private String runId; + private final String status; + private final String startTime; + private final String endTime; + private final String serviceName; + private final String errorMessage; + + public BackupServiceResult( + String runId, + String status, + String startTime, + String endTime, + String serviceName, + String errorMessage + ) { + this.runId = runId; + this.status = status; + this.startTime = startTime; + this.endTime = endTime; + this.serviceName = serviceName; + this.errorMessage = errorMessage; + } + + public void setId(String runId) { + this.runId = runId; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java new file mode 100644 index 0000000..cf67c10 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupRecord.java @@ -0,0 +1,14 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.util.List; + +public record FetchedBackupRecord( + int id, + String archiveId, + String startTime, + String endTime, + String status, + String filePath, + List fetchedServices, + String errorMessage +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java new file mode 100644 index 0000000..e823982 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/FetchedBackupServiceRecord.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdServer.model; + +public record FetchedBackupServiceRecord( + String serviceName, + String status, + String startTime, + String endTime, + String errorMessage +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/PairedClient.java b/src/main/java/wellatleastitried/mediagarrdServer/model/PairedClient.java new file mode 100644 index 0000000..1d9ec27 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/PairedClient.java @@ -0,0 +1,5 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.time.Instant; + +public record PairedClient(String id, String name, Instant createdAt, Instant lastUsedAt) {} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/model/ServiceDefinition.java b/src/main/java/wellatleastitried/mediagarrdServer/model/ServiceDefinition.java new file mode 100644 index 0000000..3245550 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/ServiceDefinition.java @@ -0,0 +1,52 @@ +package wellatleastitried.mediagarrdServer.model; + +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; + +public record ServiceDefinition(String name, List paths) { + + public static final int MAX_PATHS = 32; + public static final int MAX_PATH_LENGTH = 4096; + private static final Pattern VALID_NAME = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_.-]{0,63}"); + + public ServiceDefinition { + name = name == null ? "" : name.strip(); + paths = paths == null ? List.of() : paths.stream() + .filter(Objects::nonNull) + .map(String::strip) + .filter(path -> !path.isEmpty()) + .map(path -> path.startsWith("/") ? Path.of(path).normalize().toString() : path) + .distinct() + .toList(); + } + + public ServiceDefinition validate() { + if (!VALID_NAME.matcher(name).matches()) { + throw new IllegalArgumentException( + "Service name must be 1-64 characters of letters, digits, '.', '_' or '-' and start with a letter or digit"); + } + if (paths.isEmpty()) { + throw new IllegalArgumentException("Service '" + name + "' needs at least one path"); + } + if (paths.size() > MAX_PATHS) { + throw new IllegalArgumentException("Service '" + name + "' has more than " + MAX_PATHS + " paths"); + } + for (String path : paths) { + if (path.length() > MAX_PATH_LENGTH) { + throw new IllegalArgumentException("Path is longer than " + MAX_PATH_LENGTH + " characters"); + } + if (!path.startsWith("/")) { + throw new IllegalArgumentException("Path must be absolute: " + path); + } + if (path.equals("/")) { + throw new IllegalArgumentException("Path must not be the filesystem root"); + } + if (path.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Path must not contain control characters: " + path); + } + } + return this; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/BackupRecordRepository.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/BackupRecordRepository.java new file mode 100644 index 0000000..78a9261 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/BackupRecordRepository.java @@ -0,0 +1,249 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.formatTime; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.parseTime; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_BACKUP_RECORD; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_BACKUP_SERVICE_RECORD; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.DELETE_BACKUP_RECORD_BY_ID; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_LAST_SUCCESSFUL_START; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_LATEST_RECORD; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_RECORD_BY_ID; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SERVICES_FROM_RECORD; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.ParseException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Repository; + +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; +import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; + +@Repository +public class BackupRecordRepository { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupRecordRepository.class); + + private final SqliteDatabase database; + + public BackupRecordRepository(SqliteDatabase database) { + this.database = database; + } + + public void addNewBackupRecord(BackupRunResult backupRecord) { + database.readLock().lock(); + try (var connection = database.openVerifiedConnection()) { + connection.setAutoCommit(false); + Integer backupId = addMasterBackup(connection, backupRecord); + if (backupId != null) { + addServiceBackups(connection, backupId, backupRecord.serviceResults()); + } else if (backupRecord.archive() != null) { + LOGGER.warn("Could not record backup {}; this archive will not be pruned by retention", backupRecord.runId()); + } + } catch (SQLException e) { + LOGGER.warn("Could not log record of backup: " + backupRecord.runId(), e); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while attempting to open a connection to the database", e); + } finally { + database.readLock().unlock(); + } + } + + public Optional fetchBackupById(String archiveId) { + FetchedBackupRecord backupRecord = null; + database.readLock().lock(); + try (var connection = database.openVerifiedConnection()) { + backupRecord = fetchMasterRecordById(connection, archiveId); + if (backupRecord != null) { + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); + } + } catch (SQLException e) { + LOGGER.warn("An error occurred while fetching a backup record by archive_id (" + archiveId + ")", e); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while fetching a backup record by archive_id (" + archiveId + ")", e); + } finally { + database.readLock().unlock(); + } + + return Optional.ofNullable(backupRecord); + } + + public Optional fetchLatestBackupRecord() { + FetchedBackupRecord backupRecord = null; + database.readLock().lock(); + try (var connection = database.openVerifiedConnection()) { + backupRecord = fetchLatestMasterRecord(connection); + if (backupRecord != null) { + backupRecord = populateFetchedRecordWithServices(connection, backupRecord); + } + } catch (SQLException e) { + LOGGER.warn("An error occurred while fetching the latest backup record", e); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while fetching the latest backup record", e); + } finally { + database.readLock().unlock(); + } + + return Optional.ofNullable(backupRecord); + } + + public Optional fetchLastSuccessfulStartTime() { + return database.query("fetch the last successful backup", FETCH_LAST_SUCCESSFUL_START, rs -> rs.getString("start_time")) + .stream() + .findFirst() + .map(BackupRecordRepository::parseStartTime); + } + + private static Instant parseStartTime(String startTime) { + try { + return parseTime(startTime); + } catch (ParseException | NullPointerException e) { + throw new IllegalStateException("Unreadable backup start time: " + startTime, e); + } + } + + public void deleteBackupRecordById(String archiveId) { + database.readLock().lock(); + try (var connection = database.openVerifiedConnection(); + var statement = connection.prepareStatement(DELETE_BACKUP_RECORD_BY_ID)) { + statement.setString(1, archiveId); + statement.executeUpdate(); + } catch (SQLException e) { + database.invalidateIfDamaged(e); + LOGGER.warn("Error deleting a backup record with archive_id (" + archiveId + ")", e); + } finally { + database.readLock().unlock(); + } + } + + private Integer addMasterBackup(Connection connection, BackupRunResult backupRecord) { + try { + return database.inTransaction(connection, transaction -> insertMasterBackup(transaction, backupRecord)); + } catch (SQLException e) { + LOGGER.warn("An error occurred while logging a new backup record", e); + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while logging a new backup record", e); + } + return null; + } + + private static int insertMasterBackup(Connection connection, BackupRunResult backupRecord) throws SQLException { + try (var statement = connection.prepareStatement(ADD_BACKUP_RECORD)) { + statement.setString(1, backupRecord.runId()); + statement.setString(2, backupRecord.startTime()); + statement.setString(3, backupRecord.endTime()); + statement.setString(4, backupRecord.status()); + BackupArchive archive = backupRecord.archive(); + statement.setString(5, archive == null ? null : archive.resolvedChecksum()); + statement.setString(6, archive == null ? null : archive.path().toString()); + statement.setLong(7, archive == null ? 0 : archive.sizeBytes()); + statement.setString(8, archive == null ? null : formatTime(archive.createdAt())); + statement.setString(9, backupRecord.errorMessage()); + statement.executeUpdate(); + } + try (var idQuery = connection.createStatement(); + var keys = idQuery.executeQuery("SELECT last_insert_rowid()")) { + return keys.getInt(1); + } + } + + private void addServiceBackups(Connection connection, int backupId, List serviceResults) { + for (BackupServiceResult service : serviceResults) { + try { + database.inTransaction(connection, transaction -> insertServiceBackup(transaction, backupId, service)); + } catch (SQLException e) { + LOGGER.warn("An error occurred while adding a new backup service record for " + service.serviceName(), e); + } + } + } + + private static Void insertServiceBackup(Connection connection, int backupId, BackupServiceResult service) throws SQLException { + try (var statement = connection.prepareStatement(ADD_BACKUP_SERVICE_RECORD)) { + statement.setInt(1, backupId); + statement.setString(2, service.serviceName()); + statement.setString(3, service.status()); + statement.setString(4, service.startTime()); + statement.setString(5, service.endTime()); + statement.setString(6, service.errorMessage()); + statement.executeUpdate(); + } + return null; + } + + private FetchedBackupRecord fetchMasterRecordById(Connection connection, String archiveId) { + try (var statement = connection.prepareStatement(FETCH_RECORD_BY_ID)) { + statement.setString(1, archiveId); + var rs = statement.executeQuery(); + return buildFetchedBackupRecordFromQueryResult(rs); + } catch (SQLException e) { + database.invalidateIfDamaged(e); + LOGGER.warn("Error fetching backup record by archive_id " + archiveId + ")", e); + return null; + } + } + + private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { + try (var statement = connection.createStatement()) { + var rs = statement.executeQuery(FETCH_LATEST_RECORD); + return buildFetchedBackupRecordFromQueryResult(rs); + } catch (SQLException e) { + database.invalidateIfDamaged(e); + LOGGER.warn("Error fetching latest backup record", e); + return null; + } + } + + private FetchedBackupRecord buildFetchedBackupRecordFromQueryResult(ResultSet rs) throws SQLException { + if (!rs.next()) { + return null; + } + + int id = rs.getInt("id"); + String archiveId = rs.getString("archive_id"); + String backupStartTime = rs.getString("start_time"); + String backupEndTime = rs.getString("end_time"); + String status = rs.getString("status"); + String filePath = rs.getString("file_path"); + String errorMessage = rs.getString("error_message"); + + return new FetchedBackupRecord(id, archiveId, backupStartTime, backupEndTime, status, filePath, new ArrayList(), errorMessage); + } + + private FetchedBackupRecord populateFetchedRecordWithServices(Connection connection, FetchedBackupRecord backupRecord) { + try (var statement = connection.prepareStatement(FETCH_SERVICES_FROM_RECORD)) { + statement.setInt(1, backupRecord.id()); + var rs = statement.executeQuery(); + + while (rs.next()) { + String serviceName = rs.getString("service_name"); + String status = rs.getString("status"); + String startTime = rs.getString("start_time"); + String endTime = rs.getString("end_time"); + String errorMessage = rs.getString("error_message"); + var serviceRecord = new FetchedBackupServiceRecord( + serviceName, + status, + startTime, + endTime, + errorMessage + ); + backupRecord.fetchedServices().add(serviceRecord); + } + return backupRecord; + } catch (SQLException e) { + database.invalidateIfDamaged(e); + LOGGER.warn("Error populating backup record with related services", e); + return null; + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseQuarantine.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseQuarantine.java new file mode 100644 index 0000000..2cc6378 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseQuarantine.java @@ -0,0 +1,76 @@ +package wellatleastitried.mediagarrdServer.repository; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sqlite.SQLiteErrorCode; +import org.sqlite.SQLiteException; + +final class DatabaseQuarantine { + + private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseQuarantine.class); + + private static final DateTimeFormatter QUARANTINE_FORMAT = DateTimeFormatter + .ofPattern("yyyyMMdd-HHmmss") + .withZone(ZoneOffset.UTC); + + private static final List DATABASE_FILE_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); + + private DatabaseQuarantine() {} + + static void checkNotCorrupt(Connection connection) throws SQLException { + try (var statement = connection.createStatement(); var rs = statement.executeQuery("PRAGMA quick_check")) { + String result = rs.next() ? rs.getString(1) : "no result"; + if (!"ok".equals(result)) { + throw new CorruptDatabaseException("Database failed its integrity check: " + result); + } + } + } + + static boolean isCorrupt(SQLException e) { + if (e instanceof CorruptDatabaseException) { + return true; + } + if (e instanceof SQLiteException sqlite) { + int code = sqlite.getResultCode().code & 0xFF; + return code == SQLiteErrorCode.SQLITE_CORRUPT.code || code == SQLiteErrorCode.SQLITE_NOTADB.code; + } + return false; + } + + static boolean quarantine(Path databaseFile) { + if (!Files.isRegularFile(databaseFile)) { + return false; + } + String suffix = ".corrupt-" + QUARANTINE_FORMAT.format(Instant.now()); + try { + for (String fileSuffix : DATABASE_FILE_SUFFIXES) { + Path file = Path.of(databaseFile + fileSuffix); + if (Files.isRegularFile(file)) { + Files.move(file, Path.of(file + suffix)); + } + } + } catch (IOException e) { + LOGGER.error("Database {} is corrupt and could not be moved aside", databaseFile, e); + return false; + } + LOGGER.error("Database {} was corrupt, moved it to {}{} and created a new one. Settings and services must be configured again", + databaseFile, databaseFile, suffix); + return true; + } + + private static class CorruptDatabaseException extends SQLException { + CorruptDatabaseException(String message) { + super(message); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseRebuildListener.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseRebuildListener.java new file mode 100644 index 0000000..0aab8be --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseRebuildListener.java @@ -0,0 +1,7 @@ +package wellatleastitried.mediagarrdServer.repository; + +@FunctionalInterface +public interface DatabaseRebuildListener { + + void databaseRebuilt(); +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseSchema.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseSchema.java new file mode 100644 index 0000000..3038c6f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/DatabaseSchema.java @@ -0,0 +1,125 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.CREATE_TABLES; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.MIGRATIONS; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.Migration; + +final class DatabaseSchema { + + private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseSchema.class); + + private static final List REQUIRED_TABLES = List.of("backups", "backup_services", "services", "settings"); + + record Fingerprint(int userVersion, int schemaVersion) {} + + private DatabaseSchema() {} + + static Fingerprint fingerprint(Connection connection) throws SQLException { + try (var statement = connection.createStatement(); + var rs = statement.executeQuery("SELECT user_version, schema_version FROM pragma_user_version, pragma_schema_version")) { + return new Fingerprint(rs.getInt(1), rs.getInt(2)); + } + } + + static void ensureTablesExist(Connection connection) throws SQLException { + try (var statement = connection.createStatement()) { + for (String sql : CREATE_TABLES.split(";")) { + String createStatement = sql.trim(); + if (!createStatement.isEmpty()) { + statement.execute(createStatement); + } + } + + connection.commit(); + } catch (SQLException e) { + LOGGER.warn("Failed to verify if tables exist in database.", e); + rollback(connection); + throw e; + } + } + + static void runNeededMigrations(Connection connection) throws SQLException { + int currentVersion = databaseVersion(connection); + if (currentVersion == -1) return; + + // 0 means it is a brand new database, or it was created before migrations existed + if (currentVersion == 0) { + // Initial tables will be "v1" + currentVersion = 1; + setDatabaseVersion(connection, currentVersion); + } + + for (Migration migration : MIGRATIONS) { + if (currentVersion >= migration.version()) { + continue; + } + + try (var statement = connection.createStatement()) { + statement.execute(migration.sql()); + } catch (SQLException e) { + LOGGER.warn( + "Migration failed for v" + migration.version() + ". Aborting the rest of the migrations...", + e + ); + rollback(connection); + throw e; + } + + currentVersion = migration.version(); + setDatabaseVersion(connection, currentVersion); + } + + connection.commit(); + } + + static void requireCompleteSchema(Connection connection) throws SQLException { + if (databaseVersion(connection) < 1) { + throw new SQLException("Snapshot is missing its schema version"); + } + List tables = new ArrayList<>(); + try (var statement = connection.createStatement(); + var rs = statement.executeQuery("SELECT name FROM sqlite_master WHERE type = 'table'")) { + while (rs.next()) { + tables.add(rs.getString(1)); + } + } + if (!tables.containsAll(REQUIRED_TABLES)) { + throw new SQLException("Snapshot is missing tables, found " + tables); + } + } + + static void rollback(Connection connection) { + try { + connection.rollback(); + } catch (SQLException e) { + LOGGER.warn("Failed to rollback update after previous SQL failure, there is an issue with the database!"); + } + } + + private static int databaseVersion(Connection connection) { + try (var statement = connection.createStatement(); + var result = statement.executeQuery("PRAGMA user_version")) { + return result.getInt(1); + } catch (SQLException e) { + LOGGER.warn("Failed to fetch database version", e); + return -1; + } + } + + private static void setDatabaseVersion(Connection connection, int version) { + try (var statement = connection.createStatement()) { + statement.execute("PRAGMA user_version = " + version); + } catch (SQLException e) { + LOGGER.warn("Failed to set new database version", e); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/PairedClientRepository.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/PairedClientRepository.java new file mode 100644 index 0000000..cbf92d7 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/PairedClientRepository.java @@ -0,0 +1,59 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_PAIRED_CLIENT; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.COUNT_PAIRED_CLIENTS; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.DELETE_PAIRED_CLIENT; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_PAIRED_CLIENTS; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_PAIRED_CLIENT_BY_HASH; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.TOUCH_PAIRED_CLIENT; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; + +import org.springframework.stereotype.Repository; + +import wellatleastitried.mediagarrdServer.model.PairedClient; + +@Repository +public class PairedClientRepository { + + private final SqliteDatabase database; + + public PairedClientRepository(SqliteDatabase database) { + this.database = database; + } + + public void addPairedClient(String id, String name, String tokenHash, Instant createdAt) { + database.update("add paired client " + id, ADD_PAIRED_CLIENT, id, name, tokenHash, createdAt.toString()); + } + + public List fetchPairedClients() { + return database.query("fetch paired clients", FETCH_PAIRED_CLIENTS, PairedClientRepository::toPairedClient); + } + + public Optional fetchPairedClientByTokenHash(String tokenHash) { + return database.query("fetch paired client by token", FETCH_PAIRED_CLIENT_BY_HASH, PairedClientRepository::toPairedClient, tokenHash) + .stream().findFirst(); + } + + public boolean removePairedClient(String id) { + return database.update("remove paired client " + id, DELETE_PAIRED_CLIENT, id) > 0; + } + + public void touchPairedClient(String id, Instant usedAt) { + database.update("update paired client " + id, TOUCH_PAIRED_CLIENT, usedAt.toString(), id); + } + + public int countPairedClients() { + return database.query("count paired clients", COUNT_PAIRED_CLIENTS, rs -> rs.getInt(1)).get(0); + } + + private static PairedClient toPairedClient(ResultSet rs) throws SQLException { + String lastUsed = rs.getString("last_used_at"); + return new PairedClient(rs.getString("id"), rs.getString("name"), Instant.parse(rs.getString("created_at")), + lastUsed == null ? null : Instant.parse(lastUsed)); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/ServiceRepository.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/ServiceRepository.java new file mode 100644 index 0000000..bbd1a07 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/ServiceRepository.java @@ -0,0 +1,70 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.ADD_SERVICE; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.DELETE_SERVICE; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_ALL_SERVICES; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SERVICE_BY_NAME; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.UPDATE_SERVICE; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.Optional; + +import org.springframework.stereotype.Repository; + +import tools.jackson.core.JacksonException; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +@Repository +public class ServiceRepository { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final TypeReference> PATH_LIST = new TypeReference<>() {}; + + private final SqliteDatabase database; + + public ServiceRepository(SqliteDatabase database) { + this.database = database; + } + + public List fetchServices() { + return database.query("fetch configured services", FETCH_ALL_SERVICES, ServiceRepository::toServiceDefinition); + } + + public Optional fetchService(String name) { + return database.query("fetch service " + name, FETCH_SERVICE_BY_NAME, ServiceRepository::toServiceDefinition, name) + .stream().findFirst(); + } + + public void addService(ServiceDefinition service) { + database.update("add service " + service.name(), ADD_SERVICE, service.name(), toJson(service.paths())); + } + + public boolean updateService(String name, ServiceDefinition service) { + return database.update("update service " + name, UPDATE_SERVICE, service.name(), toJson(service.paths()), name) > 0; + } + + public boolean removeService(String name) { + return database.update("remove service " + name, DELETE_SERVICE, name) > 0; + } + + private static ServiceDefinition toServiceDefinition(ResultSet rs) throws SQLException { + try { + return new ServiceDefinition(rs.getString("name"), JSON.readValue(rs.getString("paths"), PATH_LIST)); + } catch (JacksonException e) { + throw new SQLException("Corrupt paths for service " + rs.getString("name"), e); + } + } + + private static String toJson(List paths) { + try { + return JSON.writeValueAsString(paths); + } catch (JacksonException e) { + throw new IllegalStateException("Failed to serialize service paths", e); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/SettingsRepository.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/SettingsRepository.java new file mode 100644 index 0000000..ed62062 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/SettingsRepository.java @@ -0,0 +1,26 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SETTING; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.UPSERT_SETTING; + +import java.util.Optional; + +import org.springframework.stereotype.Repository; + +@Repository +public class SettingsRepository { + + private final SqliteDatabase database; + + public SettingsRepository(SqliteDatabase database) { + this.database = database; + } + + public Optional fetchSetting(String key) { + return database.query("fetch setting " + key, FETCH_SETTING, rs -> rs.getString("value"), key).stream().findFirst(); + } + + public void saveSetting(String key, String value) { + database.update("save setting " + key, UPSERT_SETTING, key, value); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/repository/SqliteDatabase.java b/src/main/java/wellatleastitried/mediagarrdServer/repository/SqliteDatabase.java new file mode 100644 index 0000000..a3f0af5 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/repository/SqliteDatabase.java @@ -0,0 +1,289 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.SQLITE; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import jakarta.annotation.PreDestroy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.sqlite.SQLiteConfig; +import org.sqlite.SQLiteOpenMode; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.utilities.FilePermissions; + +@Component +public class SqliteDatabase { + + private static final Logger LOGGER = LoggerFactory.getLogger(SqliteDatabase.class); + + private final ReentrantReadWriteLock databaseLock = new ReentrantReadWriteLock(); + private final Path databaseFile; + private final String databaseUrl; + private final List rebuildListeners = new CopyOnWriteArrayList<>(); + private final ExecutorService rebuildNotifier = Executors.newSingleThreadExecutor(runnable -> { + Thread thread = new Thread(runnable, "database-rebuild-notifier"); + thread.setDaemon(true); + return thread; + }); + private volatile DatabaseSchema.Fingerprint verifiedSchema; + + public SqliteDatabase(MediaGarrdProperties properties) { + databaseFile = Path.of(properties.getDatabasePath()).toAbsolutePath(); + databaseUrl = SQLITE + databaseFile; + verifyDatabaseIntegrity(); + } + + @PreDestroy + public void shutdownRebuildNotifier() { + rebuildNotifier.shutdown(); + try { + if (!rebuildNotifier.awaitTermination(5, TimeUnit.SECONDS)) { + rebuildNotifier.shutdownNow(); + rebuildNotifier.awaitTermination(2, TimeUnit.SECONDS); + } + } catch (InterruptedException e) { + rebuildNotifier.shutdownNow(); + Thread.currentThread().interrupt(); + } + } + + @FunctionalInterface + interface RowMapper { + T map(ResultSet rs) throws SQLException; + } + + @FunctionalInterface + interface TransactionWork { + T run(Connection connection) throws SQLException; + } + + @FunctionalInterface + private interface StatementWork { + T run(PreparedStatement statement) throws SQLException; + } + + public void addRebuildListener(DatabaseRebuildListener listener) { + rebuildListeners.add(listener); + } + + public Path databaseFile() { + return databaseFile; + } + + protected Connection getConnection() throws SQLException { + Connection connection = DriverManager.getConnection(databaseUrl); + try (var statement = connection.createStatement()) { + statement.execute("PRAGMA foreign_keys = ON"); + } catch (SQLException e) { + connection.close(); + throw e; + } + return connection; + } + + protected synchronized boolean verifyDatabaseIntegrity() { + verifiedSchema = null; + try { + rebuildIfNeeded(); + return true; + } catch (SQLException e) { + if (!DatabaseQuarantine.isCorrupt(e) || !DatabaseQuarantine.quarantine(databaseFile)) { + LOGGER.warn("An error occurred while verifying the integrity of the database", e); + return false; + } + } catch (Exception e) { + LOGGER.warn("An unknown error occurred while verifying the integrity of the database", e); + return false; + } + + try { + rebuildIfNeeded(); + notifyRebuilt(); + return true; + } catch (Exception e) { + LOGGER.warn("Unable to create a new database after moving the corrupt one aside", e); + return false; + } + } + + private void notifyRebuilt() { + for (DatabaseRebuildListener listener : rebuildListeners) { + rebuildNotifier.execute(() -> { + try { + listener.databaseRebuilt(); + } catch (RuntimeException e) { + LOGGER.error("Unable to reset the server after the database was rebuilt, restart the server", e); + } + }); + } + } + + private void rebuildIfNeeded() throws SQLException { + try { + FilePermissions.createPrivateDirectories(databaseFile.getParent()); + if (Files.exists(databaseFile)) { + FilePermissions.restrictFile(databaseFile); + } else { + FilePermissions.createPrivateFile(databaseFile); + } + } catch (IOException e) { + LOGGER.warn("Unable to prepare the database location " + databaseFile.getParent(), e); + } + try (var connection = getConnection()) { + DatabaseQuarantine.checkNotCorrupt(connection); + connection.setAutoCommit(false); + DatabaseSchema.ensureTablesExist(connection); + DatabaseSchema.runNeededMigrations(connection); + verifiedSchema = DatabaseSchema.fingerprint(connection); + } + } + + Lock readLock() { + return databaseLock.readLock(); + } + + Connection openVerifiedConnection() throws SQLException { + DatabaseSchema.Fingerprint expected = verifiedSchema; + if (expected != null) { + Connection connection = null; + try { + connection = getConnection(); + if (DatabaseSchema.fingerprint(connection).equals(expected)) { + return connection; + } + } catch (SQLException e) { + LOGGER.debug("Unable to read the database schema fingerprint", e); + } + if (connection != null) { + connection.close(); + } + LOGGER.info("Database does not match the verified schema, rebuilding it"); + } + if (!verifyDatabaseIntegrity()) { + throw new SQLException("Database integrity check failed"); + } + return getConnection(); + } + + boolean invalidateIfDamaged(SQLException e) { + String message = String.valueOf(e.getMessage()); + boolean damaged = DatabaseQuarantine.isCorrupt(e) || message.contains("no such table") || message.contains("no such column"); + if (damaged) { + verifiedSchema = null; + } + return damaged; + } + + T inTransaction(Connection connection, TransactionWork work) throws SQLException { + try { + T result = work.run(connection); + connection.commit(); + return result; + } catch (SQLException e) { + invalidateIfDamaged(e); + DatabaseSchema.rollback(connection); + throw e; + } + } + + List query(String action, String sql, RowMapper mapper, String... params) { + return execute(action, sql, params, statement -> { + try (var rs = statement.executeQuery()) { + List rows = new ArrayList<>(); + while (rs.next()) { + rows.add(mapper.map(rs)); + } + return rows; + } + }); + } + + int update(String action, String sql, String... params) { + return execute(action, sql, params, PreparedStatement::executeUpdate); + } + + private T execute(String action, String sql, String[] params, StatementWork work) { + databaseLock.readLock().lock(); + try { + for (int attempt = 1; ; attempt++) { + try (var connection = openVerifiedConnection(); var statement = connection.prepareStatement(sql)) { + bind(statement, params); + return work.run(statement); + } catch (SQLException e) { + if (attempt > 1 || !invalidateIfDamaged(e)) { + throw new IllegalStateException("Failed to " + action, e); + } + LOGGER.warn("Database is damaged or out of date, rebuilding and retrying: {}", e.getMessage()); + } + } + } finally { + databaseLock.readLock().unlock(); + } + } + + public void snapshotTo(Path target) throws SQLException, IOException { + databaseLock.writeLock().lock(); + try { + if (Files.exists(target)) { + throw new IOException("Snapshot target " + target + " already exists"); + } + try { + if (!Files.isRegularFile(databaseFile)) { + throw new IOException("Database file " + databaseFile + " does not exist"); + } + try (var connection = openSnapshotConnection(databaseFile)) { + DatabaseQuarantine.checkNotCorrupt(connection); + try (var statement = connection.createStatement()) { + statement.execute("VACUUM INTO '" + target.toString().replace("'", "''") + "'"); + } + } + verifySnapshot(target); + } catch (SQLException | IOException | RuntimeException e) { + Files.deleteIfExists(target); + throw e; + } + } finally { + databaseLock.writeLock().unlock(); + } + } + + protected Connection openSnapshotConnection(Path file) throws SQLException { + SQLiteConfig config = new SQLiteConfig(); + config.resetOpenMode(SQLiteOpenMode.CREATE); + return config.createConnection(SQLITE + file); + } + + private void verifySnapshot(Path snapshot) throws SQLException, IOException { + if (!Files.isRegularFile(snapshot)) { + throw new IOException("Snapshot was not written to " + snapshot); + } + try (var connection = openSnapshotConnection(snapshot)) { + DatabaseQuarantine.checkNotCorrupt(connection); + DatabaseSchema.requireCompleteSchema(connection); + } + } + + private static void bind(PreparedStatement statement, String... params) throws SQLException { + for (int i = 0; i < params.length; i++) { + statement.setString(i + 1, params[i]); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/AttemptLimiter.java b/src/main/java/wellatleastitried/mediagarrdServer/service/AttemptLimiter.java new file mode 100644 index 0000000..0ee3183 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/AttemptLimiter.java @@ -0,0 +1,49 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; + +final class AttemptLimiter { + + private final int maxFailures; + private final Duration lockDuration; + private final Clock clock; + private int failures; + private Instant lockedUntil; + + AttemptLimiter(int maxFailures, Duration lockDuration, Clock clock) { + this.maxFailures = maxFailures; + this.lockDuration = lockDuration; + this.clock = clock; + } + + synchronized void checkNotLocked() { + if (lockedUntil == null) { + return; + } + Instant now = clock.instant(); + if (now.isBefore(lockedUntil)) { + throw new LockedOutException(Duration.between(now, lockedUntil)); + } + lockedUntil = null; + failures = 0; + } + + synchronized int recordFailure() { + failures++; + if (failures >= maxFailures) { + lockedUntil = clock.instant().plus(lockDuration); + } + return failures; + } + + synchronized boolean isLockedNow() { + return lockedUntil != null && clock.instant().isBefore(lockedUntil); + } + + synchronized void reset() { + failures = 0; + lockedUntil = null; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java new file mode 100644 index 0000000..9b71b06 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java @@ -0,0 +1,406 @@ +package wellatleastitried.mediagarrdServer.service; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.BACKUP_ROOT_SETTING; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.RETENTION_COUNT_SETTING; + +import java.io.IOException; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import jakarta.annotation.PostConstruct; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.repository.BackupRecordRepository; +import wellatleastitried.mediagarrdServer.repository.SettingsRepository; +import wellatleastitried.mediagarrdServer.utilities.FilePermissions; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; + +@Service +public class BackupArchiveService { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupArchiveService.class); + + private static final DateTimeFormatter FILE_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss-SSS") + .withZone(ZoneOffset.UTC); + private static final long ARCHIVE_CACHE_TTL_MS = 60_000; // Cache archive list for 60 seconds + static final String ARCHIVE_SUFFIX = "-media-backup.zip"; + static final String ZIP_EXTENSION = ".zip"; + static final String RUNS_DIRECTORY = ".mediagarrd-runs"; + static final String TEMP_SUFFIX = ARCHIVE_SUFFIX + ".tmp"; + static final int MAX_LOCATION_LENGTH = 4096; + + private final MediaGarrdProperties properties; + private final SettingsRepository settings; + private final BackupRecordRepository backups; + private final AtomicReference archiveCache = new AtomicReference<>(null); + private record ArchiveSnapshot(List archives, long loadedAtMs) {} + + private volatile Path root; + private volatile int retentionCount; + + public BackupArchiveService(MediaGarrdProperties properties, SettingsRepository settings, BackupRecordRepository backups) { + this.properties = properties; + this.settings = settings; + this.backups = backups; + loadSettings(); + } + + private void loadSettings() { + this.root = Path.of(settings.fetchSetting(BACKUP_ROOT_SETTING).orElse(properties.getBackupRoot())) + .toAbsolutePath() + .normalize(); + this.retentionCount = settings.fetchSetting(RETENTION_COUNT_SETTING) + .flatMap(BackupArchiveService::parseRetention) + .orElse(Math.max(1, properties.getRetentionCount())); + } + + public synchronized void reloadFromSettings() { + loadSettings(); + invalidateCache(); + LOGGER.info("Backup location and retention reloaded from the settings: location={}, retentionCount={}", LogSanitizer.clean(root), retentionCount); + } + + @PostConstruct + public void cleanupStaleArtifactsOnStartup() { + Path root = rootDirectory(); + Path runsRoot = root.resolve(RUNS_DIRECTORY); + + try { + FilePermissions.createPrivateDirectories(root); + + try (var stream = Files.list(root)) { + stream + .filter(Files::isRegularFile) + .filter(path -> path.getFileName().toString().endsWith(TEMP_SUFFIX)) + .forEach(path -> { + try { + Files.deleteIfExists(path); + LOGGER.info("Startup cleanup: removed stale temporary archive {}", path.getFileName()); + } catch (IOException e) { + LOGGER.warn("Startup cleanup: failed to remove stale temporary archive {}", path, e); + } + }); + } + + if (Files.exists(runsRoot)) { + try (var stream = Files.list(runsRoot)) { + stream + .filter(Files::isDirectory) + .forEach(runDir -> { + try { + removeRunDirectory(runDir); + LOGGER.info("Startup cleanup: removed stale run directory {}", runDir.getFileName()); + } catch (RuntimeException e) { + LOGGER.warn("Startup cleanup: failed to remove stale run directory {}", runDir, e); + } + }); + } + } + + enforceRetention(); + LOGGER.info("Startup cleanup: retention policy enforced"); + } catch (IOException e) { + LOGGER.warn("Startup cleanup: unable to initialize backup root {}", root, e); + } catch (RuntimeException e) { + LOGGER.warn("Startup cleanup: failed while enforcing retention policy", e); + } + } + + public Path rootDirectory() { + return root; + } + + public int retentionCount() { + return retentionCount; + } + + public synchronized void updateSettings(String location, Integer retention) { + if (location == null && retention == null) { + throw new IllegalArgumentException("Nothing to update, provide backupLocation and/or retentionCount"); + } + if (retention != null && retention < 1) { + throw new IllegalArgumentException("Retention count must be at least 1"); + } + if (location != null) { + updateRootDirectory(location); + } + if (retention != null) { + settings.saveSetting(RETENTION_COUNT_SETTING, retention.toString()); + retentionCount = retention; + LOGGER.info("Retention count changed to {}, applied on the next backup run", retention); + } + } + + public Path updateRootDirectory(String location) { + if (location == null || location.isBlank()) { + throw new IllegalArgumentException("Backup location is required"); + } + if (location.length() > MAX_LOCATION_LENGTH) { + throw new IllegalArgumentException("Backup location must be at most " + MAX_LOCATION_LENGTH + " characters"); + } + if (location.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Backup location must not contain control characters"); + } + Path requested = Path.of(location.strip()); + if (!requested.isAbsolute()) { + throw new IllegalArgumentException("Backup location must be an absolute path"); + } + Path normalized = requested.normalize(); + try { + FilePermissions.createPrivateDirectories(normalized); + } catch (IOException | SecurityException e) { + throw new IllegalArgumentException("Unable to create backup location " + normalized); + } + if (!Files.isWritable(normalized)) { + throw new IllegalArgumentException("Backup location is not writable: " + normalized); + } + + settings.saveSetting(BACKUP_ROOT_SETTING, normalized.toString()); + root = normalized; + invalidateCache(); + LOGGER.info("Backup location changed to {}", LogSanitizer.clean(normalized)); + return normalized; + } + + public BackupArchive createArchive(Path runDirectory) { + Instant createdAt = Instant.now(); + String fileName = FILE_DATE_FORMAT.format(createdAt) + ARCHIVE_SUFFIX; + Path root = rootDirectory(); + Path archivePath = root.resolve(fileName); + + LOGGER.info("Creating backup archive: {} from runDir={}", fileName, runDirectory); + try { + FilePermissions.createPrivateDirectories(root); + String checksum = mergeParts(runDirectory, archivePath); + enforceRetention(); + long size = Files.size(archivePath); + LOGGER.info("Archive created: {} ({} bytes)", fileName, size); + + invalidateCache(); + + return new BackupArchive(toId(fileName), fileName, archivePath, size, createdAt, checksum); + } catch (IOException e) { + LOGGER.error("Failed to create backup archive: {}", fileName, e); + throw new IllegalStateException("Failed to create backup archive", e); + } + } + + public List listArchives() { + long now = System.currentTimeMillis(); + ArchiveSnapshot cached = archiveCache.get(); + + if (cached != null && now - cached.loadedAtMs() < ARCHIVE_CACHE_TTL_MS) { + LOGGER.debug("Returning cached archive list ({}ms old)", now - cached.loadedAtMs()); + return cached.archives(); + } + + // Cache miss -> rebuild list + List archives; + try { + archives = scanArchives(); + } catch (IOException e) { + throw new IllegalStateException("Failed to list archives", e); + } + + archiveCache.set(new ArchiveSnapshot(archives, now)); + LOGGER.debug("Rebuilt archive cache with {} archives", archives.size()); + return archives; + } + + public Optional latest() { + return listArchives().stream().findFirst(); + } + + public Optional byId(String id) { + return listArchives().stream().filter(archive -> archive.id().equals(id)).findFirst(); + } + + public boolean deleteById(String id) { + Optional archive = byId(id); + if (archive.isEmpty()) { + return false; + } + + try { + Files.deleteIfExists(archive.get().path()); + backups.deleteBackupRecordById(id); + LOGGER.info("Archive deleted: {}", id); + invalidateCache(); + return true; + + } catch (IOException e) { + LOGGER.error("Failed to delete archive: {}", id, e); + throw new IllegalStateException("Failed to delete archive " + id, e); + } + } + + public Path createRunDirectory() { + Path runDir = rootDirectory().resolve(RUNS_DIRECTORY).resolve(UUID.randomUUID().toString()); + try { + FilePermissions.createPrivateDirectories(runDir); + return runDir; + } catch (IOException e) { + throw new IllegalStateException("Failed to create run directory", e); + } + } + + public void removeRunDirectory(Path runDirectory) { + if (runDirectory == null || !Files.exists(runDirectory)) { + return; + } + + try (var walk = Files.walk(runDirectory)) { + walk.sorted(Comparator.reverseOrder()).forEach(path -> { + try { + Files.deleteIfExists(path); + } catch (IOException e) { + throw new IllegalStateException("Failed to clean up run directory", e); + } + }); + } catch (IOException e) { + throw new IllegalStateException("Failed to walk run directory", e); + } + } + + private void enforceRetention() throws IOException { + List archives = scanArchives(); + for (BackupArchive archive : archives.subList(Math.min(retentionCount, archives.size()), archives.size())) { + if (backups.fetchBackupById(archive.id()).isEmpty()) { + LOGGER.info("Retention: keeping {} because this server has no record of creating it", archive.fileName()); + continue; + } + LOGGER.info("Retention: deleting old archive: {}", archive.fileName()); + Files.deleteIfExists(archive.path()); + backups.deleteBackupRecordById(archive.id()); + } + } + + private List scanArchives() throws IOException { + Path root = rootDirectory(); + if (!Files.exists(root)) { + return List.of(); + } + try (var stream = Files.list(root)) { + return stream + .filter(path -> path.getFileName().toString().endsWith(ARCHIVE_SUFFIX)) + .map(this::toArchive) + .sorted(Comparator.comparing(BackupArchive::createdAt).reversed()) + .toList(); + } + } + + private void invalidateCache() { + archiveCache.set(null); + } + + private String mergeParts(Path runDirectory, Path zipPath) throws IOException { + List parts; + try (var walk = Files.walk(runDirectory)) { + parts = walk + .filter(Files::isRegularFile) + .filter(path -> path.getFileName().toString().endsWith(ZipPartWriter.PART_SUFFIX)) + .sorted() + .toList(); + } + + Path tempZip = zipPath.resolveSibling(zipPath.getFileName() + ".tmp"); + Files.deleteIfExists(tempZip); + FilePermissions.createPrivateFile(tempZip); + Path snapshotDirectory = runDirectory.resolve(DatabaseSnapshotService.PART_DIRECTORY); + ZipPartMerger.Result result; + try { + result = ZipPartMerger.merge( + parts.stream().filter(path -> path.startsWith(snapshotDirectory)).toList(), + parts.stream().filter(path -> !path.startsWith(snapshotDirectory)).toList(), + tempZip, runDirectory); + syncFile(tempZip); + Files.move(tempZip, zipPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (IOException | RuntimeException e) { + Files.deleteIfExists(tempZip); + throw e; + } + syncDirectory(zipPath.getParent()); + LOGGER.info("Merged {} part(s) into {} entries", parts.size(), result.entries()); + return result.checksum(); + } + + static void syncFile(Path file) throws IOException { + try (FileChannel channel = FileChannel.open(file, StandardOpenOption.WRITE)) { + channel.force(true); + } + } + + static void syncDirectory(Path directory) { + try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) { + channel.force(true); + } catch (IOException | RuntimeException e) { + LOGGER.debug("Could not sync directory {}: {}", directory, e.toString()); + } + } + + private BackupArchive toArchive(Path path) { + String fileName = path.getFileName().toString(); + return new BackupArchive( + toId(fileName), + fileName, + path, + fileSize(path), + createdAt(path) + ); + } + + private Instant createdAt(Path path) { + String fileName = path.getFileName().toString(); + String stamp = fileName.substring(0, fileName.length() - ARCHIVE_SUFFIX.length()); + try { + return FILE_DATE_FORMAT.parse(stamp, Instant::from); + } catch (DateTimeParseException e) { + return lastModified(path); + } + } + + private static Optional parseRetention(String stored) { + try { + return Optional.of(Integer.parseInt(stored)).filter(count -> count >= 1); + } catch (NumberFormatException e) { + LOGGER.warn("Ignoring invalid stored retention count: {}", stored); + return Optional.empty(); + } + } + + private String toId(String fileName) { + return fileName.endsWith(ZIP_EXTENSION) ? fileName.substring(0, fileName.length() - ZIP_EXTENSION.length()) : fileName; + } + + private long fileSize(Path path) { + try { + return Files.size(path); + } catch (IOException e) { + return 0L; + } + } + + private Instant lastModified(Path path) { + try { + return Files.getLastModifiedTime(path).toInstant(); + } catch (IOException e) { + return Instant.EPOCH; + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupFailedException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupFailedException.java new file mode 100644 index 0000000..a274e62 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupFailedException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.service; + +public class BackupFailedException extends IllegalStateException { + + public BackupFailedException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupInProgressException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupInProgressException.java new file mode 100644 index 0000000..f173dea --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupInProgressException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.service; + +public class BackupInProgressException extends IllegalStateException { + + public BackupInProgressException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupNotFoundException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupNotFoundException.java new file mode 100644 index 0000000..753e585 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupNotFoundException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.service; + +public class BackupNotFoundException extends RuntimeException { + + public BackupNotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java new file mode 100644 index 0000000..8317521 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -0,0 +1,346 @@ +package wellatleastitried.mediagarrdServer.service; + +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.formatTime; +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.recordCurrentTime; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.BackupRecordRepository; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; + +@Service +public class BackupOrchestratorService { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupOrchestratorService.class); + + private static final String SNAPSHOT_NAME = DatabaseSnapshotService.SERVICE_NAME; + private static final int RUNNER_POOL_SIZE = 6; + private static final long RUNNER_IDLE_TTL_SECONDS = 30; + private static final long SCHEDULED_CHECK_INTERVAL_MS = 30000; + private static final AtomicInteger THREAD_COUNTER = new AtomicInteger(); + + private final ServiceBackupRunner runner; + private final BackupArchiveService archiveService; + private final BackupScheduleService scheduleService; + private final DatabaseSnapshotService snapshotService; + private final ServiceRepository services; + private final BackupRecordRepository backups; + private final BackupRunLifecycle lifecycle; + private final WebhookService webhook; + private final ExecutorService runnerExecutor = createRunnerExecutor(); + + public BackupOrchestratorService( + ServiceBackupRunner runner, + BackupArchiveService archiveService, + BackupScheduleService scheduleService, + DatabaseSnapshotService snapshotService, + ServiceRepository services, + BackupRecordRepository backups, + BackupRunLifecycle lifecycle, + WebhookService webhook + ) { + this.runner = runner; + this.archiveService = archiveService; + this.scheduleService = scheduleService; + this.snapshotService = snapshotService; + this.services = services; + this.backups = backups; + this.lifecycle = lifecycle; + this.webhook = webhook; + } + + private static ExecutorService createRunnerExecutor() { + ThreadPoolExecutor executor = new ThreadPoolExecutor( + RUNNER_POOL_SIZE, + RUNNER_POOL_SIZE, + RUNNER_IDLE_TTL_SECONDS, + TimeUnit.SECONDS, + new LinkedBlockingQueue<>(), + runnable -> { + Thread thread = new Thread(runnable, "backup-runner-" + THREAD_COUNTER.incrementAndGet()); + thread.setDaemon(true); + return thread; + } + ); + executor.allowCoreThreadTimeOut(true); + return executor; + } + + @Scheduled(fixedDelay = SCHEDULED_CHECK_INTERVAL_MS) + public void scheduledRun() { + if (lifecycle.isRunning()) { + LOGGER.debug("Scheduled check skipped, backup already in progress"); + return; + } + if (!scheduleService.dueNow()) { + return; + } + LOGGER.info("Scheduled backup triggered, next run at {}", scheduleService.getNextRun()); + try { + runBackup(true); + } catch (RunRejectedException ex) { + LOGGER.warn("Scheduled backup skipped: {}", ex.getMessage()); + } catch (RuntimeException ex) { + LOGGER.error("Scheduled backup run failed", ex); + } + } + + public BackupRunResult runBackup() { + return runBackup(false); + } + + BackupRunResult runBackup(boolean scheduled) { + Instant startedAt = Instant.now(); + return lifecycle.run(startedAt, run -> execute(run, startedAt, scheduled)); + } + + private BackupRunResult execute(BackupRunLifecycle.Run run, Instant startedAt, boolean scheduled) { + Path runDirectory = null; + boolean started = false; + boolean notified = false; + try { + List configured = services.fetchServices(); + if (configured.isEmpty()) { + LOGGER.warn("No services are configured, aborting backup run before creating a run directory"); + if (scheduled) { + scheduleService.deferNextRun(); + } + throw new RunRejectedException("No services are configured for backup"); + } + run.markStarted(); + started = true; + + scheduleService.markRunStarted(); + runDirectory = archiveService.createRunDirectory(); + final Path runDir = runDirectory; + + LOGGER.info("Backup run started: runDir={}, services={}", + runDir, configured.stream().map(ServiceDefinition::name).toList()); + + DatabaseSnapshotService.Outcome snapshot = snapshotDatabase(runDir); + BackupServiceResult snapshotResult = snapshot.result(); + Set excluded = COMPLETED.equals(snapshotResult.status()) && snapshot.hostPath() != null + ? DatabaseSnapshotService.reservedNames(snapshot.hostPath()) + : Set.of(); + + List serviceRunResults = copyServices(configured, runDir, excluded); + + List incomplete = serviceRunResults.stream() + .filter(r -> !COMPLETED.equals(r.status())) + .toList(); + int succeeded = configured.size() - incomplete.size(); + LOGGER.info("All runners finished: succeeded={}/{}", succeeded, configured.size()); + incomplete.forEach(r -> LOGGER.warn("Runner did not complete (non-fatal): {} ({})", r.serviceName(), r.status())); + + String errorMessage = incomplete.stream() + .map(r -> r.serviceName() + ": " + Objects.requireNonNullElse(r.errorMessage(), "no details")) + .collect(Collectors.joining("\n")); + + if (succeeded == 0 && incomplete.stream().allMatch(r -> FAILED.equals(r.status()))) { + String runId = "failed-" + UUID.randomUUID(); + serviceRunResults.forEach(r -> r.setId(runId)); + BackupRunResult failedRecord = new BackupRunResult( + runId, formatTime(startedAt), recordCurrentTime(), FAILED, serviceRunResults, null, errorMessage); + backups.addNewBackupRecord(failedRecord); + LOGGER.error("Every service failed, no archive created (run {}):\n{}", runId, errorMessage); + notified = true; + webhook.notifyRun(failedRecord); + throw new BackupFailedException("Every service failed, no archive created: " + errorMessage); + } + + List recordedResults = new ArrayList<>(serviceRunResults); + recordedResults.add(snapshotResult); + boolean snapshotFailed = !COMPLETED.equals(snapshotResult.status()); + if (snapshotFailed) { + LOGGER.warn("Database snapshot did not complete (non-fatal): {}", snapshotResult.errorMessage()); + String snapshotError = SNAPSHOT_NAME + ": " + Objects.requireNonNullElse(snapshotResult.errorMessage(), "no details"); + errorMessage = errorMessage.isEmpty() ? snapshotError : errorMessage + "\n" + snapshotError; + } + + BackupArchive archive = archiveService.createArchive(runDirectory); + recordedResults.forEach(r -> r.setId(archive.id())); + + long durationMs = Duration.between(startedAt, Instant.now()).toMillis(); + LOGGER.info("Backup run complete: archive={}, size={}B, duration={}ms, services={}", + archive.fileName(), archive.sizeBytes(), durationMs, + recordedResults.stream().map(BackupServiceResult::serviceName).toList()); + + String status = succeeded == configured.size() ? COMPLETED : succeeded > 0 ? PARTIAL : FAILED; + if (snapshotFailed && COMPLETED.equals(status)) { + status = PARTIAL; + } + + BackupRunResult backupRecord = new BackupRunResult( + archive.id(), formatTime(startedAt), recordCurrentTime(), status, + recordedResults, archive, errorMessage); + backups.addNewBackupRecord(backupRecord); + notified = true; + webhook.notifyRun(backupRecord); + return backupRecord; + } catch (RuntimeException e) { + if (started && !notified) { + webhook.notifyFailure(e.getMessage()); + } + throw e; + } finally { + if (runDirectory != null) { + try { + archiveService.removeRunDirectory(runDirectory); + LOGGER.debug("Run directory cleaned up: {}", runDirectory); + } catch (RuntimeException e) { + LOGGER.error("Failed to clean up run directory {}", runDirectory, e); + } + } + } + } + + private List copyServices(List services, Path runDir, Set excluded) { + Map tallies = new LinkedHashMap<>(); + List unresolved = new ArrayList<>(); + for (ServiceDefinition service : services) { + tallies.put(service.name(), new ServiceBackupRunner.Tally(service.name())); + for (int i = 0; i < service.paths().size(); i++) { + unresolved.add(new PathCoverage.Item(service, i)); + } + } + + int round = 0; + while (!unresolved.isEmpty()) { + round++; + List owners = PathCoverage.plan(unresolved); + Map> byService = new LinkedHashMap<>(); + owners.forEach(owner -> byService.computeIfAbsent(owner.item().service().name(), name -> new ArrayList<>()).add(owner)); + LOGGER.debug("Copy round {}: {} path(s), {} left", round, owners.size(), unresolved.size()); + + Map> futures = new LinkedHashMap<>(); + byService.forEach((name, serviceOwners) -> { + ServiceDefinition service = serviceOwners.get(0).item().service(); + List indexes = serviceOwners.stream().map(owner -> owner.item().index()).toList(); + List> covered = serviceOwners.stream() + .map(owner -> owner.covered().stream().map(PathCoverage.Item::key).collect(Collectors.toUnmodifiableSet())) + .toList(); + futures.put(name, CompletableFuture + .supplyAsync(() -> runner.copyPaths(service, indexes, runDir, excluded, covered), runnerExecutor) + .exceptionally(t -> { + Throwable cause = unwrap(t); + LOGGER.warn("Runner {} failed unexpectedly", name, cause); + return failedRound(service, indexes, cause); + })); + }); + + Map copies = new HashMap<>(); + futures.forEach((name, future) -> { + ServiceBackupRunner.ServiceRound finished = future.join(); + tallies.get(name).add(finished); + ServiceDefinition service = byService.get(name).get(0).item().service(); + finished.paths().forEach(copy -> copies.put(new PathCoverage.Item(service, copy.index()), copy)); + }); + + List resolved = new ArrayList<>(); + for (PathCoverage.Owner owner : owners) { + resolved.add(owner.item()); + ServiceBackupRunner.PathCopy copy = copies.get(owner.item()); + if (copy == null || !copy.copied()) { + owner.covered().forEach(item -> LOGGER.info("[{}] {} was covered by {} which failed, copying it on its own", + item.service().name(), item.path(), owner.item().path())); + continue; + } + for (PathCoverage.Item item : owner.covered()) { + if (copy.confirmed().contains(item.key())) { + tallies.get(item.service().name()).addCovered(1); + resolved.add(item); + LOGGER.info("[{}] {} is included in {} ({})", item.service().name(), item.path(), owner.item().path(), owner.item().service().name()); + } else { + LOGGER.info("[{}] {} was not found inside {}, copying it on its own", item.service().name(), item.path(), owner.item().path()); + } + } + } + unresolved.removeAll(resolved); + } + return tallies.values().stream().map(ServiceBackupRunner.Tally::result).toList(); + } + + private static ServiceBackupRunner.ServiceRound failedRound(ServiceDefinition service, List indexes, Throwable cause) { + List copies = indexes.stream() + .map(index -> new ServiceBackupRunner.PathCopy(index, service.paths().get(index), false, null, Set.of())) + .toList(); + return new ServiceBackupRunner.ServiceRound(Objects.requireNonNullElse(cause.getMessage(), cause.toString()), copies); + } + + private DatabaseSnapshotService.Outcome snapshotDatabase(Path runDir) { + try { + return snapshotService.snapshotWithHostPath(runDir); + } catch (RuntimeException e) { + LOGGER.warn("[{}] Failed to snapshot database", SNAPSHOT_NAME, e); + return new DatabaseSnapshotService.Outcome(failedResult(SNAPSHOT_NAME, e), null); + } + } + + private static Throwable unwrap(Throwable t) { + return (t instanceof CompletionException && t.getCause() != null) ? t.getCause() : t; + } + + private static BackupServiceResult failedResult(String serviceName, Throwable cause) { + String timestamp = recordCurrentTime(); + return new BackupServiceResult( + null, + FAILED, + timestamp, + timestamp, + serviceName, + Objects.requireNonNullElse(cause.getMessage(), cause.toString()) + ); + } + + public void servicesChanged() { + scheduleService.releaseDeferral(); + } + + public boolean isRunning() { + return lifecycle.isRunning(); + } + + public Duration getInterval() { + return scheduleService.getInterval(); + } + + public Duration updateInterval(Duration duration) { + return scheduleService.updateInterval(duration); + } + + @PreDestroy + public void shutdownRunnerExecutor() { + runnerExecutor.shutdownNow(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupRunLifecycle.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupRunLifecycle.java new file mode 100644 index 0000000..e3c8feb --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupRunLifecycle.java @@ -0,0 +1,111 @@ +package wellatleastitried.mediagarrdServer.service; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; + +import java.time.Instant; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.function.Supplier; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import wellatleastitried.mediagarrdServer.model.BackupRunResult; + +@Component +public class BackupRunLifecycle { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupRunLifecycle.class); + + private final RunStatusBroadcaster broadcaster; + private final AtomicBoolean running = new AtomicBoolean(false); + private final Object transitionLock = new Object(); + private final ReentrantReadWriteLock configLock = new ReentrantReadWriteLock(); + + public BackupRunLifecycle(RunStatusBroadcaster broadcaster) { + this.broadcaster = broadcaster; + } + + @FunctionalInterface + public interface RunBody { + BackupRunResult execute(Run run); + } + + public final class Run { + + private final Instant startedAt; + private boolean started; + + private Run(Instant startedAt) { + this.startedAt = startedAt; + } + + public void markStarted() { + if (started) { + return; + } + started = true; + publishStarted(startedAt); + } + } + + public BackupRunResult run(Instant startedAt, RunBody body) { + synchronized (transitionLock) { + if (!running.compareAndSet(false, true)) { + LOGGER.warn("runBackup() called while backup already in progress, rejecting"); + throw new RunRejectedException("A backup run is already in progress"); + } + } + Run run = new Run(startedAt); + String finalStatus = FAILED; + try { + configLock.readLock().lock(); + try { + BackupRunResult result = body.execute(run); + finalStatus = result.status(); + return result; + } finally { + configLock.readLock().unlock(); + } + } finally { + synchronized (transitionLock) { + running.set(false); + if (run.started) { + publishFinished(finalStatus, startedAt); + } + } + } + } + + public T whileIdle(Supplier configChange) { + if (!configLock.writeLock().tryLock()) { + throw new BackupInProgressException("Configuration cannot be changed while a backup is running, try again once it finishes"); + } + try { + return configChange.get(); + } finally { + configLock.writeLock().unlock(); + } + } + + public boolean isRunning() { + return running.get(); + } + + private void publishStarted(Instant startedAt) { + try { + broadcaster.publishStarted(startedAt); + } catch (RuntimeException e) { + LOGGER.warn("Failed to publish run-started event", e); + } + } + + private void publishFinished(String status, Instant startedAt) { + try { + broadcaster.publishFinished(status, startedAt, Instant.now()); + } catch (RuntimeException e) { + LOGGER.warn("Failed to publish run-finished event", e); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java new file mode 100644 index 0000000..1034c12 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java @@ -0,0 +1,185 @@ +package wellatleastitried.mediagarrdServer.service; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.BACKUP_INTERVAL_SETTING; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.format.DateTimeParseException; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.repository.BackupRecordRepository; +import wellatleastitried.mediagarrdServer.repository.SettingsRepository; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; + +@Service +public class BackupScheduleService { + + public static final Duration MIN_INTERVAL = Duration.ofMinutes(15); + public static final Duration MAX_INTERVAL = Duration.ofDays(365); + private static final Duration DEFAULT_INTERVAL = Duration.ofHours(12); + private static final Logger LOGGER = LoggerFactory.getLogger(BackupScheduleService.class); + + private final MediaGarrdProperties properties; + private final SettingsRepository settings; + private final Clock clock; + private final AtomicReference currentInterval; + private final AtomicReference nextRun; + private final AtomicBoolean deferred = new AtomicBoolean(); + private final AtomicBoolean awaitingSetup = new AtomicBoolean(); + private final AtomicReference lastRunStarted = new AtomicReference<>(); + private final BackupRecordRepository backups; + private final SetupService setup; + + @Autowired + public BackupScheduleService(MediaGarrdProperties properties, SettingsRepository settings, BackupRecordRepository backups, SetupService setup) { + this(properties, settings, backups, setup, Clock.systemUTC()); + } + + BackupScheduleService(MediaGarrdProperties properties, SettingsRepository settings, BackupRecordRepository backups, SetupService setup, Clock clock) { + this.properties = properties; + this.settings = settings; + this.backups = backups; + this.setup = setup; + this.clock = clock; + Duration interval = storedOrConfiguredInterval(); + this.currentInterval = new AtomicReference<>(interval); + this.nextRun = new AtomicReference<>(computeNextRun(interval)); + LOGGER.info("Backup schedule initialized: interval={}, firstRunAt={}", interval, nextRun.get()); + } + + private Duration storedOrConfiguredInterval() { + return settings.fetchSetting(BACKUP_INTERVAL_SETTING) + .flatMap(BackupScheduleService::parse) + .orElseGet(() -> fromProperties(properties.getBackupInterval())); + } + + public void reloadFromSettings() { + Duration interval = storedOrConfiguredInterval(); + Instant next = computeNextRun(interval); + currentInterval.set(interval); + nextRun.set(next); + deferred.set(false); + LOGGER.info("Backup schedule reloaded from the settings: interval={}, nextRunAt={}", interval, next); + } + + public Duration getInterval() { + return currentInterval.get(); + } + + public Instant getNextRun() { + return nextRun.get(); + } + + public Duration updateInterval(Duration interval) { + validate(interval); + Instant next = computeNextRun(interval); + settings.saveSetting(BACKUP_INTERVAL_SETTING, interval.toString()); + currentInterval.set(interval); + nextRun.set(next); + deferred.set(false); + LOGGER.info("Backup interval updated: newInterval={}, nextRunAt={}", interval, next); + return interval; + } + + public boolean dueNow() { + Instant now = clock.instant(); + if (awaitingSetup.get() && setup.isCompleted() && awaitingSetup.compareAndSet(true, false)) { + nextRun.set(now); + LOGGER.info("Setup is completed, the first scheduled backup is due now"); + } + Instant current = nextRun.get(); + return !now.isBefore(current); + } + + public void markRunStarted() { + lastRunStarted.set(clock.instant()); + Instant next = clock.instant().plus(currentInterval.get()); + nextRun.set(next); + awaitingSetup.set(false); + deferred.set(false); + LOGGER.info("Backup run started: nextScheduledRun={}", next); + } + + public void deferNextRun() { + Instant next = clock.instant().plus(currentInterval.get()); + nextRun.set(next); + awaitingSetup.set(false); + deferred.set(true); + LOGGER.info("Nothing to back up yet, next scheduled check at {}", next); + } + + public void releaseDeferral() { + if (deferred.compareAndSet(true, false)) { + nextRun.set(clock.instant()); + LOGGER.info("Services are configured, the next scheduled backup is due now"); + } + } + + private Instant computeNextRun(Duration interval) { + Instant now = clock.instant(); + awaitingSetup.set(false); + Optional recorded; + try { + recorded = backups.fetchLastSuccessfulStartTime(); + } catch (RuntimeException e) { + LOGGER.warn("Could not read the last successful backup, the next scheduled backup is one interval from now", e); + return now.plus(interval); + } + Optional last = recorded.map(this::laterThanThisRun).or(() -> Optional.ofNullable(lastRunStarted.get())); + if (last.isPresent()) { + Instant due = last.get().plus(interval); + return due.isAfter(now) && !last.get().isAfter(now) ? due : now; + } + if (setup.isCompleted()) { + return now; + } + awaitingSetup.set(true); + return now.plus(interval); + } + + private Instant laterThanThisRun(Instant recorded) { + Instant started = lastRunStarted.get(); + return started != null && started.isAfter(recorded) && !started.isAfter(clock.instant()) ? started : recorded; + } + + private static Optional parse(String stored) { + try { + Duration interval = Duration.parse(stored); + if (!inRange(interval)) { + LOGGER.warn("Ignoring out-of-range stored backup interval: {}", LogSanitizer.clean(stored)); + return Optional.empty(); + } + return Optional.of(interval); + } catch (DateTimeParseException e) { + LOGGER.warn("Ignoring invalid stored backup interval: {}", LogSanitizer.clean(stored)); + return Optional.empty(); + } + } + + private static Duration fromProperties(Duration configured) { + if (!inRange(configured)) { + LOGGER.warn("Ignoring out-of-range MEDIAGARRD_BACKUP_INTERVAL {}, using {}", configured, DEFAULT_INTERVAL); + return DEFAULT_INTERVAL; + } + return configured; + } + + private static boolean inRange(Duration interval) { + return interval != null && interval.compareTo(MIN_INTERVAL) >= 0 && interval.compareTo(MAX_INTERVAL) <= 0; + } + + private static void validate(Duration interval) { + if (!inRange(interval)) { + throw new IllegalArgumentException("Backup interval must be between 15 minutes and 365 days"); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironment.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironment.java new file mode 100644 index 0000000..bd05951 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironment.java @@ -0,0 +1,70 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.Supplier; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class ContainerEnvironment { + + private static final Logger LOGGER = LoggerFactory.getLogger(ContainerEnvironment.class); + + private static final Pattern CONTAINER_ID = Pattern.compile("containers/([0-9a-f]{64})/"); + private static final Set CONTAINER_OWNED_FILES = Set.of("/etc/hostname", "/etc/resolv.conf", "/etc/hosts"); + + private final Path mountInfo; + private final List markers; + private final Supplier hostname; + + @Autowired + public ContainerEnvironment() { + this(Path.of("/proc/self/mountinfo"), List.of(Path.of("/.dockerenv"), Path.of("/run/.containerenv")), () -> System.getenv("HOSTNAME")); + } + + ContainerEnvironment(Path mountInfo, List markers, Supplier hostname) { + this.mountInfo = mountInfo; + this.markers = markers; + this.hostname = hostname; + } + + public boolean insideContainer() { + return markers.stream().anyMatch(Files::exists) || mountedContainerId().isPresent(); + } + + public List containerIdCandidates() { + Optional mounted = mountedContainerId(); + if (mounted.isPresent()) { + return List.of(mounted.get()); + } + String name = hostname.get(); + return name == null || name.isBlank() ? List.of() : List.of(name.strip()); + } + + private Optional mountedContainerId() { + try { + for (String line : Files.readAllLines(mountInfo)) { + String[] fields = line.split(" "); + if (fields.length > 4 && CONTAINER_OWNED_FILES.contains(fields[4])) { + Matcher matcher = CONTAINER_ID.matcher(line); + if (matcher.find()) { + return Optional.of(matcher.group(1)); + } + } + } + } catch (IOException | RuntimeException e) { + LOGGER.debug("Unable to read {}", mountInfo, e); + } + return Optional.empty(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolver.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolver.java new file mode 100644 index 0000000..90f8b54 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolver.java @@ -0,0 +1,84 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import com.github.dockerjava.api.command.InspectContainerResponse; + +@Component +public class DatabaseHostPathResolver { + + private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseHostPathResolver.class); + + private final DockerService docker; + private final ContainerEnvironment environment; + + public DatabaseHostPathResolver(DockerService docker, ContainerEnvironment environment) { + this.docker = docker; + this.environment = environment; + } + + public Path resolve(Path databaseFile) throws IOException { + Path real = databaseFile.toRealPath(); + if (!environment.insideContainer()) { + return real; + } + + List candidates = environment.containerIdCandidates(); + if (candidates.isEmpty()) { + throw new IOException("The server is running in a container but its container ID could not be determined"); + } + + List failures = new ArrayList<>(); + for (String containerId : candidates) { + try { + Path hostPath = mapThroughMounts(real, docker.mountsOf(containerId)); + if (hostPath != null) { + return hostPath; + } + failures.add(containerId + ": no mount covers " + real); + } catch (IOException e) { + failures.add(containerId + ": " + e.getMessage()); + } catch (RuntimeException e) { + LOGGER.debug("Unable to inspect container {}", containerId, e); + failures.add(containerId + ": " + e.getMessage()); + } + } + throw new IOException("Unable to resolve the host path of " + real + " (" + String.join("; ", failures) + ")"); + } + + private static Path mapThroughMounts(Path real, List mounts) throws IOException { + InspectContainerResponse.Mount best = null; + Path bestDestination = null; + for (InspectContainerResponse.Mount mount : mounts) { + if (mount.getDestination() == null || mount.getDestination().getPath() == null) { + continue; + } + Path destination = Path.of(mount.getDestination().getPath()).normalize(); + if (real.startsWith(destination) + && (bestDestination == null || destination.getNameCount() > bestDestination.getNameCount())) { + best = mount; + bestDestination = destination; + } + } + if (best == null) { + return null; + } + String source = best.getSource(); + if (source == null || source.isBlank()) { + throw new IOException("the mount at " + bestDestination + " has no host source"); + } + Path sourcePath = Path.of(source); + Path hostPath = sourcePath.resolve(bestDestination.relativize(real).toString()).normalize(); + if (!sourcePath.isAbsolute() || hostPath.equals(hostPath.getRoot()) || !hostPath.startsWith(sourcePath.normalize())) { + throw new IOException("the mount source " + source + " does not give a usable host path"); + } + return hostPath; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseRebuildHandler.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseRebuildHandler.java new file mode 100644 index 0000000..d98e0df --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseRebuildHandler.java @@ -0,0 +1,32 @@ +package wellatleastitried.mediagarrdServer.service; + +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +import wellatleastitried.mediagarrdServer.repository.SqliteDatabase; + +@Component +@Lazy(false) +public class DatabaseRebuildHandler { + + private final PairingService pairing; + private final RunStatusBroadcaster broadcaster; + private final BackupArchiveService archives; + private final BackupScheduleService schedule; + + public DatabaseRebuildHandler(SqliteDatabase database, PairingService pairing, RunStatusBroadcaster broadcaster, + BackupArchiveService archives, BackupScheduleService schedule) { + this.pairing = pairing; + this.broadcaster = broadcaster; + this.archives = archives; + this.schedule = schedule; + database.addRebuildListener(this::reset); + } + + void reset() { + pairing.resetAfterRebuild(); + archives.reloadFromSettings(); + schedule.reloadFromSettings(); + broadcaster.closeAll(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java new file mode 100644 index 0000000..9f9d541 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java @@ -0,0 +1,114 @@ +package wellatleastitried.mediagarrdServer.service; + +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.recordCurrentTime; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +import org.apache.commons.compress.archivers.zip.UnixStat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.repository.SqliteDatabase; + +@Service +public class DatabaseSnapshotService { + + private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseSnapshotService.class); + + static final String SERVICE_NAME = "_mediagarrd-server"; + static final String PART_DIRECTORY = ".mediagarrd-server"; + static final String PART_NAME = "database" + ZipPartWriter.PART_SUFFIX; + private static final List DATABASE_SIDECAR_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); + private static final String SNAPSHOT_FILE = "snapshot.db"; + + private final SqliteDatabase db; + private final DatabaseHostPathResolver hostPaths; + private final ZipCompression compression; + + public DatabaseSnapshotService(SqliteDatabase db, DatabaseHostPathResolver hostPaths, ZipCompression compression) { + this.db = db; + this.hostPaths = hostPaths; + this.compression = compression; + } + + public record Outcome(BackupServiceResult result, Path hostPath) {} + + public BackupServiceResult snapshot(Path runDirectory) { + return snapshotWithHostPath(runDirectory).result(); + } + + public Outcome snapshotWithHostPath(Path runDirectory) { + String startTime = recordCurrentTime(); + Path directory = runDirectory.resolve(PART_DIRECTORY); + Path snapshot = directory.resolve(SNAPSHOT_FILE); + Path part = directory.resolve(PART_NAME); + Path hostPath = null; + try { + if (!Files.isRegularFile(db.databaseFile())) { + throw new IOException("Database file " + db.databaseFile() + " does not exist"); + } + hostPath = hostPaths.resolve(db.databaseFile()); + Files.createDirectories(directory); + db.snapshotTo(snapshot); + writePart(snapshot, hostPath, part); + LOGGER.info("[{}] Snapshotted database {} as {}", SERVICE_NAME, db.databaseFile(), hostPath); + return new Outcome(new BackupServiceResult(null, COMPLETED, startTime, recordCurrentTime(), SERVICE_NAME, null), hostPath); + } catch (IOException | SQLException | RuntimeException e) { + LOGGER.warn("[{}] Failed to snapshot database", SERVICE_NAME, e); + discardQuietly(part); + return new Outcome(new BackupServiceResult(null, FAILED, startTime, recordCurrentTime(), SERVICE_NAME, + Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName())), hostPath); + } finally { + deleteQuietly(snapshot); + } + } + + static String entryName(Path hostPath) { + return hostPath.getRoot().relativize(hostPath).toString(); + } + + static Set reservedNames(Path hostPath) { + String name = entryName(hostPath); + return DATABASE_SIDECAR_SUFFIXES.stream().map(suffix -> name + suffix).collect(Collectors.toUnmodifiableSet()); + } + + private void writePart(Path snapshot, Path hostPath, Path part) throws IOException { + Map attributes = Files.readAttributes(db.databaseFile(), "unix:mode,uid,gid,lastModifiedTime"); + try (var writer = new ZipPartWriter(part, compression); InputStream content = Files.newInputStream(snapshot)) { + writer.addEntry(entryName(hostPath), UnixStat.FILE_FLAG | ((Integer) attributes.get("mode") & 07777), + ((Integer) attributes.get("uid")).longValue(), ((Integer) attributes.get("gid")).longValue(), + ((FileTime) attributes.get("lastModifiedTime")).toMillis(), Files.size(snapshot), content); + writer.complete(); + } + } + + private static void discardQuietly(Path part) { + try { + ZipPartWriter.discard(part); + } catch (IOException e) { + LOGGER.warn("Unable to remove {}", part, e); + } + } + + private static void deleteQuietly(Path file) { + try { + Files.deleteIfExists(file); + } catch (IOException e) { + LOGGER.warn("Unable to remove {}", file, e); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java new file mode 100644 index 0000000..a937f2d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java @@ -0,0 +1,132 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.InputStream; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.HostConfig; +import com.github.dockerjava.api.model.Mount; +import com.github.dockerjava.api.model.MountType; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.utilities.Sha256; + +@Service +public class DockerService { + + private static final Logger LOGGER = LoggerFactory.getLogger(DockerService.class); + + static final String SERVICE_LABEL = "mediagarrd.service"; + static final String CONFIG_HASH_LABEL = "mediagarrd.config-hash"; + static final String MOUNT_ROOT = "/mnt"; + private static final long IMAGE_PULL_TIMEOUT_MINUTES = 10; + + private final DockerClient client; + private final String helperImage; + + public DockerService(DockerClient client, MediaGarrdProperties properties) { + this.client = client; + this.helperImage = properties.getHelperImage(); + } + + public String containerFor(ServiceDefinition service) { + String hash = configHash(service); + String reusable = null; + for (Container container : managedContainers(service.name())) { + if (reusable == null && hash.equals(container.getLabels().get(CONFIG_HASH_LABEL))) { + reusable = container.getId(); + LOGGER.debug("[{}] Reusing helper container {}", service.name(), reusable); + continue; + } + LOGGER.info("[{}] Removing stale helper container {}", service.name(), container.getId()); + removeContainer(container.getId()); + } + return reusable != null ? reusable : createContainer(service, hash); + } + + public InputStream copyFrom(String containerId, String hostPath) { + return client.copyArchiveFromContainerCmd(containerId, containerPath(hostPath)).exec(); + } + + public List mountsOf(String containerId) { + List mounts = client.inspectContainerCmd(containerId).exec().getMounts(); + return mounts == null ? List.of() : mounts; + } + + public void removeContainers(String serviceName) { + try { + managedContainers(serviceName).forEach(container -> removeContainer(container.getId())); + } catch (RuntimeException e) { + LOGGER.warn("[{}] Unable to remove helper containers", serviceName, e); + } + } + + static String containerPath(String hostPath) { + return MOUNT_ROOT + hostPath; + } + + String configHash(ServiceDefinition service) { + String fingerprint = helperImage + "\n" + String.join("\n", service.paths().stream().sorted().toList()); + return Sha256.hex(fingerprint); + } + + private List managedContainers(String serviceName) { + return client.listContainersCmd() + .withShowAll(true) + .withLabelFilter(Map.of(SERVICE_LABEL, serviceName)) + .exec(); + } + + private String createContainer(ServiceDefinition service, String hash) { + ensureHelperImage(); + List mounts = service.paths().stream() + .map(path -> new Mount() + .withType(MountType.BIND) + .withSource(path) + .withTarget(containerPath(path)) + .withReadOnly(true)) + .toList(); + String id = client.createContainerCmd(helperImage) + .withName("mediagarrd-backup-" + service.name()) + .withLabels(Map.of(SERVICE_LABEL, service.name(), CONFIG_HASH_LABEL, hash)) + .withHostConfig(HostConfig.newHostConfig().withMounts(mounts).withNetworkMode("none")) + .exec() + .getId(); + LOGGER.info("[{}] Created helper container {} with {} mount(s)", service.name(), id, mounts.size()); + return id; + } + + private synchronized void ensureHelperImage() { + try { + client.inspectImageCmd(helperImage).exec(); + } catch (NotFoundException e) { + LOGGER.info("Pulling helper image {}", helperImage); + try { + if (!client.pullImageCmd(helperImage).start().awaitCompletion(IMAGE_PULL_TIMEOUT_MINUTES, TimeUnit.MINUTES)) { + throw new IllegalStateException("Timed out pulling helper image " + helperImage); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while pulling helper image " + helperImage, ex); + } + } + } + + private void removeContainer(String containerId) { + try { + client.removeContainerCmd(containerId).withForce(true).exec(); + } catch (NotFoundException e) { + LOGGER.debug("Helper container {} already removed", containerId); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/LockedOutException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/LockedOutException.java new file mode 100644 index 0000000..36040fa --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/LockedOutException.java @@ -0,0 +1,22 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.time.Duration; + +public class LockedOutException extends RuntimeException { + + private final Duration retryAfter; + + public LockedOutException(Duration retryAfter) { + super("Too many wrong attempts, try again in " + describe(retryAfter)); + this.retryAfter = retryAfter; + } + + public Duration retryAfter() { + return retryAfter; + } + + private static String describe(Duration duration) { + long minutes = (duration.toSeconds() + 59) / 60; + return minutes <= 1 ? "a minute" : minutes + " minutes"; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/PairingException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/PairingException.java new file mode 100644 index 0000000..7429ea9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/PairingException.java @@ -0,0 +1,17 @@ +package wellatleastitried.mediagarrdServer.service; + +public class PairingException extends RuntimeException { + + public enum Reason { SETUP_INCOMPLETE, CLOSED, INVALID } + + private final Reason reason; + + public PairingException(Reason reason, String message) { + super(message); + this.reason = reason; + } + + public Reason reason() { + return reason; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/PairingService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/PairingService.java new file mode 100644 index 0000000..7a4639b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/PairingService.java @@ -0,0 +1,249 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.dto.PairResponse; +import wellatleastitried.mediagarrdServer.dto.PairingCodeDto; +import wellatleastitried.mediagarrdServer.model.PairedClient; +import wellatleastitried.mediagarrdServer.repository.PairedClientRepository; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; +import wellatleastitried.mediagarrdServer.utilities.Sha256; + +@Service +public class PairingService { + + private static final Logger LOGGER = LoggerFactory.getLogger(PairingService.class); + + static final Duration CODE_TTL = Duration.ofMinutes(10); + static final Duration CODE_LOCK_DURATION = Duration.ofMinutes(10); + static final Duration TOUCH_INTERVAL = Duration.ofMinutes(1); + static final int MAX_CODE_FAILURES = 10; + static final Duration PENDING_TTL = Duration.ofMinutes(5); + static final int MAX_OPEN_CODES = 10; + static final int MAX_PENDING = 10; + static final int CODE_LENGTH = 10; + static final int MAX_TOKEN_LENGTH = 256; + static final int MAX_CREDENTIAL_LENGTH = 64; + private static final String CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"; + private static final Pattern PIN_SHAPE = Pattern.compile("[0-9]{6}"); + private static final Pattern NAME_PATTERN = Pattern.compile("[\\p{L}\\p{N} ._()'@+-]{1,64}"); + private static final SecureRandom RANDOM = new SecureRandom(); + + private final SetupService setup; + private final PairedClientRepository pairedClients; + private final RunStatusBroadcaster broadcaster; + private final Clock clock; + private final AttemptLimiter codeLimiter; + private final Map codes = new LinkedHashMap<>(); + private final Map pending = new LinkedHashMap<>(); + private final Map lastTouched = new ConcurrentHashMap<>(); + + private record PendingPairing(String id, String name, Instant expiresAt, String codeHash, long epoch) {} + + @Autowired + public PairingService(SetupService setup, PairedClientRepository pairedClients, RunStatusBroadcaster broadcaster) { + this(setup, pairedClients, broadcaster, Clock.systemUTC()); + } + + PairingService(SetupService setup, PairedClientRepository pairedClients, RunStatusBroadcaster broadcaster, Clock clock) { + this.setup = setup; + this.pairedClients = pairedClients; + this.broadcaster = broadcaster; + this.clock = clock; + this.codeLimiter = new AttemptLimiter(MAX_CODE_FAILURES, CODE_LOCK_DURATION, clock); + } + + public synchronized PairResponse pair(String credential, String requestedName) { + String name = cleanName(requestedName); + String value = credential == null ? "" : credential.strip(); + if (value.isEmpty()) { + throw new IllegalArgumentException("A PIN or pairing code is required"); + } + if (value.length() > MAX_CREDENTIAL_LENGTH) { + throw new IllegalArgumentException("The PIN or pairing code is too long"); + } + if (!setup.isCompleted()) { + throw new PairingException(PairingException.Reason.SETUP_INCOMPLETE, "This server has not finished setup yet. Finish it on the server's /config page, then pair."); + } + if (PIN_SHAPE.matcher(value).matches()) { + return registerPending(name, null, setup.checkPairingPin(value)); + } + return registerPending(name, checkCode(value), 0); + } + + public synchronized PairingCodeDto createCode() { + Instant now = clock.instant(); + codes.values().removeIf(expiry -> !expiry.isAfter(now)); + while (codes.size() >= MAX_OPEN_CODES) { + String evicted = codes.keySet().iterator().next(); + codes.remove(evicted); + pending.values().removeIf(entry -> evicted.equals(entry.codeHash())); + } + StringBuilder code = new StringBuilder(CODE_LENGTH); + for (int i = 0; i < CODE_LENGTH; i++) { + code.append(CODE_ALPHABET.charAt(RANDOM.nextInt(CODE_ALPHABET.length()))); + } + Instant expiresAt = now.plus(CODE_TTL); + codes.put(hashToken(code.toString()), expiresAt); + LOGGER.info("Pairing code created, it expires at {}", expiresAt); + return new PairingCodeDto(code.substring(0, CODE_LENGTH / 2) + "-" + code.substring(CODE_LENGTH / 2), expiresAt); + } + + public Optional authenticate(String token) { + if (token == null || token.isEmpty() || token.length() > MAX_TOKEN_LENGTH) { + return Optional.empty(); + } + String tokenHash = hashToken(token); + Optional client = pairedClients.fetchPairedClientByTokenHash(tokenHash); + if (client.isEmpty()) { + client = confirm(tokenHash); + } + client.ifPresent(this::recordUse); + return client; + } + + public List list() { + return pairedClients.fetchPairedClients(); + } + + public boolean isPaired(String id) { + return pairedClients.fetchPairedClients().stream().anyMatch(client -> client.id().equals(id)); + } + + public synchronized boolean revoke(String id) { + boolean removed = pairedClients.removePairedClient(id); + if (removed) { + lastTouched.remove(id); + broadcaster.closeClient(id); + LOGGER.info("Client {} was unpaired", LogSanitizer.clean(id)); + if (pairedClients.countPairedClients() == 0) { + LOGGER.info("No Client is paired any more, opening pairing again"); + setup.reopenPairing(); + } + } + return removed; + } + + synchronized void resetAfterRebuild() { + codes.clear(); + pending.clear(); + lastTouched.clear(); + codeLimiter.reset(); + setup.resetAfterRebuild(); + } + + public static String hashToken(String token) { + return Sha256.hex(token); + } + + private synchronized Optional confirm(String tokenHash) { + Optional existing = pairedClients.fetchPairedClientByTokenHash(tokenHash); + if (existing.isPresent()) { + return existing; + } + PendingPairing entry = pending.get(tokenHash); + if (entry == null) { + return Optional.empty(); + } + Instant now = clock.instant(); + if (!entry.expiresAt().isAfter(now)) { + pending.remove(tokenHash); + return Optional.empty(); + } + boolean viaPin = entry.codeHash() == null; + if (viaPin && !setup.isPairingOpen(entry.epoch())) { + pending.remove(tokenHash); + return Optional.empty(); + } + boolean firstClient = pairedClients.countPairedClients() == 0; + pairedClients.addPairedClient(entry.id(), entry.name(), tokenHash, now); + pending.remove(tokenHash); + if (!viaPin && firstClient) { + setup.closeCurrentPairing(); + pending.values().removeIf(other -> other.codeHash() == null); + } + if (viaPin) { + setup.closePairing(entry.epoch()); + pending.values().removeIf(other -> other.codeHash() == null); + } else { + codes.remove(entry.codeHash()); + pending.values().removeIf(other -> entry.codeHash().equals(other.codeHash())); + } + LOGGER.info("Client {} confirmed its pairing ({})", LogSanitizer.clean(entry.name()), entry.id()); + return pairedClients.fetchPairedClientByTokenHash(tokenHash); + } + + private String checkCode(String candidate) { + codeLimiter.checkNotLocked(); + String normalized = candidate.replace("-", "").replace(" ", "").toUpperCase(Locale.ROOT); + String codeHash = hashToken(normalized); + Instant expiry = codes.get(codeHash); + if (expiry == null || !expiry.isAfter(clock.instant())) { + int failures = codeLimiter.recordFailure(); + LOGGER.warn("Rejected pairing code attempt ({}/{})", failures, MAX_CODE_FAILURES); + throw new PairingException(PairingException.Reason.INVALID, "Invalid PIN or pairing code"); + } + codeLimiter.reset(); + return codeHash; + } + + private PairResponse registerPending(String requestedName, String codeHash, long epoch) { + Instant now = clock.instant(); + pending.values().removeIf(entry -> !entry.expiresAt().isAfter(now)); + while (pending.size() >= MAX_PENDING) { + pending.remove(pending.keySet().iterator().next()); + } + byte[] bytes = new byte[32]; + RANDOM.nextBytes(bytes); + String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + byte[] idBytes = new byte[8]; + RANDOM.nextBytes(idBytes); + String id = HexFormat.of().formatHex(idBytes); + String name = requestedName != null ? requestedName : "Client " + id.substring(0, 6); + pending.put(hashToken(token), new PendingPairing(id, name, now.plus(PENDING_TTL), codeHash, epoch)); + LOGGER.info("Client pairing started: {} ({}), it is confirmed by the Client's first request with its token", LogSanitizer.clean(name), id); + return new PairResponse(token, id, name); + } + + private void recordUse(PairedClient client) { + Instant now = clock.instant(); + Instant last = lastTouched.get(client.id()); + if (last != null && now.isBefore(last.plus(TOUCH_INTERVAL))) { + return; + } + lastTouched.put(client.id(), now); + try { + pairedClients.touchPairedClient(client.id(), now); + } catch (IllegalStateException e) { + LOGGER.debug("Unable to record last use for client {}: {}", client.id(), e.getMessage()); + } + } + + private static String cleanName(String name) { + if (name == null || name.isBlank()) { + return null; + } + String stripped = name.strip(); + if (!NAME_PATTERN.matcher(stripped).matches()) { + throw new IllegalArgumentException("Name must be 1 to 64 characters: letters, digits, spaces and . _ - ( ) ' @ +"); + } + return stripped; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/PathCoverage.java b/src/main/java/wellatleastitried/mediagarrdServer/service/PathCoverage.java new file mode 100644 index 0000000..71a7d2d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/PathCoverage.java @@ -0,0 +1,60 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +final class PathCoverage { + + private static final Comparator TIE_BREAK = Comparator.comparing((Item item) -> item.service().name()).thenComparingInt(Item::index); + + record Item(ServiceDefinition service, int index) { + + String path() { + return service.paths().get(index); + } + + Path location() { + return Path.of(path()); + } + + String key() { + Path location = location(); + return location.getRoot() == null ? path() : location.getRoot().relativize(location).toString(); + } + } + + record Owner(Item item, List covered) {} + + private PathCoverage() {} + + static List plan(List unresolved) { + List owners = new ArrayList<>(); + for (Item candidate : unresolved) { + if (unresolved.stream().noneMatch(other -> other != candidate && covers(other, candidate))) { + owners.add(new Owner(candidate, new ArrayList<>())); + } + } + for (Item candidate : unresolved) { + if (owners.stream().noneMatch(owner -> owner.item() == candidate)) { + owners.stream() + .filter(owner -> candidate.location().startsWith(owner.item().location())) + .findFirst() + .ifPresent(owner -> owner.covered().add(candidate)); + } + } + return owners; + } + + private static boolean covers(Item other, Item candidate) { + Path otherLocation = other.location(); + Path candidateLocation = candidate.location(); + if (candidateLocation.equals(otherLocation)) { + return TIE_BREAK.compare(other, candidate) < 0; + } + return candidateLocation.startsWith(otherLocation); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RateLimitedException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RateLimitedException.java new file mode 100644 index 0000000..ebb99e4 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RateLimitedException.java @@ -0,0 +1,17 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.time.Duration; + +public class RateLimitedException extends RuntimeException { + + private final Duration retryAfter; + + public RateLimitedException(String message, Duration retryAfter) { + super(message); + this.retryAfter = retryAfter; + } + + public Duration retryAfter() { + return retryAfter; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RunRejectedException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RunRejectedException.java new file mode 100644 index 0000000..be998c9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RunRejectedException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.service; + +public class RunRejectedException extends IllegalStateException { + + public RunRejectedException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java new file mode 100644 index 0000000..b9edf53 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java @@ -0,0 +1,256 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import jakarta.annotation.PreDestroy; + +@Service +public class RunStatusBroadcaster { + + private static final Logger LOGGER = LoggerFactory.getLogger(RunStatusBroadcaster.class); + + static final int MAX_SUBSCRIBERS = 16; + static final long EMITTER_TIMEOUT_MS = TimeUnit.MINUTES.toMillis(6); + static final long ROLLOVER_MS = TimeUnit.SECONDS.toMillis(270); + static final long PING_INTERVAL_MS = TimeUnit.SECONDS.toMillis(20); + static final int QUEUE_CAPACITY = 8; + + private static final AtomicInteger THREAD_COUNTER = new AtomicInteger(); + private static final Message CLOSE = new Message("close", ""); + + private final Object lock = new Object(); + private final List subscribers = new ArrayList<>(); + private final int maxSubscribers; + private final long emitterTimeoutMs; + private final long pingIntervalMs; + private final long rolloverMs; + private final ThreadFactory threadFactory; + private boolean running; + private boolean shutdown; + + public RunStatusBroadcaster() { + this(MAX_SUBSCRIBERS, EMITTER_TIMEOUT_MS, PING_INTERVAL_MS, ROLLOVER_MS, RunStatusBroadcaster::newWriterThread); + } + + RunStatusBroadcaster(int maxSubscribers, long emitterTimeoutMs, long pingIntervalMs, long rolloverMs, ThreadFactory threadFactory) { + this.maxSubscribers = maxSubscribers; + this.emitterTimeoutMs = emitterTimeoutMs; + this.pingIntervalMs = pingIntervalMs; + this.rolloverMs = rolloverMs; + this.threadFactory = threadFactory; + } + + private static Thread newWriterThread(Runnable runnable) { + Thread thread = new Thread(runnable, "run-events-writer-" + THREAD_COUNTER.incrementAndGet()); + thread.setDaemon(true); + return thread; + } + + public SseEmitter subscribe() { + return subscribe(new SseEmitter(emitterTimeoutMs), null); + } + + public SseEmitter subscribe(String clientId) { + return subscribe(new SseEmitter(emitterTimeoutMs), clientId); + } + + SseEmitter subscribe(SseEmitter emitter) { + return subscribe(emitter, null); + } + + SseEmitter subscribe(SseEmitter emitter, String clientId) { + Subscriber subscriber = new Subscriber(emitter, clientId); + synchronized (lock) { + if (shutdown || subscribers.size() >= maxSubscribers) { + throw new SubscriberLimitException("Too many event stream subscribers"); + } + subscriber.queue.offer(new Message("state", stateJson(running, Instant.now()))); + subscribers.add(subscriber); + } + emitter.onTimeout(subscriber::close); + emitter.onCompletion(subscriber::ended); + emitter.onError(error -> subscriber.ended()); + Thread writer = threadFactory.newThread(subscriber::writeLoop); + writer.start(); + return emitter; + } + + public void publishStarted(Instant startedAt) { + publish("run-started", Boolean.TRUE, "{\"running\":true,\"startedAt\":\"" + startedAt + "\"}"); + } + + public void publishFinished(String status, Instant startedAt, Instant finishedAt) { + publish("run-finished", Boolean.FALSE, "{\"running\":false,\"status\":\"" + status.toUpperCase(Locale.ROOT) + + "\",\"startedAt\":\"" + startedAt + "\",\"finishedAt\":\"" + finishedAt + "\"}"); + } + + public void publishBackupsChanged() { + publish("backups-changed", null, atJson()); + } + + public void publishConfigChanged() { + publish("config-changed", null, atJson()); + } + + private static String atJson() { + return "{\"at\":\"" + Instant.now() + "\"}"; + } + + private void publish(String name, Boolean nowRunning, String json) { + Message message = new Message(name, json); + synchronized (lock) { + if (nowRunning != null) { + running = nowRunning; + } + for (Subscriber subscriber : new ArrayList<>(subscribers)) { + if (!subscriber.queue.offer(message)) { + LOGGER.warn("Event stream subscriber is not keeping up, dropping it"); + subscribers.remove(subscriber); + subscriber.close(); + } + } + } + } + + public void closeClient(String clientId) { + List toClose; + synchronized (lock) { + toClose = subscribers.stream().filter(subscriber -> clientId.equals(subscriber.clientId)).toList(); + subscribers.removeAll(toClose); + } + toClose.forEach(Subscriber::close); + } + + public void closeAll() { + List toClose; + synchronized (lock) { + toClose = new ArrayList<>(subscribers); + subscribers.clear(); + } + toClose.forEach(Subscriber::close); + } + + int subscriberCount() { + synchronized (lock) { + return subscribers.size(); + } + } + + @PreDestroy + public void shutdown() { + List toClose; + synchronized (lock) { + shutdown = true; + toClose = new ArrayList<>(subscribers); + subscribers.clear(); + } + toClose.forEach(Subscriber::close); + } + + private static String stateJson(boolean running, Instant at) { + return "{\"running\":" + running + ",\"at\":\"" + at + "\"}"; + } + + private record Message(String name, String data) { + } + + public static class SubscriberLimitException extends RuntimeException { + public SubscriberLimitException(String message) { + super(message); + } + } + + private final class Subscriber { + + private final SseEmitter emitter; + private final String clientId; + private final BlockingQueue queue = new LinkedBlockingQueue<>(QUEUE_CAPACITY); + private final AtomicBoolean closed = new AtomicBoolean(); + private final AtomicBoolean ended = new AtomicBoolean(); + + Subscriber(SseEmitter emitter, String clientId) { + this.emitter = emitter; + this.clientId = clientId; + } + + void close() { + closed.set(true); + queue.offer(CLOSE); + } + + void ended() { + ended.set(true); + synchronized (lock) { + subscribers.remove(this); + } + close(); + } + + void writeLoop() { + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(rolloverMs); + try { + while (!closed.get()) { + long remainingMs = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()); + if (remainingMs <= 0) { + break; + } + Message message = queue.poll(Math.min(pingIntervalMs, remainingMs), TimeUnit.MILLISECONDS); + if (message == null) { + if (System.nanoTime() - deadline >= 0) { + break; + } + message = new Message("ping", "{}"); + } + if (message == CLOSE || closed.get()) { + break; + } + emitter.send(SseEmitter.event().name(message.name()).data(message.data())); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (IOException | RuntimeException e) { + LOGGER.debug("Event stream write failed, dropping subscriber: {}", e.toString()); + closed.set(true); + synchronized (lock) { + subscribers.remove(this); + } + finish(e); + return; + } + synchronized (lock) { + subscribers.remove(this); + } + finish(null); + } + + private void finish(Exception error) { + if (ended.get()) { + return; + } + try { + if (error == null) { + emitter.complete(); + } else { + emitter.completeWithError(error); + } + } catch (RuntimeException e) { + LOGGER.debug("Completing the event stream failed: {}", e.toString()); + } + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java new file mode 100644 index 0000000..71e4394 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceBackupRunner.java @@ -0,0 +1,216 @@ +package wellatleastitried.mediagarrdServer.service; + +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.recordCurrentTime; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.IntStream; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.compress.archivers.zip.UnixStat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +@Service +public class ServiceBackupRunner { + + private static final Logger LOGGER = LoggerFactory.getLogger(ServiceBackupRunner.class); + + static final String PART_SUFFIX = ZipPartWriter.PART_SUFFIX; + + public record PathCopy(int index, String path, boolean copied, String error, Set confirmed) {} + + public record ServiceRound(String error, List paths) {} + + record ArchiveResult(int entries, Set confirmed) {} + + public static final class Tally { + + private final String serviceName; + private final String startTime = recordCurrentTime(); + private final List errors = new ArrayList<>(); + private String endTime = startTime; + private int copied; + + public Tally(String serviceName) { + this.serviceName = serviceName; + } + + public void add(ServiceRound round) { + if (round.error() != null && !errors.contains(round.error())) { + errors.add(round.error()); + } + for (PathCopy path : round.paths()) { + if (path.copied()) { + copied++; + } else if (path.error() != null) { + errors.add(path.error()); + } + } + endTime = recordCurrentTime(); + } + + public void addCovered(int paths) { + copied += paths; + endTime = recordCurrentTime(); + } + + public BackupServiceResult result() { + String status = errors.isEmpty() ? COMPLETED : copied > 0 ? PARTIAL : FAILED; + return new BackupServiceResult(null, status, startTime, endTime, serviceName, + errors.isEmpty() ? null : String.join("; ", errors)); + } + } + + private final DockerService docker; + private final ZipCompression compression; + + public ServiceBackupRunner(DockerService docker, ZipCompression compression) { + this.docker = docker; + this.compression = compression; + } + + public BackupServiceResult run(ServiceDefinition service, Path runDirectory) { + Tally tally = new Tally(service.name()); + tally.add(copyPaths(service, IntStream.range(0, service.paths().size()).boxed().toList(), runDirectory, Set.of(), List.of())); + return tally.result(); + } + + public ServiceRound copyPaths(ServiceDefinition service, List indexes, Path runDirectory, Set excluded, List> covered) { + Path serviceDirectory = runDirectory.resolve(service.name()).toAbsolutePath().normalize(); + List copies = new ArrayList<>(); + try { + Files.createDirectories(serviceDirectory); + String containerId = docker.containerFor(service); + for (int i = 0; i < indexes.size(); i++) { + copies.add(copyPath(containerId, service, indexes.get(i), serviceDirectory, excluded, covered.isEmpty() ? Set.of() : covered.get(i))); + } + return new ServiceRound(null, copies); + } catch (IOException | RuntimeException e) { + LOGGER.warn("[{}] Unable to prepare helper container", service.name(), e); + for (int i = copies.size(); i < indexes.size(); i++) { + int index = indexes.get(i); + copies.add(new PathCopy(index, service.paths().get(index), false, null, Set.of())); + } + return new ServiceRound(describe(e), copies); + } + } + + private PathCopy copyPath(String containerId, ServiceDefinition service, int index, Path serviceDirectory, Set excluded, Set covered) { + String hostPath = service.paths().get(index); + Path part = serviceDirectory.resolve(index + PART_SUFFIX); + try (InputStream tar = docker.copyFrom(containerId, hostPath)) { + ArchiveResult result = archive(tar, hostPath, part, compression, excluded, covered); + LOGGER.info("[{}] Copied {} ({} entries)", service.name(), hostPath, result.entries()); + return new PathCopy(index, hostPath, true, null, result.confirmed()); + } catch (IOException | RuntimeException e) { + discard(part); + LOGGER.warn("[{}] Failed to copy {}", service.name(), hostPath, e); + return new PathCopy(index, hostPath, false, hostPath + ": " + describe(e), Set.of()); + } + } + + static int archive(InputStream tarStream, String hostPath, Path part, ZipCompression compression) throws IOException { + return archive(tarStream, hostPath, part, compression, Set.of(), Set.of()).entries(); + } + + static ArchiveResult archive(InputStream tarStream, String hostPath, Path part, ZipCompression compression, Set excluded, Set covered) + throws IOException { + Path source = Path.of(hostPath); + Path base = Objects.requireNonNullElse(source.getParent(), source.getRoot()); + Set confirmed = new HashSet<>(); + + try (var tar = new TarArchiveInputStream(tarStream); var writer = new ZipPartWriter(part, compression)) { + TarArchiveEntry entry; + while ((entry = tar.getNextEntry()) != null) { + String name = entryName(base, source, entry.getName(), entry.isDirectory()); + if (excluded.contains(name)) { + writer.markSkipped(name); + LOGGER.debug("Skipping {} in {}, the database snapshot owns that path", name, hostPath); + continue; + } + if (writer.contains(name)) { + continue; + } + long modified = entry.getModTime().getTime(); + boolean content = false; + if (entry.isFIFO() || entry.isCharacterDevice() || entry.isBlockDevice()) { + writer.markSkipped(name); + LOGGER.warn("Skipping special file {} in {}", entry.getName(), hostPath); + } else if (entry.isDirectory()) { + writer.addEntry(name, UnixStat.DIR_FLAG | (entry.getMode() & 07777), entry.getLongUserId(), entry.getLongGroupId(), modified, 0, + InputStream.nullInputStream()); + content = true; + } else if (entry.isSymbolicLink() && covered.contains(name)) { + writer.markSkipped(name); + LOGGER.debug("Not storing symlink {} in {}, it is configured as its own path and is copied from its target", name, hostPath); + } else if (entry.isSymbolicLink()) { + byte[] target = entry.getLinkName().getBytes(StandardCharsets.UTF_8); + writer.addEntry(name, UnixStat.LINK_FLAG | (entry.getMode() & 07777), entry.getLongUserId(), entry.getLongGroupId(), modified, + target.length, new ByteArrayInputStream(target)); + } else if (entry.isLink()) { + if (writer.addCopy(name, entryName(base, source, entry.getLinkName(), false))) { + content = true; + } else { + writer.markSkipped(name); + LOGGER.warn("Skipping hard link {} in {}, its target was skipped", entry.getName(), hostPath); + } + } else if (entry.isFile()) { + writer.addEntry(name, UnixStat.FILE_FLAG | (entry.getMode() & 07777), entry.getLongUserId(), entry.getLongGroupId(), modified, + entry.getRealSize(), tar); + content = true; + } else { + writer.markSkipped(name); + LOGGER.warn("Skipping unsupported entry {} in {}", entry.getName(), hostPath); + } + if (content) { + String key = name.endsWith("/") ? name.substring(0, name.length() - 1) : name; + if (covered.contains(key)) { + confirmed.add(key); + } + } + } + int entries = writer.entryCount(); + writer.complete(); + return new ArchiveResult(entries, confirmed); + } + } + + static String entryName(Path base, Path source, String tarName, boolean directory) throws IOException { + Path resolved = base.resolve(tarName).normalize(); + if (!resolved.startsWith(source)) { + throw new IOException("Archive entry escapes " + source + ": " + tarName); + } + String name = source.getRoot().relativize(resolved).toString(); + return directory ? name + "/" : name; + } + + private static void discard(Path part) { + try { + ZipPartWriter.discard(part); + } catch (IOException e) { + LOGGER.warn("Unable to remove incomplete archive part {}", part, e); + } + } + + private static String describe(Throwable e) { + return Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName()); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceConfigService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceConfigService.java new file mode 100644 index 0000000..1a7b381 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceConfigService.java @@ -0,0 +1,82 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.util.List; + +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; + +@Service +public class ServiceConfigService { + + private final ServiceRepository services; + private final DockerService docker; + private final BackupOrchestratorService orchestrator; + private final BackupRunLifecycle lifecycle; + private final RunStatusBroadcaster broadcaster; + + public ServiceConfigService( + ServiceRepository services, + DockerService docker, + BackupOrchestratorService orchestrator, + BackupRunLifecycle lifecycle, + RunStatusBroadcaster broadcaster + ) { + this.services = services; + this.docker = docker; + this.orchestrator = orchestrator; + this.lifecycle = lifecycle; + this.broadcaster = broadcaster; + } + + public List list() { + return services.fetchServices(); + } + + public ServiceDefinition add(ServiceDefinition service) { + return lifecycle.whileIdle(() -> { + requireNameFree(service.name()); + services.addService(service); + orchestrator.servicesChanged(); + broadcaster.publishConfigChanged(); + return service; + }); + } + + public ServiceDefinition update(String name, ServiceDefinition service) { + return lifecycle.whileIdle(() -> { + String currentName = require(name).name(); + if (!service.name().equalsIgnoreCase(currentName)) { + requireNameFree(service.name()); + } + services.updateService(currentName, service); + if (!service.name().equals(currentName)) { + docker.removeContainers(currentName); + } + orchestrator.servicesChanged(); + broadcaster.publishConfigChanged(); + return service; + }); + } + + public void remove(String name) { + lifecycle.whileIdle(() -> { + String currentName = require(name).name(); + services.removeService(currentName); + docker.removeContainers(currentName); + broadcaster.publishConfigChanged(); + return null; + }); + } + + private ServiceDefinition require(String name) { + return services.fetchService(name).orElseThrow(() -> new ServiceNotFoundException("Service not found: " + name)); + } + + private void requireNameFree(String name) { + if (services.fetchService(name).isPresent()) { + throw new ServiceConflictException("Service already exists: " + name); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceConflictException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceConflictException.java new file mode 100644 index 0000000..d60c501 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceConflictException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.service; + +public class ServiceConflictException extends RuntimeException { + + public ServiceConflictException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceNotFoundException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceNotFoundException.java new file mode 100644 index 0000000..9bad642 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ServiceNotFoundException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.service; + +public class ServiceNotFoundException extends RuntimeException { + + public ServiceNotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/SetupAlreadyCompleteException.java b/src/main/java/wellatleastitried/mediagarrdServer/service/SetupAlreadyCompleteException.java new file mode 100644 index 0000000..019c011 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/SetupAlreadyCompleteException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.service; + +public class SetupAlreadyCompleteException extends IllegalStateException { + + public SetupAlreadyCompleteException() { + super("Setup is already complete"); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/SetupService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/SetupService.java new file mode 100644 index 0000000..f2f79cb --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/SetupService.java @@ -0,0 +1,233 @@ +package wellatleastitried.mediagarrdServer.service; + +import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.recordCurrentTime; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.SETUP_COMPLETED_SETTING; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Optional; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.repository.PairedClientRepository; +import wellatleastitried.mediagarrdServer.repository.SettingsRepository; + +@Service +@Lazy(false) +public class SetupService { + + private static final Logger LOGGER = LoggerFactory.getLogger(SetupService.class); + + static final int MAX_FAILED_ATTEMPTS = 5; + static final Duration LOCK_DURATION = Duration.ofMinutes(10); + static final Duration SESSION_IDLE_TIMEOUT = Duration.ofMinutes(30); + static final int MAX_PIN_LENGTH = 64; + private static final SecureRandom RANDOM = new SecureRandom(); + + private final SettingsRepository settings; + private final PairedClientRepository pairedClients; + private final AttemptLimiter limiter; + private final Clock clock; + private final boolean openPairingOnStart; + private final Map sessions = new ConcurrentHashMap<>(); + private volatile boolean completed; + private boolean pairingOpen; + private long pairingEpoch; + private String pin; + + @Autowired + public SetupService(SettingsRepository settings, PairedClientRepository pairedClients, MediaGarrdProperties properties) { + this(settings, pairedClients, properties.isOpenPairing(), Clock.systemUTC()); + } + + SetupService(SettingsRepository settings, PairedClientRepository pairedClients, boolean openPairing, Clock clock) { + this.settings = settings; + this.pairedClients = pairedClients; + this.clock = clock; + this.limiter = new AttemptLimiter(MAX_FAILED_ATTEMPTS, LOCK_DURATION, clock); + this.openPairingOnStart = openPairing; + applyStoredState(); + } + + synchronized void resetAfterRebuild() { + sessions.clear(); + limiter.reset(); + pairingOpen = false; + pairingEpoch++; + pin = null; + applyStoredState(); + if (!completed) { + LOGGER.warn("The database was damaged and has been replaced with an empty one. Setup is open again with the Setup PIN logged above: " + + "enter it at /config to configure the server again, or restore an archive first. Paired Clients must pair again"); + } else { + LOGGER.warn("The database was damaged and has been replaced. Clients that paired before must pair again"); + } + } + + private void applyStoredState() { + this.completed = settings.fetchSetting(SETUP_COMPLETED_SETTING).isPresent(); + if (!completed) { + rotatePin(); + } else if (openPairingOnStart) { + LOGGER.warn("MEDIAGARRD_OPEN_PAIRING is set, pairing is open on every start while it is set. Remove it once the Client is paired"); + openPairing(); + } else if (pairedClients.countPairedClients() == 0) { + LOGGER.info("Setup is completed but no Client is paired"); + openPairing(); + } else { + LOGGER.info("Setup already completed, the web setup page is disabled and pairing is closed. " + + "Request a pairing code from a paired Client, or restart with MEDIAGARRD_OPEN_PAIRING=true to print a new PIN"); + } + } + + public boolean isCompleted() { + return completed; + } + + public boolean canConfigure(String sessionToken) { + if (completed || sessionToken == null) { + return false; + } + Instant now = clock.instant(); + return sessions.computeIfPresent(sessionToken, (token, lastSeen) -> expired(lastSeen, now) ? null : now) != null; + } + + public synchronized boolean isPairingOpen() { + return pairingOpen; + } + + public synchronized Optional startSession(String candidate) { + if (completed) { + return Optional.empty(); + } + if (candidate != null && candidate.length() > MAX_PIN_LENGTH) { + throw new IllegalArgumentException("PIN is too long"); + } + limiter.checkNotLocked(); + if (!pinMatches(candidate)) { + rejectPin("setup"); + return Optional.empty(); + } + limiter.reset(); + byte[] token = new byte[32]; + RANDOM.nextBytes(token); + String session = HexFormat.of().formatHex(token); + Instant now = clock.instant(); + sessions.values().removeIf(lastSeen -> expired(lastSeen, now)); + sessions.put(session, now); + LOGGER.info("Setup PIN accepted, a new PIN is required for any other device"); + rotatePin(); + return Optional.of(session); + } + + public synchronized String complete() { + if (completed) { + throw new SetupAlreadyCompleteException(); + } + settings.saveSetting(SETUP_COMPLETED_SETTING, recordCurrentTime()); + completed = true; + sessions.clear(); + limiter.reset(); + LOGGER.info("Setup completed, the web setup page is now disabled"); + if (pairedClients.countPairedClients() == 0) { + openPairing(); + } else { + pin = null; + } + return pin; + } + + synchronized long checkPairingPin(String candidate) { + if (!completed) { + throw new PairingException(PairingException.Reason.SETUP_INCOMPLETE, "This server has not finished setup yet. Finish it on the server's /config page, then pair."); + } + limiter.checkNotLocked(); + if (!pairingOpen) { + throw new PairingException(PairingException.Reason.CLOSED, + "Pairing is closed. Ask a paired Client for a pairing code, or restart the server with MEDIAGARRD_OPEN_PAIRING=true"); + } + if (!pinMatches(candidate)) { + rejectPin("pairing"); + throw new PairingException(PairingException.Reason.INVALID, "Invalid PIN or pairing code"); + } + LOGGER.info("Pairing PIN accepted, pairing closes once the Client has used its token"); + return pairingEpoch; + } + + synchronized boolean isPairingOpen(long epoch) { + return pairingOpen && pairingEpoch == epoch; + } + + synchronized boolean closePairing(long epoch) { + if (!isPairingOpen(epoch)) { + return false; + } + limiter.reset(); + pairingOpen = false; + pin = null; + LOGGER.info("Pairing is now closed"); + return true; + } + + synchronized boolean closeCurrentPairing() { + return closePairing(pairingEpoch); + } + + synchronized void reopenPairing() { + if (completed && !pairingOpen) { + openPairing(); + } + } + + synchronized String currentPin() { + return pin; + } + + private void openPairing() { + pairingOpen = true; + pairingEpoch++; + rotatePin(); + } + + private static boolean expired(Instant lastSeen, Instant now) { + return !lastSeen.plus(SESSION_IDLE_TIMEOUT).isAfter(now); + } + + private void rejectPin(String purpose) { + int failures = limiter.recordFailure(); + LOGGER.warn("Rejected {} PIN attempt ({}/{})", purpose, failures, MAX_FAILED_ATTEMPTS); + if (limiter.isLockedNow()) { + LOGGER.warn("PIN entry is locked for {} minutes after too many wrong attempts", LOCK_DURATION.toMinutes()); + rotatePin(); + } + } + + private boolean pinMatches(String candidate) { + return pin != null && candidate != null && MessageDigest.isEqual(bytes(pin), bytes(candidate.strip())); + } + + private void rotatePin() { + pin = "%06d".formatted(RANDOM.nextInt(1_000_000)); + if (completed) { + LOGGER.warn("Pairing PIN: {} (enter it in the MediaGarrd Client, it stops working once a Client has paired)", pin); + } else { + LOGGER.warn("Setup PIN: {} (single use, enter it at http://:/config)", pin); + } + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/UpdateCheckService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/UpdateCheckService.java new file mode 100644 index 0000000..799880e --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/UpdateCheckService.java @@ -0,0 +1,171 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.net.http.HttpClient; +import java.time.Clock; +import java.time.Duration; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.info.BuildProperties; +import org.springframework.context.annotation.Lazy; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.JdkClientHttpRequestFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClient; +import org.springframework.web.client.RestClientResponseException; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.dto.CheckState; +import wellatleastitried.mediagarrdServer.dto.VersionStatusDto; +import wellatleastitried.mediagarrdServer.utilities.SemVer; + +@Service +@Lazy(false) +public class UpdateCheckService { + + @JsonIgnoreProperties(ignoreUnknown = true) + record GithubRelease(@JsonProperty("tag_name") String tagName, @JsonProperty("html_url") String htmlUrl) { + } + + private static final Logger LOGGER = LoggerFactory.getLogger(UpdateCheckService.class); + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(3); + private static final Duration READ_TIMEOUT = Duration.ofSeconds(5); + static final Duration MIN_INTERVAL = Duration.ofHours(1); + + private final String currentVersion; + private final Optional current; + private final String repository; + private final Clock clock; + private final RestClient client; + private final AtomicReference status; + + @Autowired + public UpdateCheckService(MediaGarrdProperties properties, ObjectProvider buildProperties) { + this(properties, versionOf(buildProperties), Clock.systemUTC()); + } + + UpdateCheckService(MediaGarrdProperties properties, String currentVersion, Clock clock) { + Duration interval = properties.getUpdateCheckInterval(); + if (interval == null || interval.compareTo(MIN_INTERVAL) < 0) { + throw new IllegalStateException("mediagarrd.update-check-interval must be at least " + MIN_INTERVAL + ", was " + interval); + } + this.currentVersion = currentVersion; + this.current = SemVer.parse(currentVersion); + this.repository = properties.getUpdateRepository(); + this.clock = clock; + HttpClient httpClient = HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NORMAL) + .build(); + JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient); + requestFactory.setReadTimeout(READ_TIMEOUT); + this.client = RestClient.builder() + .baseUrl(properties.getGithubApiBaseUrl().replaceAll("/+$", "")) + .requestFactory(requestFactory) + .defaultHeader(HttpHeaders.USER_AGENT, "MediaGarrd-Server/" + (currentVersion == null ? "unknown" : currentVersion)) + .defaultHeader(HttpHeaders.ACCEPT, "application/vnd.github+json") + .build(); + this.status = new AtomicReference<>(result(CheckState.NOT_CHECKED, null, null, null)); + } + + public VersionStatusDto status() { + return status.get(); + } + + @Scheduled(initialDelayString = "PT5S", fixedDelayString = "${mediagarrd.update-check-interval:PT24H}") + public void check() { + VersionStatusDto previous = status.get(); + VersionStatusDto next = fetch(); + status.set(next); + logChange(previous, next); + } + + private VersionStatusDto fetch() { + if (current.isEmpty()) { + return result(CheckState.ERROR, null, null, "Current version is unknown"); + } + try { + GithubRelease release = client.get() + .uri("/repos/" + repository + "/releases/latest") + .retrieve() + .body(GithubRelease.class); + return fromRelease(release); + } catch (RestClientResponseException e) { + return fromHttpFailure(e); + } catch (ResourceAccessException e) { + LOGGER.debug("GitHub is unreachable", e); + return result(CheckState.ERROR, null, null, "GitHub is unreachable"); + } catch (RuntimeException e) { + LOGGER.debug("Unexpected update check failure", e); + return result(CheckState.ERROR, null, null, "Unexpected response from GitHub"); + } + } + + private VersionStatusDto fromRelease(GithubRelease release) { + Optional latest = release == null ? Optional.empty() : SemVer.parse(release.tagName()); + if (latest.isEmpty()) { + return result(CheckState.ERROR, null, null, "Latest release has an unrecognized version tag"); + } + String url = release.htmlUrl() == null || release.htmlUrl().isBlank() + ? "https://github.com/" + repository + "/releases/tag/" + release.tagName().strip() + : release.htmlUrl(); + return result(CheckState.OK, latest.get(), url, null); + } + + private VersionStatusDto fromHttpFailure(RestClientResponseException e) { + int code = e.getStatusCode().value(); + if (code == HttpStatus.NOT_FOUND.value()) { + return result(CheckState.NO_RELEASES, null, null, null); + } + boolean limitExhausted = code == HttpStatus.FORBIDDEN.value() + && e.getResponseHeaders() != null + && "0".equals(e.getResponseHeaders().getFirst("X-RateLimit-Remaining")); + if (code == HttpStatus.TOO_MANY_REQUESTS.value() || limitExhausted) { + return result(CheckState.ERROR, null, null, "GitHub rate limit reached"); + } + return result(CheckState.ERROR, null, null, "GitHub returned HTTP " + code); + } + + private VersionStatusDto result(CheckState state, SemVer latest, String url, String message) { + boolean update = state == CheckState.OK && latest != null && current.isPresent() && latest.compareTo(current.get()) > 0; + return new VersionStatusDto( + currentVersion, + latest == null ? null : latest.toString(), + url, + update, + state, + state == CheckState.NOT_CHECKED ? null : clock.instant(), + message); + } + + private static void logChange(VersionStatusDto previous, VersionStatusDto next) { + boolean changed = previous.checkState() != next.checkState() + || !Objects.equals(previous.latestVersion(), next.latestVersion()) + || !Objects.equals(previous.message(), next.message()); + if (!changed) { + LOGGER.debug("Update check unchanged: {}", next.checkState()); + } else if (next.checkState() == CheckState.ERROR) { + LOGGER.warn("Update check failed: {}", next.message()); + } else if (next.updateAvailable()) { + LOGGER.info("Update available: {} -> {} ({})", next.currentVersion(), next.latestVersion(), next.releaseUrl()); + } else { + LOGGER.info("Update check: {}, running {}", next.checkState(), next.currentVersion()); + } + } + + private static String versionOf(ObjectProvider buildProperties) { + BuildProperties build = buildProperties.getIfAvailable(); + return build == null ? null : build.getVersion(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/WebhookService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/WebhookService.java new file mode 100644 index 0000000..fc51854 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/WebhookService.java @@ -0,0 +1,316 @@ +package wellatleastitried.mediagarrdServer.service; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.FAILURE_WEBHOOK_SETTING; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.io.IOException; +import java.net.URI; +import java.text.ParseException; +import java.net.http.HttpClient; +import java.net.http.HttpConnectTimeoutException; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpTimeoutException; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import jakarta.annotation.PreDestroy; +import tools.jackson.databind.json.JsonMapper; +import wellatleastitried.mediagarrdServer.dto.WebhookStatusDto; +import wellatleastitried.mediagarrdServer.dto.WebhookTestDto; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.repository.SettingsRepository; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; +import wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils; + +@Service +public class WebhookService { + + public static final String EVENT_FAILED = "backup.failed"; + public static final String EVENT_PARTIAL = "backup.partial"; + public static final String EVENT_TEST = "test"; + + static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(5); + static final Duration DELIVERY_TIMEOUT = Duration.ofSeconds(10); + static final Duration TEST_TIMEOUT = Duration.ofSeconds(5); + static final Duration TEST_COOLDOWN = Duration.ofSeconds(10); + static final int QUEUE_CAPACITY = 16; + static final int MAX_MESSAGE_LENGTH = 1900; + static final int MAX_ERROR_LENGTH = 1000; + + private static final Logger LOGGER = LoggerFactory.getLogger(WebhookService.class); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String ZERO_WIDTH_SPACE = "​"; + + record Event(String name, Instant time, String error, List failedServices, String archiveId) {} + + private record Outcome(boolean delivered, Integer status, String error) {} + + private final SettingsRepository settings; + private final HttpClient client; + private final Clock clock; + private final Duration deliveryTimeout; + private final Duration testTimeout; + private final ThreadPoolExecutor executor; + private final AtomicReference lastTest = new AtomicReference<>(); + + @Autowired + public WebhookService(SettingsRepository settings) { + this(settings, HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NEVER) + .build(), Clock.systemUTC(), DELIVERY_TIMEOUT, TEST_TIMEOUT); + } + + WebhookService(SettingsRepository settings, HttpClient client, Clock clock, Duration deliveryTimeout, Duration testTimeout) { + this.settings = settings; + this.client = client; + this.clock = clock; + this.deliveryTimeout = deliveryTimeout; + this.testTimeout = testTimeout; + this.executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(QUEUE_CAPACITY), runnable -> { + Thread thread = new Thread(runnable, "webhook-delivery"); + thread.setDaemon(true); + return thread; + }); + } + + public WebhookStatusDto status() { + Optional url = configuredUrl(); + return new WebhookStatusDto(url.isPresent(), url.map(WebhookUrl::target).orElse(null)); + } + + public WebhookStatusDto update(String raw) { + if (raw == null || raw.isBlank()) { + settings.saveSetting(FAILURE_WEBHOOK_SETTING, ""); + LOGGER.info("Failure webhook cleared"); + return status(); + } + String url = WebhookUrl.validate(raw); + settings.saveSetting(FAILURE_WEBHOOK_SETTING, url); + LOGGER.info("Failure webhook set, target={}", WebhookUrl.target(url)); + return status(); + } + + public WebhookTestDto test() { + String url = configuredUrl().orElseThrow(() -> new IllegalArgumentException("No webhook is configured")); + claimTestSlot(); + Instant now = clock.instant(); + Outcome outcome = deliver(url, new Event(EVENT_TEST, now, null, List.of(), null), testTimeout); + LOGGER.info("Webhook test to {}: {}", WebhookUrl.host(url), outcome.delivered() ? "delivered" : outcome.error()); + return new WebhookTestDto(outcome.delivered(), outcome.status(), outcome.error()); + } + + public void notifyRun(BackupRunResult result) { + try { + String event = FAILED.equals(result.status()) ? EVENT_FAILED : PARTIAL.equals(result.status()) ? EVENT_PARTIAL : null; + if (event == null) { + return; + } + List failed = result.serviceResults().stream() + .filter(r -> !COMPLETED.equals(r.status())) + .map(BackupServiceResult::serviceName) + .toList(); + String archiveId = result.archive() == null ? null : result.archive().id(); + enqueue(new Event(event, eventTime(result), result.errorMessage(), failed, archiveId)); + } catch (RuntimeException e) { + LOGGER.warn("Could not queue the failure webhook: {}", e.getClass().getSimpleName()); + } + } + + private Instant eventTime(BackupRunResult result) { + try { + return result.endTime() == null ? clock.instant() : MediaGarrdUtils.parseTime(result.endTime()); + } catch (ParseException | RuntimeException e) { + return clock.instant(); + } + } + + public void notifyFailure(String reason) { + try { + enqueue(new Event(EVENT_FAILED, clock.instant(), reason, List.of(), null)); + } catch (RuntimeException e) { + LOGGER.warn("Could not queue the failure webhook: {}", e.getClass().getSimpleName()); + } + } + + @PreDestroy + public void shutdown() { + executor.shutdownNow(); + try { + executor.awaitTermination(2, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private Optional configuredUrl() { + return settings.fetchSetting(FAILURE_WEBHOOK_SETTING).filter(url -> !url.isBlank()); + } + + private void claimTestSlot() { + Instant now = clock.instant(); + while (true) { + Instant last = lastTest.get(); + if (last != null && now.isBefore(last.plus(TEST_COOLDOWN))) { + Duration remaining = Duration.between(now, last.plus(TEST_COOLDOWN)); + long seconds = Math.max(1, (remaining.toMillis() + 999) / 1000); + throw new RateLimitedException("Wait " + seconds + " seconds before sending another test", Duration.ofSeconds(seconds)); + } + if (lastTest.compareAndSet(last, now)) { + return; + } + } + } + + private void enqueue(Event event) { + if (configuredUrl().isEmpty()) { + return; + } + try { + executor.execute(() -> sendQueued(event)); + } catch (RejectedExecutionException e) { + LOGGER.warn("Failure webhook dropped, the delivery queue is full or stopped"); + } + } + + private void sendQueued(Event event) { + try { + Optional url = configuredUrl(); + if (url.isEmpty()) { + return; + } + Outcome outcome = deliver(url.get(), event, deliveryTimeout); + if (outcome.delivered()) { + LOGGER.info("Failure webhook delivered to {} ({})", WebhookUrl.host(url.get()), event.name()); + } else { + LOGGER.warn("Failure webhook to {} failed: {}", WebhookUrl.host(url.get()), outcome.error()); + } + } catch (RuntimeException e) { + LOGGER.warn("Failure webhook failed: {}", e.getClass().getSimpleName()); + } + } + + private Outcome deliver(String url, Event event, Duration timeout) { + try { + URI uri = WebhookUrl.parse(url); + HttpRequest request = HttpRequest.newBuilder(uri) + .timeout(timeout) + .header("Content-Type", "application/json") + .header("User-Agent", "MediaGarrd-Server") + .POST(HttpRequest.BodyPublishers.ofString(payload(uri.getHost(), uri.getPath(), event))) + .build(); + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.discarding()); + int status = response.statusCode(); + if (status >= 200 && status < 300) { + return new Outcome(true, status, null); + } + return new Outcome(false, status, "Webhook answered " + status); + } catch (HttpConnectTimeoutException e) { + return new Outcome(false, null, "Could not connect"); + } catch (HttpTimeoutException e) { + return new Outcome(false, null, "Timed out"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return new Outcome(false, null, "Interrupted"); + } catch (IOException e) { + return new Outcome(false, null, "Could not connect"); + } catch (RuntimeException e) { + return new Outcome(false, null, "Delivery failed"); + } + } + + static String payload(String host, String path, Event event) { + String lowerHost = host == null ? "" : host.toLowerCase(Locale.ROOT); + Map body = new LinkedHashMap<>(); + boolean discord = isHostOrSubdomain(lowerHost, "discord.com") || isHostOrSubdomain(lowerHost, "discordapp.com"); + boolean slackShape = lowerHost.equals("hooks.slack.com") || (discord && path != null && path.toLowerCase(Locale.ROOT).endsWith("/slack")); + if (discord && !slackShape) { + body.put("content", cap(message(event, true))); + body.put("allowed_mentions", Map.of("parse", List.of())); + } else if (slackShape) { + body.put("text", cap(escapeSlack(message(event, false)))); + } else { + String message = cap(message(event, false)); + body.put("event", event.name()); + body.put("time", event.time().toString()); + body.put("error", event.error() == null ? null : sanitize(event.error(), MAX_ERROR_LENGTH)); + body.put("failedServices", event.failedServices().stream().map(name -> sanitize(name, 128)).toList()); + if (event.archiveId() != null) { + body.put("archiveId", event.archiveId()); + } + body.put("content", message); + body.put("text", message); + } + return JSON.writeValueAsString(body); + } + + private static boolean isHostOrSubdomain(String host, String domain) { + return host.equals(domain) || host.endsWith("." + domain); + } + + private static String message(Event event, boolean discord) { + return switch (event.name()) { + case EVENT_TEST -> "MediaGarrd test notification at " + event.time(); + case EVENT_PARTIAL -> { + List names = event.failedServices().stream().map(name -> sanitize(name, 128)).toList(); + String detail = names.isEmpty() ? "see the server log" : String.join(", ", names); + yield "MediaGarrd backup partially failed (" + event.failedServices().size() + " service(s)): " + quote(detail, discord); + } + default -> { + String reason = event.error() == null || event.error().isBlank() ? "see the server log" : sanitize(event.error(), MAX_ERROR_LENGTH); + yield "MediaGarrd backup failed at " + event.time() + ": " + quote(reason, discord); + } + }; + } + + private static String quote(String text, boolean discord) { + return discord ? "`" + text.replace("`", "'") + "`" : text; + } + + static String sanitize(String text, int max) { + List lines = new ArrayList<>(); + for (String line : text.split("\\R")) { + if (!line.isBlank()) { + lines.add(LogSanitizer.clean(line.strip())); + } + } + String joined = String.join("; ", lines); + if (joined.length() > max) { + joined = joined.substring(0, max - 3) + "..."; + } + return neutralizeMentions(joined); + } + + private static String neutralizeMentions(String text) { + return text.replace("@", "@" + ZERO_WIDTH_SPACE).replace("<", "<" + ZERO_WIDTH_SPACE); + } + + private static String escapeSlack(String text) { + return text.replace("&", "&").replace("<", "<").replace(">", ">"); + } + + private static String cap(String text) { + return text.length() <= MAX_MESSAGE_LENGTH ? text : text.substring(0, MAX_MESSAGE_LENGTH - 3) + "..."; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/WebhookUrl.java b/src/main/java/wellatleastitried/mediagarrdServer/service/WebhookUrl.java new file mode 100644 index 0000000..b2fbdb3 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/WebhookUrl.java @@ -0,0 +1,68 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Locale; + +final class WebhookUrl { + + static final int MAX_LENGTH = 2048; + + private WebhookUrl() {} + + static String validate(String raw) { + String url = raw.strip(); + if (url.length() > MAX_LENGTH) { + throw new IllegalArgumentException("Webhook URL is too long"); + } + if (url.codePoints().anyMatch(c -> Character.isWhitespace(c) || Character.isISOControl(c) || Character.isSpaceChar(c))) { + throw new IllegalArgumentException("Webhook URL must not contain spaces or control characters"); + } + URI uri = parse(url); + String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT); + if (!scheme.equals("http") && !scheme.equals("https")) { + throw new IllegalArgumentException("Webhook URL must use http or https"); + } + if (uri.getRawUserInfo() != null) { + throw new IllegalArgumentException("Webhook URL must not contain user info"); + } + if (uri.getHost() == null || uri.getHost().isEmpty()) { + throw new IllegalArgumentException("Webhook URL must have a valid host name"); + } + if (url.indexOf('#') >= 0) { + throw new IllegalArgumentException("Webhook URL must not contain a fragment"); + } + return url; + } + + static URI parse(String url) { + try { + return new URI(url); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Webhook URL is not a valid URL"); + } + } + + static String host(String url) { + try { + String host = new URI(url).getHost(); + return host == null ? "unknown host" : host; + } catch (URISyntaxException e) { + return "unknown host"; + } + } + + static String target(String url) { + URI uri; + try { + uri = new URI(url); + } catch (URISyntaxException e) { + return null; + } + if (uri.getScheme() == null || uri.getHost() == null || uri.getHost().isEmpty()) { + return null; + } + String port = uri.getPort() < 0 ? "" : ":" + uri.getPort(); + return uri.getScheme().toLowerCase(Locale.ROOT) + "://" + uri.getHost().toLowerCase(Locale.ROOT) + port; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipCompression.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipCompression.java new file mode 100644 index 0000000..f8b7d9f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipCompression.java @@ -0,0 +1,48 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.util.Locale; +import java.util.Set; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; + +@Component +public class ZipCompression { + + static final int MIN_LEVEL = 0; + static final int MAX_LEVEL = 9; + private static final Set ALREADY_COMPRESSED = Set.of( + "zip", "gz", "tgz", "bz2", "xz", "zst", "7z", "rar", + "jpg", "jpeg", "png", "gif", "webp", + "mp4", "mkv", "mp3", "flac", "ogg", + "mov", "avi", "webm", "m4v", "m4a", "aac", "opus", "heic", "avif", + "lz4", "zstd", "jar", "docx", "xlsx", "pptx"); + + private final int level; + + @Autowired + public ZipCompression(MediaGarrdProperties properties) { + this(properties.getCompressionLevel()); + } + + public ZipCompression(int level) { + if (level < MIN_LEVEL || level > MAX_LEVEL) { + throw new IllegalStateException("mediagarrd.compression-level must be between " + MIN_LEVEL + " and " + MAX_LEVEL + ", was " + level); + } + this.level = level; + } + + public int level() { + return level; + } + + boolean stores(String name) { + if (level == 0) { + return true; + } + int dot = name.lastIndexOf('.'); + return dot >= 0 && dot > name.lastIndexOf('/') && ALREADY_COMPRESSED.contains(name.substring(dot + 1).toLowerCase(Locale.ROOT)); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipFormat.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipFormat.java new file mode 100644 index 0000000..30cfc6b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipFormat.java @@ -0,0 +1,232 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; + +final class ZipFormat { + + static final int STORED = 0; + static final int DEFLATED = 8; + static final long ZIP64_LIMIT = 0xFFFFFFFFL; + static final long UINT32_MAX = 0xFFFFFFFFL; + static final long ZIP64_LOCAL_THRESHOLD = 0xF0000000L; + static final int LOCAL_HEADER_SIZE = 30; + static final int CRC_OFFSET = 14; + static final int ZIP64_FIELD_BYTES = 16; + static final int MAX_NAME_BYTES = 0xFFFF; + + private static final int LOCAL_SIGNATURE = 0x04034b50; + private static final int CENTRAL_SIGNATURE = 0x02014b50; + private static final int END_SIGNATURE = 0x06054b50; + private static final int ZIP64_END_SIGNATURE = 0x06064b50; + private static final int ZIP64_LOCATOR_SIGNATURE = 0x07064b50; + private static final int UTF8_FLAG = 0x0800; + private static final int VERSION_DEFAULT = 20; + private static final int VERSION_ZIP64 = 45; + private static final int MADE_BY_UNIX = 0x0314; + private static final int MADE_BY_UNIX_ZIP64 = 0x032D; + private static final int ZIP64_ID = 0x0001; + private static final int TIMESTAMP_ID = 0x5455; + private static final int OWNER_ID = 0x7875; + private static final int DOS_BEFORE_1980 = 1 << 21 | 1 << 16; + private static final int DOS_MAX_YEAR = 2107; + + private ZipFormat() {} + + record Entry(String name, long localOffset, long dataOffset, int method, long crc, long compressedSize, long size, + int mode, long uid, long gid, long modified, boolean localZip64) {} + + static byte[] nameBytes(String name) throws IOException { + byte[] bytes = name.getBytes(StandardCharsets.UTF_8); + if (bytes.length > MAX_NAME_BYTES) { + throw new IOException("Entry name is too long for a zip archive: " + name.substring(0, 64) + "..."); + } + return bytes; + } + + static byte[] localHeader(byte[] name, int method, long modified, long uid, long gid, boolean zip64, long crc, long compressedSize, long size) { + byte[] extra = localExtra(modified, uid, gid, zip64, compressedSize, size); + byte[] header = new byte[LOCAL_HEADER_SIZE + name.length + extra.length]; + put32(header, 0, LOCAL_SIGNATURE); + put16(header, 4, zip64 ? VERSION_ZIP64 : VERSION_DEFAULT); + put16(header, 6, UTF8_FLAG); + put16(header, 8, method); + put32(header, 10, dosTime(modified)); + System.arraycopy(localSizes(zip64, crc, compressedSize, size), 0, header, CRC_OFFSET, 12); + put16(header, 26, name.length); + put16(header, 28, extra.length); + System.arraycopy(name, 0, header, LOCAL_HEADER_SIZE, name.length); + System.arraycopy(extra, 0, header, LOCAL_HEADER_SIZE + name.length, extra.length); + return header; + } + + static byte[] localSizes(boolean zip64, long crc, long compressedSize, long size) { + byte[] sizes = new byte[12]; + put32(sizes, 0, crc); + put32(sizes, 4, zip64 ? ZIP64_LIMIT : compressedSize); + put32(sizes, 8, zip64 ? ZIP64_LIMIT : size); + return sizes; + } + + static byte[] zip64LocalExtra(long compressedSize, long size) { + byte[] extra = new byte[4 + ZIP64_FIELD_BYTES]; + put16(extra, 0, ZIP64_ID); + put16(extra, 2, ZIP64_FIELD_BYTES); + put64(extra, 4, size); + put64(extra, 12, compressedSize); + return extra; + } + + private static byte[] localExtra(long modified, long uid, long gid, boolean zip64, long compressedSize, long size) { + byte[] ownerData = ownerData(uid, gid); + boolean timestamp = fitsUnixTime(modified); + byte[] extra = new byte[(zip64 ? 4 + ZIP64_FIELD_BYTES : 0) + (timestamp ? 9 : 0) + 4 + ownerData.length]; + int pos = 0; + if (zip64) { + byte[] field = zip64LocalExtra(compressedSize, size); + System.arraycopy(field, 0, extra, pos, field.length); + pos += field.length; + } + if (timestamp) { + pos = putTimestamp(extra, pos, modified); + } + put16(extra, pos, OWNER_ID); + put16(extra, pos + 2, ownerData.length); + System.arraycopy(ownerData, 0, extra, pos + 4, ownerData.length); + return extra; + } + + static byte[] ownerData(long uid, long gid) { + byte[] data = new byte[11]; + data[0] = 1; + data[1] = 4; + put32(data, 2, Math.max(0, Math.min(uid, UINT32_MAX))); + data[6] = 4; + put32(data, 7, Math.max(0, Math.min(gid, UINT32_MAX))); + return data; + } + + static byte[] centralHeader(Entry entry, long offset) throws IOException { + byte[] name = nameBytes(entry.name()); + boolean overflowSize = entry.size() >= ZIP64_LIMIT; + boolean overflowCompressed = entry.compressedSize() >= ZIP64_LIMIT; + boolean overflowOffset = offset >= ZIP64_LIMIT; + int zip64Fields = (overflowSize ? 1 : 0) + (overflowCompressed ? 1 : 0) + (overflowOffset ? 1 : 0); + boolean zip64 = zip64Fields > 0; + boolean timestamp = fitsUnixTime(entry.modified()); + int extraLength = (zip64 ? 4 + 8 * zip64Fields : 0) + (timestamp ? 9 : 0) + 4; + byte[] header = new byte[46 + name.length + extraLength]; + boolean needsZip64 = zip64 || entry.localZip64(); + put32(header, 0, CENTRAL_SIGNATURE); + put16(header, 4, needsZip64 ? MADE_BY_UNIX_ZIP64 : MADE_BY_UNIX); + put16(header, 6, needsZip64 ? VERSION_ZIP64 : VERSION_DEFAULT); + put16(header, 8, UTF8_FLAG); + put16(header, 10, entry.method()); + put32(header, 12, dosTime(entry.modified())); + put32(header, 16, entry.crc()); + put32(header, 20, overflowCompressed ? ZIP64_LIMIT : entry.compressedSize()); + put32(header, 24, overflowSize ? ZIP64_LIMIT : entry.size()); + put16(header, 28, name.length); + put16(header, 30, extraLength); + put32(header, 38, externalAttributes(entry.mode(), entry.name().endsWith("/"))); + put32(header, 42, overflowOffset ? ZIP64_LIMIT : offset); + System.arraycopy(name, 0, header, 46, name.length); + int pos = 46 + name.length; + if (zip64) { + put16(header, pos, ZIP64_ID); + put16(header, pos + 2, 8 * zip64Fields); + pos += 4; + if (overflowSize) { + put64(header, pos, entry.size()); + pos += 8; + } + if (overflowCompressed) { + put64(header, pos, entry.compressedSize()); + pos += 8; + } + if (overflowOffset) { + put64(header, pos, offset); + pos += 8; + } + } + if (timestamp) { + pos = putTimestamp(header, pos, entry.modified()); + } + put16(header, pos, OWNER_ID); + put16(header, pos + 2, 0); + return header; + } + + static byte[] endOfArchive(long entries, long centralSize, long centralOffset) { + boolean zip64 = entries >= 0xFFFF || centralSize >= ZIP64_LIMIT || centralOffset >= ZIP64_LIMIT; + byte[] tail = new byte[(zip64 ? 56 + 20 : 0) + 22]; + int pos = 0; + if (zip64) { + put32(tail, 0, ZIP64_END_SIGNATURE); + put64(tail, 4, 44); + put16(tail, 12, MADE_BY_UNIX_ZIP64); + put16(tail, 14, VERSION_ZIP64); + put64(tail, 24, entries); + put64(tail, 32, entries); + put64(tail, 40, centralSize); + put64(tail, 48, centralOffset); + put32(tail, 56, ZIP64_LOCATOR_SIGNATURE); + put64(tail, 64, centralOffset + centralSize); + put32(tail, 72, 1); + pos = 76; + } + put32(tail, pos, END_SIGNATURE); + put16(tail, pos + 8, Math.min(entries, 0xFFFF)); + put16(tail, pos + 10, Math.min(entries, 0xFFFF)); + put32(tail, pos + 12, Math.min(centralSize, ZIP64_LIMIT)); + put32(tail, pos + 16, Math.min(centralOffset, ZIP64_LIMIT)); + return tail; + } + + static long externalAttributes(int mode, boolean directory) { + return ((long) mode << 16) | ((mode & 0200) == 0 ? 1 : 0) | (directory ? 0x10 : 0); + } + + static boolean fitsUnixTime(long millis) { + long seconds = Math.floorDiv(millis, 1000L); + return seconds >= 0 && seconds <= Integer.MAX_VALUE; + } + + static long dosTime(long millis) { + LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()); + if (time.getYear() < 1980) { + return DOS_BEFORE_1980; + } + if (time.getYear() > DOS_MAX_YEAR) { + time = LocalDateTime.of(DOS_MAX_YEAR, 12, 31, 23, 59, 58); + } + return ((long) (time.getYear() - 1980) << 25 | (long) time.getMonthValue() << 21 | (long) time.getDayOfMonth() << 16 + | (long) time.getHour() << 11 | (long) time.getMinute() << 5 | time.getSecond() >> 1) & 0xFFFFFFFFL; + } + + private static int putTimestamp(byte[] target, int pos, long modified) { + put16(target, pos, TIMESTAMP_ID); + put16(target, pos + 2, 5); + target[pos + 4] = 1; + put32(target, pos + 5, Math.floorDiv(modified, 1000L)); + return pos + 9; + } + + static void put16(byte[] target, int pos, long value) { + target[pos] = (byte) value; + target[pos + 1] = (byte) (value >> 8); + } + + static void put32(byte[] target, int pos, long value) { + put16(target, pos, value); + put16(target, pos + 2, value >> 16); + } + + static void put64(byte[] target, int pos, long value) { + put32(target, pos, value); + put32(target, pos + 4, value >> 32); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartIndex.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartIndex.java new file mode 100644 index 0000000..6503070 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartIndex.java @@ -0,0 +1,27 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +final class ZipPartIndex { + + private static final int CACHE_KIB = 2048; + + private ZipPartIndex() {} + + static Connection open(Path file) throws SQLException { + Connection connection = DriverManager.getConnection("jdbc:sqlite:" + file.toAbsolutePath()); + try (Statement statement = connection.createStatement()) { + statement.execute("PRAGMA journal_mode=OFF"); + statement.execute("PRAGMA synchronous=OFF"); + statement.execute("PRAGMA cache_size=-" + CACHE_KIB); + } catch (SQLException e) { + connection.close(); + throw e; + } + return connection; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java new file mode 100644 index 0000000..fac0d9e --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java @@ -0,0 +1,212 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import wellatleastitried.mediagarrdServer.service.ZipFormat.Entry; +import wellatleastitried.mediagarrdServer.utilities.Sha256; + +final class ZipPartMerger { + + private static final Logger LOGGER = LoggerFactory.getLogger(ZipPartMerger.class); + + private static final int BUFFER_SIZE = 64 * 1024; + private static final int COMMIT_INTERVAL = 10_000; + private static final List DATABASE_SIDECAR_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); + + record Result(String checksum, long entries, long bytes) {} + + private ZipPartMerger() {} + + static Result merge(List snapshotParts, List parts, Path output, Path scratchDirectory) throws IOException { + Path names = scratchDirectory.resolve("merge-names" + ZipPartWriter.INDEX_SUFFIX); + MessageDigest digest = Sha256.newDigest(); + try (OutputStream file = Files.newOutputStream(output); Sink sink = new Sink(file, digest); NameIndex seen = new NameIndex(names)) { + List ordered = new ArrayList<>(snapshotParts); + ordered.addAll(parts); + long[] bases = new long[ordered.size()]; + for (int i = 0; i < ordered.size(); i++) { + bases[i] = sink.written(); + copyData(ordered.get(i), sink); + } + + Set reserved = new HashSet<>(); + long centralStart = sink.written(); + long entries = 0; + for (int i = 0; i < ordered.size(); i++) { + boolean snapshot = i < snapshotParts.size(); + entries += writeCentral(ordered.get(i), bases[i], snapshot, reserved, seen, sink); + } + long centralSize = sink.written() - centralStart; + sink.write(ZipFormat.endOfArchive(entries, centralSize, centralStart)); + sink.flush(); + LOGGER.debug("Merged {} part(s) into {} entries", ordered.size(), entries); + return new Result(Sha256.hex(digest.digest()), entries, sink.written()); + } finally { + Files.deleteIfExists(names); + } + } + + private static void copyData(Path part, Sink sink) throws IOException { + byte[] chunk = new byte[BUFFER_SIZE]; + try (InputStream in = Files.newInputStream(part)) { + int read; + while ((read = in.read(chunk)) != -1) { + sink.write(chunk, 0, read); + } + } + } + + private static long writeCentral(Path part, long base, boolean snapshot, Set reserved, NameIndex seen, Sink sink) throws IOException { + Path index = ZipPartWriter.indexOf(part); + if (!Files.isRegularFile(index)) { + throw new IOException("Archive part " + part + " has no index"); + } + long count = 0; + try (Connection connection = ZipPartIndex.open(index); + Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery("SELECT name,lfh_offset,method,crc,csize,usize,mode,uid,gid,mtime,zip64 FROM entries ORDER BY id")) { + while (rows.next()) { + String name = rows.getString(1); + if (snapshot) { + if (!name.endsWith("/")) { + DATABASE_SIDECAR_SUFFIXES.forEach(suffix -> reserved.add(name + suffix)); + } + } else if (reserved.contains(name)) { + throw new IOException("Archive part " + part + " contains " + name + ", which the database snapshot owns"); + } + seen.add(name, part); + Entry entry = new Entry(name, rows.getLong(2), 0, rows.getInt(3), rows.getLong(4), rows.getLong(5), rows.getLong(6), + rows.getInt(7), rows.getLong(8), rows.getLong(9), rows.getLong(10), rows.getInt(11) != 0); + sink.write(ZipFormat.centralHeader(entry, base + entry.localOffset())); + count++; + } + } catch (SQLException e) { + throw new IOException("Unable to read the index of archive part " + part, e); + } + return count; + } + + private static final class NameIndex implements AutoCloseable { + + private final Connection connection; + private final PreparedStatement insert; + private int pending; + + NameIndex(Path file) throws IOException { + Connection opened = null; + try { + Files.deleteIfExists(file); + opened = ZipPartIndex.open(file); + try (Statement statement = opened.createStatement()) { + statement.execute("CREATE TABLE names(name TEXT PRIMARY KEY) WITHOUT ROWID"); + } + opened.setAutoCommit(false); + insert = opened.prepareStatement("INSERT INTO names(name) VALUES(?)"); + connection = opened; + } catch (SQLException | IOException e) { + if (opened != null) { + try { + opened.close(); + } catch (SQLException ignored) { + LOGGER.debug("Unable to close the name index", ignored); + } + } + throw e instanceof IOException io ? io : new IOException("Unable to create the merge name index", e); + } + } + + void add(String name, Path part) throws IOException { + try { + insert.setString(1, name); + insert.executeUpdate(); + if (++pending >= COMMIT_INTERVAL) { + connection.commit(); + pending = 0; + } + } catch (SQLException e) { + throw new IOException("Duplicate or unrecordable entry " + name + " in archive part " + part, e); + } + } + + @Override + public void close() throws IOException { + try { + insert.close(); + connection.close(); + } catch (SQLException e) { + throw new IOException("Unable to close the merge name index", e); + } + } + } + + private static final class Sink extends OutputStream { + + private final OutputStream out; + private final MessageDigest digest; + private final byte[] buffer = new byte[BUFFER_SIZE]; + private int buffered; + private long written; + + Sink(OutputStream out, MessageDigest digest) { + this.out = out; + this.digest = digest; + } + + long written() { + return written; + } + + @Override + public void write(int b) throws IOException { + write(new byte[] {(byte) b}, 0, 1); + } + + @Override + public void write(byte[] data, int offset, int length) throws IOException { + if (length >= buffer.length) { + flush(); + digest.update(data, offset, length); + out.write(data, offset, length); + } else { + if (length > buffer.length - buffered) { + flush(); + } + System.arraycopy(data, offset, buffer, buffered, length); + buffered += length; + } + written += length; + } + + @Override + public void flush() throws IOException { + if (buffered > 0) { + digest.update(buffer, 0, buffered); + out.write(buffer, 0, buffered); + buffered = 0; + } + } + + @Override + public void close() throws IOException { + flush(); + out.flush(); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartWriter.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartWriter.java new file mode 100644 index 0000000..317aa19 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartWriter.java @@ -0,0 +1,364 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.Closeable; +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.zip.CRC32; +import java.util.zip.Deflater; + +import wellatleastitried.mediagarrdServer.service.ZipFormat.Entry; + +final class ZipPartWriter implements Closeable { + + static final String PART_SUFFIX = ".part"; + static final String INDEX_SUFFIX = ".idx"; + static final String PARTIAL_SUFFIX = ".partial"; + + private static final int BUFFER_SIZE = 64 * 1024; + private static final int COMMIT_INTERVAL = 10_000; + private static final String COLUMNS = "name,lfh_offset,data_offset,method,crc,csize,usize,mode,uid,gid,mtime,zip64"; + + private final Path part; + private final Path partial; + private final Path index; + private final ZipCompression compression; + private final FileChannel channel; + private final Connection connection; + private final PreparedStatement insert; + private final PreparedStatement exists; + private final PreparedStatement lookup; + private final PreparedStatement skip; + private final PreparedStatement skipped; + private final Deflater deflater; + private final byte[] buffer = new byte[BUFFER_SIZE]; + private final byte[] chunk = new byte[BUFFER_SIZE]; + private final byte[] compressed = new byte[BUFFER_SIZE]; + private int buffered; + private long position; + private int entries; + private int pendingRows; + private boolean completed; + private boolean closed; + + ZipPartWriter(Path part, ZipCompression compression) throws IOException { + this.part = part; + this.partial = partialOf(part); + this.index = indexOf(part); + this.compression = compression; + this.deflater = new Deflater(Math.max(compression.level(), 1), true); + FileChannel opened = null; + Connection connected = null; + try { + Files.deleteIfExists(index); + opened = FileChannel.open(partial, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.READ, StandardOpenOption.WRITE); + connected = ZipPartIndex.open(index); + try (Statement statement = connected.createStatement()) { + statement.execute("CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, lfh_offset INTEGER NOT NULL, data_offset INTEGER NOT NULL, " + + "method INTEGER NOT NULL, crc INTEGER NOT NULL, csize INTEGER NOT NULL, usize INTEGER NOT NULL, mode INTEGER NOT NULL, " + + "uid INTEGER NOT NULL, gid INTEGER NOT NULL, mtime INTEGER NOT NULL, zip64 INTEGER NOT NULL)"); + statement.execute("CREATE TABLE skipped(name TEXT PRIMARY KEY) WITHOUT ROWID"); + } + connected.setAutoCommit(false); + this.insert = connected.prepareStatement("INSERT INTO entries(" + COLUMNS + ") VALUES(?,?,?,?,?,?,?,?,?,?,?,?)"); + this.exists = connected.prepareStatement("SELECT 1 FROM entries WHERE name=?"); + this.lookup = connected.prepareStatement("SELECT " + COLUMNS + " FROM entries WHERE name=?"); + this.skip = connected.prepareStatement("INSERT OR IGNORE INTO skipped(name) VALUES(?)"); + this.skipped = connected.prepareStatement("SELECT 1 FROM skipped WHERE name=?"); + this.channel = opened; + this.connection = connected; + } catch (SQLException | IOException | RuntimeException e) { + deflater.end(); + closeQuietly(connected); + closeQuietly(opened); + deleteQuietly(partial); + deleteQuietly(index); + throw e instanceof IOException io ? io : new IOException("Unable to create archive part " + part, e); + } + } + + static Path partialOf(Path part) { + return part.resolveSibling(part.getFileName() + PARTIAL_SUFFIX); + } + + static Path indexOf(Path part) { + return part.resolveSibling(part.getFileName() + INDEX_SUFFIX); + } + + static void discard(Path part) throws IOException { + Files.deleteIfExists(part); + Files.deleteIfExists(partialOf(part)); + Files.deleteIfExists(indexOf(part)); + } + + int entryCount() { + return entries; + } + + boolean contains(String name) throws IOException { + try { + exists.setString(1, name); + try (ResultSet rows = exists.executeQuery()) { + return rows.next(); + } + } catch (SQLException e) { + throw new IOException("Unable to query the archive part index", e); + } + } + + void markSkipped(String name) throws IOException { + try { + skip.setString(1, name); + skip.executeUpdate(); + } catch (SQLException e) { + throw new IOException("Unable to update the archive part index", e); + } + } + + boolean wasSkipped(String name) throws IOException { + try { + skipped.setString(1, name); + try (ResultSet rows = skipped.executeQuery()) { + return rows.next(); + } + } catch (SQLException e) { + throw new IOException("Unable to query the archive part index", e); + } + } + + void addEntry(String name, int mode, long uid, long gid, long modified, long size, InputStream content) throws IOException { + int method = compression.stores(name) ? ZipFormat.STORED : ZipFormat.DEFLATED; + boolean zip64 = size >= ZipFormat.ZIP64_LOCAL_THRESHOLD; + byte[] nameBytes = ZipFormat.nameBytes(name); + long localOffset = position; + byte[] header = ZipFormat.localHeader(nameBytes, method, modified, uid, gid, zip64, 0, 0, 0); + write(header, 0, header.length); + long dataOffset = localOffset + header.length; + + CRC32 crc = new CRC32(); + long total = 0; + long compressedSize = 0; + if (method == ZipFormat.STORED) { + int read; + while ((read = content.read(chunk)) != -1) { + crc.update(chunk, 0, read); + write(chunk, 0, read); + total += read; + } + compressedSize = total; + } else { + deflater.reset(); + int read; + while ((read = content.read(chunk)) != -1) { + crc.update(chunk, 0, read); + total += read; + deflater.setInput(chunk, 0, read); + compressedSize += drain(false); + } + deflater.finish(); + compressedSize += drain(true); + } + if (total != size) { + throw new EOFException("Entry " + name + " has " + total + " bytes but its header says " + size); + } + if (!zip64 && (compressedSize >= ZipFormat.ZIP64_LIMIT || total >= ZipFormat.ZIP64_LIMIT)) { + throw new IOException("Entry " + name + " outgrew its header, size " + total + ", compressed " + compressedSize); + } + patchSizes(localOffset, nameBytes.length, zip64, crc.getValue(), compressedSize, total); + record(new Entry(name, localOffset, dataOffset, method, crc.getValue(), compressedSize, total, mode, uid, gid, modified, zip64)); + } + + boolean addCopy(String name, String targetName) throws IOException { + Entry target = find(targetName); + if (target == null) { + if (wasSkipped(targetName)) { + return false; + } + throw new IOException("Hard link " + name + " points to a missing entry " + targetName); + } + byte[] nameBytes = ZipFormat.nameBytes(name); + long localOffset = position; + byte[] header = ZipFormat.localHeader(nameBytes, target.method(), target.modified(), target.uid(), target.gid(), target.localZip64(), + target.crc(), target.compressedSize(), target.size()); + flush(); + write(header, 0, header.length); + long remaining = target.compressedSize(); + long from = target.dataOffset(); + while (remaining > 0) { + int length = (int) Math.min(chunk.length, remaining); + ByteBuffer slice = ByteBuffer.wrap(chunk, 0, length); + while (slice.hasRemaining()) { + int read = channel.read(slice, from + slice.position()); + if (read < 0) { + throw new EOFException("Archive part ended while copying " + targetName); + } + } + write(chunk, 0, length); + from += length; + remaining -= length; + } + record(new Entry(name, localOffset, localOffset + header.length, target.method(), target.crc(), target.compressedSize(), target.size(), + target.mode(), target.uid(), target.gid(), target.modified(), target.localZip64())); + return true; + } + + void complete() throws IOException { + flush(); + try { + connection.commit(); + } catch (SQLException e) { + throw new IOException("Unable to save the archive part index", e); + } + release(); + Files.move(partial, part, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + completed = true; + } + + @Override + public void close() { + release(); + if (!completed) { + deleteQuietly(partial); + deleteQuietly(index); + } + } + + private Entry find(String name) throws IOException { + try { + lookup.setString(1, name); + try (ResultSet rows = lookup.executeQuery()) { + if (!rows.next()) { + return null; + } + return new Entry(rows.getString(1), rows.getLong(2), rows.getLong(3), rows.getInt(4), rows.getLong(5), rows.getLong(6), rows.getLong(7), + rows.getInt(8), rows.getLong(9), rows.getLong(10), rows.getLong(11), rows.getInt(12) != 0); + } + } catch (SQLException e) { + throw new IOException("Unable to query the archive part index", e); + } + } + + private void record(Entry entry) throws IOException { + try { + insert.setString(1, entry.name()); + insert.setLong(2, entry.localOffset()); + insert.setLong(3, entry.dataOffset()); + insert.setInt(4, entry.method()); + insert.setLong(5, entry.crc()); + insert.setLong(6, entry.compressedSize()); + insert.setLong(7, entry.size()); + insert.setInt(8, entry.mode()); + insert.setLong(9, entry.uid()); + insert.setLong(10, entry.gid()); + insert.setLong(11, entry.modified()); + insert.setInt(12, entry.localZip64() ? 1 : 0); + insert.executeUpdate(); + entries++; + if (++pendingRows >= COMMIT_INTERVAL) { + connection.commit(); + pendingRows = 0; + } + } catch (SQLException e) { + throw new IOException("Unable to record " + entry.name() + " in the archive part index", e); + } + } + + private long drain(boolean finish) throws IOException { + long produced = 0; + while (finish ? !deflater.finished() : !deflater.needsInput()) { + int length = deflater.deflate(compressed); + if (length > 0) { + write(compressed, 0, length); + produced += length; + } + } + return produced; + } + + private void patchSizes(long localOffset, int nameLength, boolean zip64, long crc, long compressedSize, long size) throws IOException { + flush(); + writeAt(localOffset + ZipFormat.CRC_OFFSET, ZipFormat.localSizes(zip64, crc, compressedSize, size)); + if (zip64) { + writeAt(localOffset + ZipFormat.LOCAL_HEADER_SIZE + nameLength, ZipFormat.zip64LocalExtra(compressedSize, size)); + } + } + + private void writeAt(long at, byte[] data) throws IOException { + ByteBuffer source = ByteBuffer.wrap(data); + long written = at; + while (source.hasRemaining()) { + written += channel.write(source, written); + } + } + + private void write(byte[] data, int offset, int length) throws IOException { + if (length >= buffer.length) { + flush(); + ByteBuffer source = ByteBuffer.wrap(data, offset, length); + while (source.hasRemaining()) { + channel.write(source); + } + } else { + if (length > buffer.length - buffered) { + flush(); + } + System.arraycopy(data, offset, buffer, buffered, length); + buffered += length; + } + position += length; + } + + private void flush() throws IOException { + if (buffered > 0) { + ByteBuffer source = ByteBuffer.wrap(buffer, 0, buffered); + while (source.hasRemaining()) { + channel.write(source); + } + buffered = 0; + } + } + + private void release() { + if (closed) { + return; + } + closed = true; + deflater.end(); + closeQuietly(skipped); + closeQuietly(skip); + closeQuietly(lookup); + closeQuietly(exists); + closeQuietly(insert); + closeQuietly(connection); + closeQuietly(channel); + } + + private static void closeQuietly(AutoCloseable closeable) { + if (closeable != null) { + try { + closeable.close(); + } catch (Exception e) { + return; + } + } + } + + private static void deleteQuietly(Path file) { + try { + Files.deleteIfExists(file); + } catch (IOException e) { + return; + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/FilePermissions.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/FilePermissions.java new file mode 100644 index 0000000..09420a3 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/FilePermissions.java @@ -0,0 +1,57 @@ +package wellatleastitried.mediagarrdServer.utilities; + +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public final class FilePermissions { + + private static final Logger LOGGER = LoggerFactory.getLogger(FilePermissions.class); + + private static final Set OWNER_ONLY_DIRECTORY = PosixFilePermissions.fromString("rwx------"); + private static final Set OWNER_ONLY_FILE = PosixFilePermissions.fromString("rw-------"); + private static final boolean POSIX = FileSystems.getDefault().supportedFileAttributeViews().contains("posix"); + + private FilePermissions() {} + + public static Path createPrivateDirectories(Path directory) throws IOException { + if (!POSIX) { + return Files.createDirectories(directory); + } + return Files.createDirectories(directory, directoryAttribute()); + } + + public static Path createPrivateFile(Path file) throws IOException { + if (!POSIX) { + return Files.createFile(file); + } + return Files.createFile(file, fileAttribute()); + } + + public static void restrictFile(Path file) { + if (!POSIX) { + return; + } + try { + Files.setPosixFilePermissions(file, OWNER_ONLY_FILE); + } catch (IOException | RuntimeException e) { + LOGGER.warn("Unable to restrict permissions of {}", LogSanitizer.clean(file), e); + } + } + + private static FileAttribute> directoryAttribute() { + return PosixFilePermissions.asFileAttribute(OWNER_ONLY_DIRECTORY); + } + + private static FileAttribute> fileAttribute() { + return PosixFilePermissions.asFileAttribute(OWNER_ONLY_FILE); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/LogSanitizer.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/LogSanitizer.java new file mode 100644 index 0000000..fa47a33 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/LogSanitizer.java @@ -0,0 +1,24 @@ +package wellatleastitried.mediagarrdServer.utilities; + +public final class LogSanitizer { + + private static final int MAX_LENGTH = 256; + + private LogSanitizer() {} + + public static String clean(Object value) { + if (value == null) { + return "null"; + } + String text = value.toString(); + StringBuilder cleaned = new StringBuilder(Math.min(text.length(), MAX_LENGTH + 3)); + for (int i = 0; i < text.length() && cleaned.length() < MAX_LENGTH; i++) { + char c = text.charAt(i); + cleaned.append(Character.isISOControl(c) || c == '
' || c == '
' ? '_' : c); + } + if (cleaned.length() < text.length()) { + cleaned.append("..."); + } + return cleaned.toString(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java new file mode 100644 index 0000000..9d7b135 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java @@ -0,0 +1,37 @@ +package wellatleastitried.mediagarrdServer.utilities; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.Date; + +public class MediaGarrdUtils { + + private MediaGarrdUtils() {} + + public static String recordCurrentTime() { + Instant instant = Instant.now(); + return formatTime(instant); + } + + public static String formatTime(Instant instant) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String formattedTime = sdf.format(Date.from(instant)); + return formattedTime; + } + + public static Instant parseTime(String time) throws ParseException { + return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time).toInstant(); + } + + public static long getDurationMs(String startTimeStr, String endTimeStr) { + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date startDate = sdf.parse(startTimeStr); + Date endDate = sdf.parse(endTimeStr); + return endDate.getTime() - startDate.getTime(); + } catch (ParseException e) {} + return -1; + } +} + diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/SemVer.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/SemVer.java new file mode 100644 index 0000000..1a10f86 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/SemVer.java @@ -0,0 +1,78 @@ +package wellatleastitried.mediagarrdServer.utilities; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public record SemVer(long major, long minor, long patch, List prerelease) implements Comparable { + + private static final String IDENTIFIERS = "[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*"; + private static final Pattern PATTERN = Pattern.compile( + "v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-(" + IDENTIFIERS + "))?(?:\\+" + IDENTIFIERS + ")?"); + + public static Optional parse(String text) { + if (text == null) { + return Optional.empty(); + } + Matcher matcher = PATTERN.matcher(text.strip()); + if (!matcher.matches()) { + return Optional.empty(); + } + try { + List prerelease = matcher.group(4) == null ? List.of() : Arrays.asList(matcher.group(4).split("\\.")); + return Optional.of(new SemVer( + Long.parseLong(matcher.group(1)), + Long.parseLong(matcher.group(2)), + Long.parseLong(matcher.group(3)), + prerelease)); + } catch (NumberFormatException e) { + return Optional.empty(); + } + } + + @Override + public int compareTo(SemVer other) { + int result = Long.compare(major, other.major); + if (result == 0) { + result = Long.compare(minor, other.minor); + } + if (result == 0) { + result = Long.compare(patch, other.patch); + } + return result != 0 ? result : comparePrerelease(prerelease, other.prerelease); + } + + @Override + public String toString() { + String core = major + "." + minor + "." + patch; + return prerelease.isEmpty() ? core : core + "-" + String.join(".", prerelease); + } + + private static int comparePrerelease(List left, List right) { + if (left.isEmpty() || right.isEmpty()) { + return Boolean.compare(left.isEmpty(), right.isEmpty()); + } + for (int i = 0; i < Math.min(left.size(), right.size()); i++) { + int result = compareIdentifier(left.get(i), right.get(i)); + if (result != 0) { + return result; + } + } + return Integer.compare(left.size(), right.size()); + } + + private static int compareIdentifier(String left, String right) { + boolean leftNumeric = left.chars().allMatch(Character::isDigit); + boolean rightNumeric = right.chars().allMatch(Character::isDigit); + if (leftNumeric && rightNumeric) { + return new BigInteger(left).compareTo(new BigInteger(right)); + } + if (leftNumeric != rightNumeric) { + return leftNumeric ? -1 : 1; + } + return left.compareTo(right); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/Sha256.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/Sha256.java new file mode 100644 index 0000000..e98b791 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/Sha256.java @@ -0,0 +1,27 @@ +package wellatleastitried.mediagarrdServer.utilities; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +public final class Sha256 { + + private Sha256() {} + + public static MessageDigest newDigest() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is not available", e); + } + } + + public static String hex(String value) { + return hex(newDigest().digest(value.getBytes(StandardCharsets.UTF_8))); + } + + public static String hex(byte[] digest) { + return HexFormat.of().formatHex(digest); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java new file mode 100644 index 0000000..bbabaf1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java @@ -0,0 +1,180 @@ +package wellatleastitried.mediagarrdServer.utilities.database; + +import java.util.ArrayList; +import java.util.List; + +public class DatabaseQueries { + + public static final String CREATE_TABLES = """ + CREATE TABLE IF NOT EXISTS backups ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + archive_id TEXT NOT NULL UNIQUE, + start_time DATETIME NOT NULL, + end_time DATETIME, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), + checksum TEXT, + file_path TEXT, + file_size INTEGER NOT NULL, + file_created_time DATETIME, + error_message TEXT + ); + + CREATE TABLE IF NOT EXISTS backup_services ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + backup_id INTEGER NOT NULL, + service_name TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'partial')), + start_time DATETIME, + end_time DATETIME, + error_message TEXT, + FOREIGN KEY (backup_id) REFERENCES backups(id) ON DELETE CASCADE, + UNIQUE (backup_id, service_name) + ); + + CREATE TABLE IF NOT EXISTS services ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL UNIQUE COLLATE NOCASE, + paths TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS paired_clients ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + token_hash TEXT NOT NULL UNIQUE, + created_at TEXT NOT NULL, + last_used_at TEXT + ); + + CREATE INDEX IF NOT EXISTS idx_backups_start_time ON backups(start_time); + CREATE INDEX IF NOT EXISTS idx_backup_services_service_name ON backup_services(service_name); + """; + + public static final String ADD_BACKUP_RECORD = """ + INSERT INTO backups ( + archive_id, + start_time, + end_time, + status, + checksum, + file_path, + file_size, + file_created_time, + error_message + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?); + """; + + public static final String ADD_BACKUP_SERVICE_RECORD = """ + INSERT INTO backup_services ( + backup_id, + service_name, + status, + start_time, + end_time, + error_message + ) VALUES (?, ?, ?, ?, ?, ?); + """; + + public static final String FETCH_LATEST_RECORD = """ + SELECT id, archive_id, start_time, end_time, status, file_path, error_message FROM backups + ORDER BY start_time DESC + LIMIT 1; + """; + + public static final String FETCH_LAST_SUCCESSFUL_START = """ + SELECT start_time FROM backups + WHERE status IN ('completed', 'partial') + ORDER BY start_time DESC + LIMIT 1; + """; + + public static final String FETCH_RECORD_BY_ID = """ + SELECT id, archive_id, start_time, end_time, status, file_path, error_message FROM backups + WHERE archive_id = ?; + """; + + public static final String FETCH_SERVICES_FROM_RECORD = """ + SELECT service_name, status, start_time, end_time, error_message FROM backup_services + WHERE backup_id = ?; + """; + + public static final String DELETE_BACKUP_RECORD_BY_ID = """ + DELETE FROM backups + WHERE archive_id = ?; + """; + + public static final String FETCH_ALL_SERVICES = """ + SELECT name, paths FROM services + ORDER BY name COLLATE NOCASE; + """; + + public static final String FETCH_SERVICE_BY_NAME = """ + SELECT name, paths FROM services + WHERE name = ?; + """; + + public static final String ADD_SERVICE = """ + INSERT INTO services (name, paths) VALUES (?, ?); + """; + + public static final String UPDATE_SERVICE = """ + UPDATE services SET name = ?, paths = ? + WHERE name = ?; + """; + + public static final String DELETE_SERVICE = """ + DELETE FROM services + WHERE name = ?; + """; + + public static final String FETCH_SETTING = """ + SELECT value FROM settings + WHERE key = ?; + """; + + public static final String UPSERT_SETTING = """ + INSERT INTO settings (key, value) VALUES (?, ?) + ON CONFLICT(key) DO UPDATE SET value = excluded.value; + """; + + public static final String ADD_PAIRED_CLIENT = """ + INSERT INTO paired_clients (id, name, token_hash, created_at) VALUES (?, ?, ?, ?); + """; + + public static final String FETCH_PAIRED_CLIENTS = """ + SELECT id, name, created_at, last_used_at FROM paired_clients + ORDER BY created_at, id; + """; + + public static final String FETCH_PAIRED_CLIENT_BY_HASH = """ + SELECT id, name, created_at, last_used_at FROM paired_clients + WHERE token_hash = ?; + """; + + public static final String DELETE_PAIRED_CLIENT = """ + DELETE FROM paired_clients + WHERE id = ?; + """; + + public static final String TOUCH_PAIRED_CLIENT = """ + UPDATE paired_clients SET last_used_at = ? + WHERE id = ?; + """; + + public static final String COUNT_PAIRED_CLIENTS = """ + SELECT COUNT(*) FROM paired_clients; + """; + + public record Migration(int version, String sql) {} + + public static final List MIGRATIONS; + static { + MIGRATIONS = new ArrayList(); + // Migration versions will start at 2, as the initial tables will be schema v1 + MIGRATIONS.add(new Migration(2, "DELETE FROM backup_services WHERE backup_id NOT IN (SELECT id FROM backups)")); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java new file mode 100644 index 0000000..c6a2f0f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java @@ -0,0 +1,19 @@ +package wellatleastitried.mediagarrdServer.utilities.database; + +public class DatabaseUtils { + + public static final String SQLITE = "jdbc:sqlite:"; + public static final String BACKUP_ROOT_SETTING = "backup_root"; + public static final String SETUP_COMPLETED_SETTING = "setup_completed"; + public static final String BACKUP_INTERVAL_SETTING = "backup_interval"; + public static final String RETENTION_COUNT_SETTING = "retention_count"; + public static final String FAILURE_WEBHOOK_SETTING = "failure_webhook_url"; + + // Status used for the overall backup AND the individual service runners + public class Status { + public static final String COMPLETED = "completed"; + public static final String PARTIAL = "partial"; + public static final String FAILED = "failed"; + } + +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 7d47d49..0dee2d0 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,27 +1,20 @@ server: port: ${SERVER_PORT:8080} +spring: + task: + scheduling: + pool: + size: 2 + mediagarrd: backup-interval: ${MEDIAGARRD_BACKUP_INTERVAL:PT12H} - backup-root: ${MEDIAGARRD_BACKUP_ROOT:./data/server/backups} + backup-root: ${MEDIAGARRD_BACKUP_ROOT:/var/lib/mediagarrd/backups} retention-count: ${MEDIAGARRD_RETENTION_COUNT:10} - services: - jellyfin: - enabled: ${JELLYFIN_ENABLED:true} - config-path: /srv/sources/jellyfin/config - radarr: - enabled: ${RADARR_ENABLED:true} - path: /srv/sources/radarr - sonarr: - enabled: ${SONARR_ENABLED:true} - path: /srv/sources/sonarr - prowlarr: - enabled: ${PROWLARR_ENABLED:true} - path: /srv/sources/prowlarr - tdarr: - enabled: ${TDARR_ENABLED:true} - path: /srv/sources/tdarr - qbittorrent: - enabled: ${QBITTORRENT_ENABLED:true} - path: /srv/sources/qbittorrent - saved-torrents-path: ${QBITTORRENT_SAVED_TORRENTS_PATH} + database-path: ${MEDIAGARRD_DATABASE_PATH:/var/lib/mediagarrd/db/mediagarrd.db} + compression-level: ${MEDIAGARRD_COMPRESSION_LEVEL:1} + helper-image: ${MEDIAGARRD_HELPER_IMAGE:busybox:stable} + update-repository: ${MEDIAGARRD_UPDATE_REPOSITORY:MediaGarrd/Server} + github-api-base-url: ${MEDIAGARRD_GITHUB_API_URL:https://api.github.com} + update-check-interval: ${MEDIAGARRD_UPDATE_CHECK_INTERVAL:PT24H} + open-pairing: ${MEDIAGARRD_OPEN_PAIRING:false} diff --git a/src/main/resources/static/config.html b/src/main/resources/static/config.html new file mode 100644 index 0000000..1f021d6 --- /dev/null +++ b/src/main/resources/static/config.html @@ -0,0 +1,152 @@ + + + + + + MediaGarrd Server Configuration + + + + +
+
+ MediaGarrd + Server Configuration +
+
+ + + + +
Setup PIN
+
+
+ + + +
+ +
+
+ +
+ + + + +
+
+
Backup Settings
+
+
+ + +

Must be on a mounted volume, otherwise archives are lost when the container is recreated.

+
+
+ + +
+
+ + +
+
+
+
+ +
+
Failure Notifications
+
+
+ + +

Sends a message when a backup fails or only partly succeeds. Works with Discord, Slack and any receiver that accepts JSON. The saved address is never shown again.

+

Not configured

+
+
+ + + +
+
+
+
+ +
+
+
Add Service
+
+
+ + +
+
+
+ Host paths to back up +
+ +
+
+
+ + +
+
+ + + + + +
Configured Services
+
+ + + + +
Configured services
NamePathsActions
+
+

No services configured yet.

+
+
+
Finish Setup
+
+

Once finished, this page is disabled. Later changes go through the API or the MediaGarrd Client.

+
+
+
+
+
+ + diff --git a/src/main/resources/static/css/mediagarrd.css b/src/main/resources/static/css/mediagarrd.css new file mode 100644 index 0000000..fa64743 --- /dev/null +++ b/src/main/resources/static/css/mediagarrd.css @@ -0,0 +1,173 @@ +:root { + --bg: #000; + --surface: #0a0a0a; + --surface-raised: #111; + --ink: #f5f5f5; + --muted: #737373; + --subtle: #404040; + --border: #1f1f1f; + --border-mid: #2e2e2e; + --accent: #f5f5f5; + --accent-dim: #d4d4d4; + --ok: #22c55e; + --warn: #ef4444; + --mono: "JetBrains Mono", "Fira Code", ui-monospace, monospace; +} + +*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } + +body { + font-family: "Space Grotesk", "Inter", "Avenir Next", ui-sans-serif, system-ui, sans-serif; + background: var(--bg); + color: var(--ink); + min-height: 100vh; + font-size: 14px; + line-height: 1.5; +} + +[hidden] { display: none !important; } + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0.85rem 1.5rem; + border-bottom: 1px solid var(--border); + background: var(--surface); + position: sticky; + top: 0; + z-index: 10; +} + +.brand { display: flex; flex-direction: column; } +.brand-title { font-size: 1rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; } +.brand-sub { font-size: 0.72rem; color: var(--muted); letter-spacing: 0.05em; } + +.workspace { + max-width: 1200px; + margin: 0 auto; + padding: 1.5rem; + display: grid; + grid-template-columns: 360px minmax(0, 1fr); + gap: 1rem; + align-items: start; +} + +.workspace > * { min-width: 0; } + +@media (max-width: 900px) { .workspace { grid-template-columns: minmax(0, 1fr); } } + +.panel { background: var(--surface); border: 1px solid var(--border); } +.panel.wide { grid-column: 1 / -1; } +.stack { display: flex; flex-direction: column; gap: 1rem; } + +dialog.panel { color: var(--ink); margin: auto; width: min(360px, calc(100% - 2rem)); } +dialog::backdrop { background: rgba(0, 0, 0, 0.8); } +.error-text, .note.error-text { color: #fca5a5; } +.panel-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0.7rem 1rem; + border-bottom: 1px solid var(--border); +} +.panel-title { font-size: 0.72rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: var(--accent-dim); } +.panel-body { padding: 1rem; } + +.field-group { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 0.75rem; } +.field-label { font-size: 0.7rem; color: var(--muted); letter-spacing: 0.04em; } +.note { font-size: 0.72rem; color: var(--muted); margin-top: 0.45rem; overflow-wrap: anywhere; } +.input-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0.5rem; } +.button-row { display: flex; flex-wrap: wrap; gap: 0.5rem; } +.note + .button-row { margin-top: 0.75rem; } +.pin-row { display: flex; flex-wrap: wrap; align-items: center; gap: 0.75rem; margin-top: 0.75rem; } +.pin-value { font-size: 1.6rem; font-weight: 700; letter-spacing: 0.2em; color: var(--ink); } + +input { + width: 100%; + min-width: 0; + background: var(--bg); + color: var(--ink); + border: 1px solid var(--border-mid); + padding: 0.5rem 0.65rem; + font: inherit; + font-size: 0.85rem; + transition: border-color 150ms; +} +input:focus { border-color: var(--muted); } +input:focus-visible, button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +input::placeholder { color: var(--muted); } + +button { + background: var(--accent); + color: #000; + border: 1px solid var(--accent); + padding: 0.5rem 0.85rem; + font: inherit; + font-size: 0.78rem; + font-weight: 700; + letter-spacing: 0.05em; + text-transform: uppercase; + cursor: pointer; + white-space: nowrap; + transition: background 120ms, color 120ms, border-color 120ms, transform 70ms; +} +button:hover { background: var(--accent-dim); border-color: var(--accent-dim); } +button:active { transform: translateY(1px) scale(0.98); } +button:disabled { cursor: not-allowed; opacity: 0.62; transform: none; } +button.ghost { background: transparent; color: var(--ink); border-color: var(--border-mid); } +button.ghost:hover { border-color: var(--subtle); background: var(--surface-raised); } +button.danger { background: transparent; color: #fca5a5; border-color: #3b1111; } +button.danger:hover { background: #1c0606; } + +table { width: 100%; border-collapse: collapse; font-size: 0.82rem; } +thead th { + padding: 0.5rem 0.75rem; + text-align: left; + font-size: 0.68rem; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); + border-bottom: 1px solid var(--border-mid); +} +tbody tr { border-bottom: 1px solid var(--border); transition: background 100ms; } +tbody tr:last-child { border-bottom: none; } +tbody tr:hover { background: var(--surface-raised); } +tbody td { padding: 0.55rem 0.75rem; vertical-align: top; } +.td-mono { font-family: var(--mono); font-size: 0.78rem; color: var(--accent-dim); white-space: pre-line; word-break: break-all; } +.actions-cell { text-align: right; white-space: nowrap; } +.actions-cell button + button { margin-left: 0.4rem; } +.empty-state { padding: 2.5rem 1rem; text-align: center; color: var(--muted); font-size: 0.83rem; } + +.banner { + display: none; + grid-column: 1 / -1; + padding: 0.65rem 1rem; + font-size: 0.82rem; + background: #1c0606; + border: 1px solid #3b1111; + color: #fca5a5; +} +.banner.visible { display: block; } +.banner.ok { background: #06140b; border-color: #1e3b2a; color: #a3e8bc; } + +.table-wrap { overflow-x: auto; } +.field-set { border: 0; min-width: 0; } +.fatal { max-width: 480px; margin: 2rem auto; } +.sr-only { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + margin: -1px; + padding: 0; + border: 0; + clip: rect(0 0 0 0); + white-space: nowrap; +} + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { transition: none !important; animation: none !important; } + button:active { transform: none; } +} diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html index 8095409..de496d1 100644 --- a/src/main/resources/static/index.html +++ b/src/main/resources/static/index.html @@ -8,5 +8,6 @@

MediaGarrd Server

API is available under /api/v1.

+

The setup page lets you configure services and the backup location, but it is only available until setup is finished: /config

diff --git a/src/main/resources/static/js/api.js b/src/main/resources/static/js/api.js new file mode 100644 index 0000000..36c8fa5 --- /dev/null +++ b/src/main/resources/static/js/api.js @@ -0,0 +1,33 @@ +async function request(method, url, body) { + const response = await fetch(url, { + method, + headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + if (!response.ok) { + const data = await response.json().catch(() => ({})); + const failure = new Error(data.error || `${method} ${url} failed (${response.status})`); + failure.status = response.status; + failure.retryAfter = Number(response.headers.get('Retry-After')) || 0; + throw failure; + } + return response.status === 204 ? null : response.json(); +} + +const servicePath = (name) => `/api/v1/services/${encodeURIComponent(name)}`; + +export const api = { + getConfig: () => request('GET', '/api/v1/config'), + updateConfig: (settings) => request('PUT', '/api/v1/config', settings), + updateSchedule: (backupInterval) => request('PUT', '/api/v1/schedule', { backupInterval }), + getWebhook: () => request('GET', '/api/v1/notifications/webhook'), + updateWebhook: (url) => request('PUT', '/api/v1/notifications/webhook', { url }), + testWebhook: () => request('POST', '/api/v1/notifications/webhook/test'), + listServices: () => request('GET', '/api/v1/services'), + addService: (service) => request('POST', '/api/v1/services', service), + updateService: (name, service) => request('PUT', servicePath(name), service), + removeService: (name) => request('DELETE', servicePath(name)), + setupStatus: () => request('GET', '/api/v1/setup'), + startSetupSession: (pin) => request('POST', '/api/v1/setup/session', { pin }), + completeSetup: () => request('POST', '/api/v1/setup/complete'), +}; diff --git a/src/main/resources/static/js/config.js b/src/main/resources/static/js/config.js new file mode 100644 index 0000000..3619ada --- /dev/null +++ b/src/main/resources/static/js/config.js @@ -0,0 +1,36 @@ +import { initServices } from './services.js'; +import { initSettings } from './settings.js'; +import { initWebhook } from './webhook.js'; +import { initFinish, unlock } from './setup.js'; + +const workspace = document.querySelector('.workspace'); +const banner = document.getElementById('banner'); + +function show(message, kind) { + banner.textContent = message; + banner.className = `banner visible ${kind}`; +} + +const notify = { + ok: (message) => show(message, 'ok'), + error: (error) => show(error.message || String(error), 'error'), +}; + +function start() { + workspace.hidden = false; + initSettings(document.getElementById('settingsForm'), notify); + initWebhook(document.getElementById('webhookForm'), notify); + initServices(document.getElementById('services'), notify); + initFinish(document.getElementById('finish'), document.getElementById('pairingResult'), notify, () => { + workspace.querySelectorAll('[data-setup]').forEach((element) => element.remove()); + }); +} + +const fatal = document.getElementById('fatal'); +fatal.querySelector('[data-reload]').addEventListener('click', () => location.reload()); + +unlock(document.getElementById('pinDialog')).then(start).catch((error) => { + workspace.hidden = true; + fatal.querySelector('[data-message]').textContent = `Setup could not be unlocked: ${error.message || error}`; + fatal.hidden = false; +}); diff --git a/src/main/resources/static/js/services.js b/src/main/resources/static/js/services.js new file mode 100644 index 0000000..45913a3 --- /dev/null +++ b/src/main/resources/static/js/services.js @@ -0,0 +1,91 @@ +import { api } from './api.js'; + +export function initServices(root, notify) { + const form = root.querySelector('form'); + const title = root.querySelector('[data-form-title]'); + const paths = root.querySelector('[data-paths]'); + const cancel = root.querySelector('[data-cancel]'); + const rows = root.querySelector('tbody'); + const empty = root.querySelector('[data-empty]'); + const pathTemplate = root.querySelector('#pathTemplate'); + const rowTemplate = root.querySelector('#serviceTemplate'); + let editing = null; + + function addPathInput(value = '') { + const row = pathTemplate.content.firstElementChild.cloneNode(true); + row.querySelector('input').value = value; + row.querySelector('button').addEventListener('click', () => { + row.remove(); + if (!paths.children.length) addPathInput(); + }); + paths.append(row); + } + + function resetForm() { + editing = null; + form.reset(); + paths.replaceChildren(); + addPathInput(); + title.textContent = 'Add Service'; + cancel.hidden = true; + } + + function editService(service) { + editing = service.name; + form.elements.name.value = service.name; + paths.replaceChildren(); + service.paths.forEach(addPathInput); + title.textContent = `Edit ${service.name}`; + cancel.hidden = false; + form.elements.name.focus(); + } + + async function removeService(service) { + if (!confirm(`Remove ${service.name}? Existing backups are kept.`)) return; + try { + await api.removeService(service.name); + if (editing === service.name) resetForm(); + notify.ok(`Removed ${service.name}`); + await refresh(); + } catch (error) { + notify.error(error); + } + } + + function renderRow(service) { + const row = rowTemplate.content.firstElementChild.cloneNode(true); + row.querySelector('[data-name]').textContent = service.name; + row.querySelector('[data-paths]').textContent = service.paths.join('\n'); + row.querySelector('[data-edit]').addEventListener('click', () => editService(service)); + row.querySelector('[data-remove]').addEventListener('click', () => removeService(service)); + return row; + } + + async function refresh() { + const services = await api.listServices(); + rows.replaceChildren(...services.map(renderRow)); + empty.hidden = services.length > 0; + } + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + const service = { + name: form.elements.name.value, + paths: [...paths.querySelectorAll('input')].map((input) => input.value), + }; + try { + const saved = editing ? await api.updateService(editing, service) : await api.addService(service); + notify.ok(`Saved ${saved.name}`); + resetForm(); + await refresh(); + } catch (error) { + notify.error(error); + } + }); + + root.querySelector('[data-add-path]').addEventListener('click', () => addPathInput()); + cancel.addEventListener('click', resetForm); + + resetForm(); + refresh().catch(notify.error); +} diff --git a/src/main/resources/static/js/settings.js b/src/main/resources/static/js/settings.js new file mode 100644 index 0000000..070f84d --- /dev/null +++ b/src/main/resources/static/js/settings.js @@ -0,0 +1,47 @@ +import { api } from './api.js'; + +const ISO_DURATION = /^PT(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?$/; + +function toHours(duration) { + const [, hours = 0, minutes = 0, seconds = 0] = ISO_DURATION.exec(duration) || []; + return Number(hours) + Number(minutes) / 60 + Number(seconds) / 3600; +} + +const MIN_HOURS = 0.25; +const MAX_HOURS = 8760; + +const toDuration = (hours) => `PT${Math.round(hours * 60)}M`; + +export function initSettings(form, notify) { + const { backupLocation, intervalHours, retentionCount } = form.elements; + + function show(config) { + backupLocation.value = config.backupLocation; + intervalHours.value = toHours(config.backupInterval); + retentionCount.value = config.retentionCount; + } + + api.getConfig().then(show).catch(notify.error); + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + let saved = false; + const hours = Number(intervalHours.value); + if (!(hours >= MIN_HOURS && hours <= MAX_HOURS)) { + notify.error(new Error('Backup interval must be between 15 minutes and 365 days')); + return; + } + try { + const config = await api.updateConfig({ backupLocation: backupLocation.value, retentionCount: Number(retentionCount.value) }); + saved = true; + const { backupInterval } = await api.updateSchedule(toDuration(hours)); + show({ ...config, backupInterval }); + notify.ok('Backup settings saved'); + } catch (error) { + notify.error(saved ? new Error(`Location and backups to keep were saved, but the interval was not: ${error.message}`) : error); + if (saved) { + await api.getConfig().then(show).catch(() => {}); + } + } + }); +} diff --git a/src/main/resources/static/js/setup.js b/src/main/resources/static/js/setup.js new file mode 100644 index 0000000..521ec31 --- /dev/null +++ b/src/main/resources/static/js/setup.js @@ -0,0 +1,89 @@ +import { api } from './api.js'; + +function formatWait(seconds) { + const minutes = Math.floor(seconds / 60); + return `${minutes}:${String(seconds % 60).padStart(2, '0')}`; +} + +export async function unlock(dialog) { + const status = await api.setupStatus(); + if (status.authorized) return; + + const form = dialog.querySelector('form'); + const error = dialog.querySelector('[data-error]'); + const unlockButton = dialog.querySelector('[data-unlock]'); + dialog.addEventListener('cancel', (event) => event.preventDefault()); + dialog.showModal(); + + function lockFor(seconds) { + let left = seconds; + unlockButton.disabled = true; + const tick = setInterval(() => { + left -= 1; + if (left <= 0) { + clearInterval(tick); + unlockButton.disabled = false; + unlockButton.textContent = 'Unlock'; + return; + } + unlockButton.textContent = `Locked ${formatWait(left)}`; + }, 1000); + unlockButton.textContent = `Locked ${formatWait(left)}`; + } + + await new Promise((resolve) => { + form.addEventListener('submit', async (event) => { + event.preventDefault(); + try { + await api.startSetupSession(form.elements.pin.value); + dialog.close(); + resolve(); + } catch (e) { + error.textContent = e.message; + form.reset(); + form.elements.pin.focus(); + if (e.retryAfter) lockFor(e.retryAfter); + } + }); + }); +} + +function showPairing(panel, pairingPin, notify) { + const withPin = panel.querySelector('[data-with-pin]'); + const withoutPin = panel.querySelector('[data-without-pin]'); + withPin.hidden = !pairingPin; + withoutPin.hidden = Boolean(pairingPin); + if (pairingPin) { + const code = panel.querySelector('[data-pin]'); + const button = panel.querySelector('[data-copy-pin]'); + code.textContent = pairingPin; + button.addEventListener('click', async () => { + try { + await navigator.clipboard.writeText(pairingPin); + button.textContent = 'Copied'; + } catch { + window.getSelection().selectAllChildren(code); + notify.ok('Copying is not available on this connection. The PIN is selected, press Ctrl+C or Cmd+C to copy it.'); + } + }); + } + panel.hidden = false; +} + +export function initFinish(root, pairingPanel, notify, onComplete) { + const button = root.querySelector('[data-finish]'); + button.addEventListener('click', async () => { + if (button.disabled) return; + if (!confirm('Finish setup? This page will be disabled and further changes must go through the API or the MediaGarrd Client.')) return; + button.disabled = true; + try { + const result = await api.completeSetup(); + onComplete(); + notify.ok('Setup complete. This page is now disabled, further changes go through the Client.'); + showPairing(pairingPanel, result && result.pairingPin, notify); + } catch (error) { + button.disabled = false; + notify.error(error); + } + }); +} diff --git a/src/main/resources/static/js/webhook.js b/src/main/resources/static/js/webhook.js new file mode 100644 index 0000000..4c9d041 --- /dev/null +++ b/src/main/resources/static/js/webhook.js @@ -0,0 +1,63 @@ +import { api } from './api.js'; + +function describe(status) { + return status.configured ? `Configured: ${status.target}` : 'Not configured'; +} + +export function initWebhook(form, notify) { + const { url } = form.elements; + const label = form.querySelector('[data-webhook-status]'); + const buttons = form.querySelectorAll('button'); + + function show(status) { + label.textContent = describe(status); + url.value = ''; + } + + async function busy(task) { + buttons.forEach((button) => { button.disabled = true; }); + try { + await task(); + } catch (error) { + notify.error(error); + } finally { + buttons.forEach((button) => { button.disabled = false; }); + } + } + + async function save() { + const value = url.value.trim(); + if (value) { + show(await api.updateWebhook(value)); + } + return value; + } + + api.getWebhook().then((status) => { label.textContent = describe(status); }).catch(notify.error); + + form.addEventListener('submit', (event) => { + event.preventDefault(); + busy(async () => { + if (await save()) { + notify.ok('Webhook saved'); + } else { + notify.error(new Error('Enter a webhook URL, or use Clear to turn notifications off')); + } + }); + }); + + form.querySelector('[data-webhook-clear]').addEventListener('click', () => busy(async () => { + show(await api.updateWebhook('')); + notify.ok('Webhook cleared'); + })); + + form.querySelector('[data-webhook-test]').addEventListener('click', () => busy(async () => { + await save(); + const result = await api.testWebhook(); + if (result.delivered) { + notify.ok('Test message delivered'); + } else { + notify.error(new Error(`Test message was not delivered: ${result.error}`)); + } + })); +} diff --git a/src/test/java/wellatleastitried/mediagarrd/MediaGarrdPropertiesBindingTest.java b/src/test/java/wellatleastitried/mediagarrd/MediaGarrdPropertiesBindingTest.java deleted file mode 100644 index b037445..0000000 --- a/src/test/java/wellatleastitried/mediagarrd/MediaGarrdPropertiesBindingTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package wellatleastitried.mediagarrd; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; - -import java.util.EnumMap; - -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; - -import wellatleastitried.mediagarrd.Constants.Services; -import wellatleastitried.mediagarrd.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrd.services.config.CommonServiceConfig; -import wellatleastitried.mediagarrd.services.config.QBittorrentServiceConfig; - -@SpringBootTest(properties = { - "mediagarrd.backup-root=${java.io.tmpdir}/mediagarrd-properties-test", - "mediagarrd.services.jellyfin.enabled=false", - "mediagarrd.services.radarr.enabled=false", - "mediagarrd.services.sonarr.enabled=false", - "mediagarrd.services.prowlarr.enabled=false", - "mediagarrd.services.tdarr.enabled=false", - "mediagarrd.services.qbittorrent.enabled=false" -}) -class MediaGarrdPropertiesBindingTest { - - @Autowired - private MediaGarrdProperties properties; - - @Test - void bindsConcreteServiceConfigurations() { - EnumMap configs = properties.getServiceConfigs(); - - assertEquals(6, configs.size()); - assertInstanceOf(CommonServiceConfig.class, configs.get(Services.RADARR)); - assertInstanceOf(QBittorrentServiceConfig.class, configs.get(Services.QBITTORRENT)); - } -} diff --git a/src/test/java/wellatleastitried/mediagarrd/api/BackupControllerTest.java b/src/test/java/wellatleastitried/mediagarrd/api/BackupControllerTest.java deleted file mode 100644 index 0e10eca..0000000 --- a/src/test/java/wellatleastitried/mediagarrd/api/BackupControllerTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package wellatleastitried.mediagarrd.api; - -import static org.hamcrest.Matchers.hasSize; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.nio.file.Path; -import java.time.Duration; -import java.time.Instant; -import java.util.List; - -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.web.servlet.MockMvc; - -import wellatleastitried.mediagarrd.MediaGarrdProperties; -import wellatleastitried.mediagarrd.model.BackupArchive; -import wellatleastitried.mediagarrd.model.BackupRunResult; -import wellatleastitried.mediagarrd.service.BackupArchiveService; -import wellatleastitried.mediagarrd.service.BackupOrchestratorService; - -@WebMvcTest(BackupController.class) -class BackupControllerTest { - @Autowired - MockMvc mockMvc; - - @MockBean - BackupArchiveService archiveService; - - @MockBean - BackupOrchestratorService orchestratorService; - - @MockBean - MediaGarrdProperties properties; - - @Test - void healthReturnsServerStatus() throws Exception { - when(orchestratorService.isRunning()).thenReturn(false); - when(orchestratorService.getInterval()).thenReturn(Duration.ofHours(12)); - when(properties.getRetentionCount()).thenReturn(10); - - mockMvc.perform(get("/api/v1/health")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.healthy").value(true)); - } - - @Test - void runAndListBackups() throws Exception { - BackupArchive archive = new BackupArchive( - "backup-1", - "backup-1.zip", - Path.of("backup-1.zip"), - 12, - Instant.parse("2026-01-01T00:00:00Z") - ); - BackupRunResult result = new BackupRunResult( - "run-1", - Instant.parse("2026-01-01T00:00:00Z"), - Instant.parse("2026-01-01T00:01:00Z"), - List.of(), - archive - ); - when(orchestratorService.runBackup()).thenReturn(result); - when(archiveService.listArchives()).thenReturn(List.of(archive)); - - mockMvc.perform(post("/api/v1/backups/run")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.archive.id").isNotEmpty()); - - mockMvc.perform(get("/api/v1/backups")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$", hasSize(1))); - } -} diff --git a/src/test/java/wellatleastitried/mediagarrd/service/BackupArchiveServiceTest.java b/src/test/java/wellatleastitried/mediagarrd/service/BackupArchiveServiceTest.java deleted file mode 100644 index fdf7c1e..0000000 --- a/src/test/java/wellatleastitried/mediagarrd/service/BackupArchiveServiceTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package wellatleastitried.mediagarrd.service; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Path; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import wellatleastitried.mediagarrd.MediaGarrdProperties; - -class BackupArchiveServiceTest { - - @TempDir - Path tempDir; - - @Test - void createsArchiveAndEnforcesRetention() throws Exception { - MediaGarrdProperties properties = new MediaGarrdProperties(); - properties.setBackupRoot(tempDir.resolve("backups").toString()); - properties.setRetentionCount(2); - - BackupArchiveService service = new BackupArchiveService(properties); - - for (int i = 0; i < 3; i++) { - Path run = service.createRunDirectory(); - Files.writeString(run.resolve("marker" + i + ".txt"), "ok"); - service.createArchive(run); - service.removeRunDirectory(run); - Thread.sleep(10); - } - - assertEquals(2, service.listArchives().size()); - assertTrue(service.latest().isPresent()); - } -} diff --git a/src/test/java/wellatleastitried/mediagarrd/service/BackupScheduleServiceTest.java b/src/test/java/wellatleastitried/mediagarrd/service/BackupScheduleServiceTest.java deleted file mode 100644 index b94912b..0000000 --- a/src/test/java/wellatleastitried/mediagarrd/service/BackupScheduleServiceTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package wellatleastitried.mediagarrd.service; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.time.Duration; - -import org.junit.jupiter.api.Test; - -import wellatleastitried.mediagarrd.MediaGarrdProperties; - -class BackupScheduleServiceTest { - - @Test - void updatesAndEvaluatesDueState() { - MediaGarrdProperties props = new MediaGarrdProperties(); - props.setBackupInterval(Duration.ofMillis(1)); - - BackupScheduleService service = new BackupScheduleService(props); - service.updateInterval(Duration.ofMillis(1)); - - assertEquals(Duration.ofMillis(1), service.getInterval()); - assertFalse(service.dueNow()); - - try { - Thread.sleep(5); - } catch (InterruptedException ignored) { - } - - assertTrue(service.dueNow()); - } -} diff --git a/src/test/java/wellatleastitried/mediagarrd/service/RealRunnersInteractiveCheck.java b/src/test/java/wellatleastitried/mediagarrd/service/RealRunnersInteractiveCheck.java deleted file mode 100644 index bec1370..0000000 --- a/src/test/java/wellatleastitried/mediagarrd/service/RealRunnersInteractiveCheck.java +++ /dev/null @@ -1,120 +0,0 @@ -package wellatleastitried.mediagarrd.service; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.EnumMap; -import java.util.List; -import java.util.Locale; - -import wellatleastitried.mediagarrd.Constants.Services; -import wellatleastitried.mediagarrd.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrd.services.config.CommonServiceConfig; -import wellatleastitried.mediagarrd.services.config.QBittorrentServiceConfig; -import wellatleastitried.mediagarrd.services.runner.Runner; - -public final class RealRunnersInteractiveCheck { - - private RealRunnersInteractiveCheck() { - } - - public static void main(String[] args) throws Exception { - BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); - - System.out.println("=== Real Runner Integration Check ==="); - System.out.println("This check prompts for local directory/file paths on the server host."); - System.out.println("Any service you skip will not be run."); - - EnumMap configs = new EnumMap<>(Services.class); - configs.put(Services.JELLYFIN, promptJellyfin(reader)); - configs.put(Services.RADARR, promptPathService(reader, "Radarr")); - configs.put(Services.SONARR, promptPathService(reader, "Sonarr")); - configs.put(Services.PROWLARR, promptPathService(reader, "Prowlarr")); - configs.put(Services.TDARR, promptPathService(reader, "Tdarr")); - configs.put(Services.QBITTORRENT, promptQbittorrent(reader)); - - RunnerFactory factory = new RunnerFactory(); - List runners = factory.build(configs); - if (runners.isEmpty()) { - throw new IllegalStateException("No runners enabled. Re-run and enable at least one service."); - } - - Path output = Files.createTempDirectory("real-runner-output-"); - - System.out.println("Running " + runners.size() + " runners..."); - for (Runner runner : runners) { - System.out.println("- Running: " + runner.getServiceName()); - runner.run(output); - } - - long fileCount; - try (var walk = Files.walk(output)) { - fileCount = walk.filter(Files::isRegularFile).count(); - } - - if (fileCount <= 0) { - throw new IllegalStateException("No files were discovered/written by enabled runners."); - } - - System.out.println("Runner output directory: " + output); - System.out.println("Total files discovered: " + fileCount); - } - - private static AbstractServiceConfig promptJellyfin(BufferedReader reader) throws Exception { - CommonServiceConfig config = new CommonServiceConfig(); - boolean enabled = askYesNo(reader, "Enable Jellyfin runner? [y/N]: ", false); - config.setEnabled(enabled); - if (!enabled) { - return config; - } - - config.setConfigPath(ask(reader, "Jellyfin config directory", "/mnt/appdata/jellyfin/config")); - return config; - } - - private static AbstractServiceConfig promptPathService(BufferedReader reader, String label) throws Exception { - CommonServiceConfig config = new CommonServiceConfig(); - boolean enabled = askYesNo(reader, "Enable " + label + " runner? [y/N]: ", false); - config.setEnabled(enabled); - if (!enabled) { - return config; - } - - String lower = label.toLowerCase(Locale.ROOT); - config.setPath(ask(reader, label + " base directory", "/mnt/appdata/" + lower)); - return config; - } - - private static AbstractServiceConfig promptQbittorrent(BufferedReader reader) throws Exception { - QBittorrentServiceConfig config = new QBittorrentServiceConfig(); - boolean enabled = askYesNo(reader, "Enable qBittorrent runner? [y/N]: ", false); - config.setEnabled(enabled); - if (!enabled) { - return config; - } - - config.setPath(ask(reader, "qBittorrent base directory", "/mnt/appdata/qbittorrent")); - config.setSavedTorrentsPath(ask(reader, "qBittorrent saved torrents directory", "/mnt/media/saved-torrents")); - return config; - } - - private static String ask(BufferedReader reader, String prompt, String defaultValue) throws Exception { - System.out.print(prompt + (defaultValue == null || defaultValue.isBlank() ? ": " : " [" + defaultValue + "]: ")); - String line = reader.readLine(); - if (line == null) { - return defaultValue == null ? "" : defaultValue; - } - String trimmed = line.trim(); - if (trimmed.isEmpty()) { - return defaultValue == null ? "" : defaultValue; - } - return trimmed; - } - - private static boolean askYesNo(BufferedReader reader, String prompt, boolean defaultValue) throws Exception { - String fallback = defaultValue ? "y" : "n"; - String answer = ask(reader, prompt, fallback).toLowerCase(Locale.ROOT); - return answer.equals("y") || answer.equals("yes") || answer.equals("true"); - } -} diff --git a/src/test/java/wellatleastitried/mediagarrd/service/RunnersIntegrationTest.java b/src/test/java/wellatleastitried/mediagarrd/service/RunnersIntegrationTest.java deleted file mode 100644 index b676ffc..0000000 --- a/src/test/java/wellatleastitried/mediagarrd/service/RunnersIntegrationTest.java +++ /dev/null @@ -1,201 +0,0 @@ -package wellatleastitried.mediagarrd.service; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import wellatleastitried.mediagarrd.Constants.Services; -import wellatleastitried.mediagarrd.services.config.AbstractServiceConfig; -import wellatleastitried.mediagarrd.services.config.CommonServiceConfig; -import wellatleastitried.mediagarrd.services.config.QBittorrentServiceConfig; -import wellatleastitried.mediagarrd.services.runner.Runner; - -@Tag("real-runners") -class RunnersIntegrationTest { - - @TempDir - Path tempDir; - - @Test - void enabledRunnersCopyFilesFromConfiguredPaths() throws Exception { - Map env = loadEnv(); - - EnumMap configs = new EnumMap<>(Services.class); - - addJellyfin(configs, env); - addPathService(configs, env, Services.RADARR); - addPathService(configs, env, Services.SONARR); - addPathService(configs, env, Services.PROWLARR); - addPathService(configs, env, Services.TDARR); - addQbittorrent(configs, env); - - RunnerFactory factory = new RunnerFactory(); - List runners = factory.build(configs); - assertFalse(runners.isEmpty(), "No runners enabled in .env/.env.test."); - - Path outputDirectory = tempDir.resolve("runner-output"); - Files.createDirectories(outputDirectory); - - for (Runner runner : runners) { - runner.run(outputDirectory); - } - - assertEquals(configs.size(), runners.size()); - for (Runner runner : runners) { - Path serviceOutput = outputDirectory.resolve(runner.getServiceName().toLowerCase(Locale.ROOT)); - assertTrue(Files.exists(serviceOutput), "Missing service output directory: " + serviceOutput); - - try (var walk = Files.walk(serviceOutput)) { - assertTrue( - walk.anyMatch(Files::isRegularFile), - "No files copied for service " + runner.getServiceName() - ); - } - } - } - - private void addJellyfin(EnumMap configs, Map env) { - boolean enabled = booleanValue(env, "JELLYFIN_ENABLED", "jellyfin_enabled", false); - if (!enabled) { - return; - } - - CommonServiceConfig config = new CommonServiceConfig(); - config.setEnabled(true); - config.setConfigPath(required(env, "JELLYFIN_CONFIG_PATH", "jellyfin_config_path")); - - configs.put(Services.JELLYFIN, config); - } - - private void addQbittorrent(EnumMap configs, Map env) { - boolean enabled = booleanValue(env, "QBITTORRENT_ENABLED", "qbittorrent_enabled", false); - if (!enabled) { - return; - } - - QBittorrentServiceConfig config = new QBittorrentServiceConfig(); - config.setEnabled(true); - config.setPath(required(env, "QBITTORRENT_PATH", "qbittorrent_path")); - config.setSavedTorrentsPath(required(env, "QBITTORRENT_SAVED_TORRENTS_PATH", "qbittorrent_saved_torrents_path")); - - configs.put(Services.QBITTORRENT, config); - } - - private void addPathService( - EnumMap configs, - Map env, - Services service - ) { - String key = service.name().toLowerCase(Locale.ROOT); - String upper = service.name(); - boolean enabled = booleanValue(env, upper + "_ENABLED", key + "_enabled", false); - if (!enabled) { - return; - } - - CommonServiceConfig config = new CommonServiceConfig(); - config.setEnabled(true); - config.setPath(required(env, upper + "_PATH", key + "_path")); - - configs.put(service, config); - } - - private Map loadEnv() throws IOException { - Map merged = new HashMap<>(); - merged.putAll(parseDotEnv(resolveEnvFile())); - merged.putAll(System.getenv()); - return merged; - } - - private Path resolveEnvFile() { - String override = System.getenv("MEDIAGARRD_TEST_ENV_FILE"); - if (override != null && !override.isBlank()) { - Path explicit = Path.of(override).toAbsolutePath().normalize(); - if (Files.exists(explicit)) { - return explicit; - } - throw new IllegalStateException("MEDIAGARRD_TEST_ENV_FILE not found: " + explicit); - } - - Path current = Path.of("").toAbsolutePath(); - for (int i = 0; i < 8 && current != null; i++) { - Path testEnv = current.resolve(".env.test"); - if (Files.exists(testEnv)) { - return testEnv; - } - Path prodEnv = current.resolve(".env"); - if (Files.exists(prodEnv)) { - return prodEnv; - } - current = current.getParent(); - } - - throw new IllegalStateException("No .env.test or .env found. Create one from .env.test.example or .env.example."); - } - - private Map parseDotEnv(Path file) throws IOException { - Map values = new HashMap<>(); - List lines = Files.readAllLines(file); - for (String rawLine : lines) { - if (rawLine == null) { - continue; - } - String line = rawLine.trim(); - if (line.isBlank() || line.startsWith("#")) { - continue; - } - int idx = line.indexOf('='); - if (idx <= 0) { - continue; - } - String key = line.substring(0, idx).trim(); - String value = line.substring(idx + 1).trim(); - if ((value.startsWith("\"") && value.endsWith("\"")) || (value.startsWith("'") && value.endsWith("'"))) { - value = value.substring(1, value.length() - 1); - } - values.put(key, value); - } - return values; - } - - private String required(Map env, String... keys) { - String value = firstPresent(env, keys); - if (value == null || value.isBlank()) { - throw new IllegalStateException("Missing required .env key. Expected one of: " + String.join(", ", keys)); - } - return value; - } - - private boolean booleanValue(Map env, String keyUpper, String keyLower, boolean fallback) { - String value = firstPresent(env, keyUpper, keyLower); - if (value == null || value.isBlank()) { - return fallback; - } - String normalized = value.trim().toLowerCase(Locale.ROOT); - return normalized.equals("1") || normalized.equals("true") || normalized.equals("yes") || normalized.equals("y") || normalized.equals("on"); - } - - private String firstPresent(Map env, String... keys) { - for (String key : keys) { - String value = env.get(key); - if (value != null) { - return value; - } - } - return null; - } - -} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java new file mode 100644 index 0000000..40a1715 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java @@ -0,0 +1,35 @@ +package wellatleastitried.mediagarrdServer; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.Duration; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest(properties = { + "mediagarrd.backup-root=${java.io.tmpdir}/mediagarrd-binding-test/backups", + "mediagarrd.database-path=${java.io.tmpdir}/mediagarrd-binding-test/mediagarrd.db", + "mediagarrd.helper-image=alpine:3", + "mediagarrd.github-api-base-url=http://127.0.0.1:1" +}) +class MediaGarrdPropertiesBindingTest { + + @Autowired + private MediaGarrdProperties properties; + + @Test + void bindsApplicationProperties() { + String tmp = System.getProperty("java.io.tmpdir"); + + assertEquals(Duration.ofHours(12), properties.getBackupInterval()); + assertEquals(10, properties.getRetentionCount()); + assertEquals(tmp + "/mediagarrd-binding-test/backups", properties.getBackupRoot()); + assertEquals(tmp + "/mediagarrd-binding-test/mediagarrd.db", properties.getDatabasePath()); + assertEquals(1, properties.getCompressionLevel()); + assertEquals("alpine:3", properties.getHelperImage()); + assertEquals("MediaGarrd/Server", properties.getUpdateRepository()); + assertEquals("http://127.0.0.1:1", properties.getGithubApiBaseUrl()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ApiAuthSetupPhaseFullContextTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiAuthSetupPhaseFullContextTest.java new file mode 100644 index 0000000..a1fd3a3 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiAuthSetupPhaseFullContextTest.java @@ -0,0 +1,226 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import jakarta.servlet.http.Cookie; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@SpringBootTest +@AutoConfigureMockMvc +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ApiAuthSetupPhaseFullContextTest { + + private static final Path DATA_DIR = FullContextSupport.newDataDir(); + private static final List SETUP_ENDPOINTS = List.of( + "/api/v1/services", "/api/v1/config", "/api/v1/services;x", "/api/v1;x/services", "/api/v1/config;x"); + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) { + FullContextSupport.register(registry, DATA_DIR); + } + + @Autowired + MockMvc mockMvc; + + @Autowired + ServiceRepository services; + + @Autowired + SetupService setup; + + @Autowired + @Qualifier("requestMappingHandlerMapping") + RequestMappingHandlerMapping handlerMapping; + + @Test + @Order(0) + void everyResponseForbidsFraming() throws Exception { + for (String path : List.of("/config", "/config.html", "/api/v1/health", "/api/v1/services", "/no-such-page.html")) { + mockMvc.perform(get(path)) + .andExpect(header().string("X-Frame-Options", "DENY")) + .andExpect(header().string("Content-Security-Policy", SecurityHeadersFilter.CONTENT_SECURITY_POLICY)) + .andExpect(header().string("X-Content-Type-Options", "nosniff")) + .andExpect(header().string("Referrer-Policy", "no-referrer")); + } + } + + @Test + @Order(1) + void setupEndpointsNeedASetupSessionAndEverythingElseNeedsAToken() throws Exception { + for (String path : SETUP_ENDPOINTS) { + mockMvc.perform(get(path)).andExpect(status().isUnauthorized()); + } + mockMvc.perform(get("/api/v1/backups")).andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/events")).andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/clients")).andExpect(status().isUnauthorized()); + mockMvc.perform(get("/config")).andExpect(status().isOk()); + + Cookie session = startSession(); + + for (String path : List.of("/api/v1/services", "/api/v1/config", "/api/v1/services;x")) { + mockMvc.perform(get(path).cookie(session)).andExpect(status().isOk()); + } + mockMvc.perform(get("/api/v1/backups").cookie(session)).andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/events").cookie(session)).andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/clients").cookie(session)).andExpect(status().isUnauthorized()); + mockMvc.perform(post("/api/v1/pairing-codes").cookie(session)).andExpect(status().isUnauthorized()); + } + + @Test + @Order(2) + void everyCallTheSetupPageMakesWorksWithTheSetupSession() throws Exception { + Cookie session = startSession(); + String json = MediaType.APPLICATION_JSON_VALUE; + + mockMvc.perform(get("/api/v1/setup").cookie(session)).andExpect(status().isOk()) + .andExpect(jsonPath("$.authorized").value(true)); + mockMvc.perform(get("/api/v1/config").cookie(session)).andExpect(status().isOk()); + mockMvc.perform(put("/api/v1/config").cookie(session).contentType(json).content("{\"retentionCount\": 5}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.retentionCount").value(5)); + mockMvc.perform(put("/api/v1/schedule").cookie(session).contentType(json).content("{\"backupInterval\": \"PT2H\"}")) + .andExpect(status().isOk()); + mockMvc.perform(get("/api/v1/services").cookie(session)).andExpect(status().isOk()); + mockMvc.perform(post("/api/v1/services").cookie(session).contentType(json) + .content("{\"name\": \"lidarr\", \"paths\": [\"/srv/lidarr\"]}")) + .andExpect(status().isCreated()); + mockMvc.perform(put("/api/v1/services/lidarr").cookie(session).contentType(json) + .content("{\"name\": \"lidarr\", \"paths\": [\"/srv/lidarr\", \"/srv/lidarr2\"]}")) + .andExpect(status().isOk()); + mockMvc.perform(delete("/api/v1/services/lidarr").cookie(session)).andExpect(status().isNoContent()); + + mockMvc.perform(put("/api/v1/schedule").contentType(json).content("{\"backupInterval\": \"PT2H\"}")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(put("/api/v1/config").contentType(json).content("{\"retentionCount\": 5}")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/api/v1/services").contentType(json) + .content("{\"name\": \"lidarr\", \"paths\": [\"/srv/lidarr\"]}")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(delete("/api/v1/services/radarr")).andExpect(status().isUnauthorized()); + } + + @Test + @Order(6) + void theSetupSessionRoutesAreExactlyTheOnesTheSetupPageCalls() throws Exception { + Set pageCalls = new TreeSet<>(); + Matcher matcher = Pattern.compile("request\\('(\\w+)', (?:'([^']+)'|servicePath\\(name\\))") + .matcher(Files.readString(Path.of("src/main/resources/static/js/api.js"))); + while (matcher.find()) { + pageCalls.add(matcher.group(1) + " " + (matcher.group(2) != null ? matcher.group(2) : "/api/v1/services/{name}")); + } + assertTrue(pageCalls.size() >= 10, "Parsed only " + pageCalls); + + Set setupRoutes = new TreeSet<>(); + Set publicRoutes = new TreeSet<>(); + for (var entry : handlerMapping.getHandlerMethods().entrySet()) { + for (String pattern : entry.getKey().getPathPatternsCondition().getPatternValues()) { + for (var method : entry.getKey().getMethodsCondition().getMethods()) { + String key = method.name() + " " + pattern; + if (entry.getValue().hasMethodAnnotation(SetupSessionAllowed.class)) { + setupRoutes.add(key); + } + if (entry.getValue().hasMethodAnnotation(PublicEndpoint.class)) { + publicRoutes.add(key); + } + } + } + } + + Set tokenOrSession = new TreeSet<>(pageCalls); + tokenOrSession.removeAll(publicRoutes); + assertEquals(tokenOrSession, setupRoutes); + } + + @Test + @Order(3) + void pairingIsRefusedBeforeSetupCompletes() throws Exception { + mockMvc.perform(post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON) + .content("{\"pin\": \"" + FullContextSupport.currentPin(setup) + "\"}")) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error").value("This server has not finished setup yet. Finish it on the server's /config page, then pair.")); + } + + @Test + @Order(4) + void completingSetupOpensPairingAndRetiresTheSetupPageAndSession() throws Exception { + services.addService(new ServiceDefinition("radarr", List.of("/srv/radarr"))); + Cookie session = startSession(); + + mockMvc.perform(post("/api/v1/setup/complete")).andExpect(status().isUnauthorized()); + mockMvc.perform(post("/api/v1/setup/complete").cookie(session)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.pairingPin").value(FullContextSupport.currentPin(setup))) + .andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-store")) + .andExpect(cookie().maxAge(SetupInterceptor.SESSION_COOKIE, 0)); + + assertTrue(setup.isCompleted()); + assertTrue(setup.isPairingOpen()); + mockMvc.perform(get("/api/v1/services").cookie(session)).andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/services;x").cookie(session)).andExpect(status().isUnauthorized()); + mockMvc.perform(get("/config")).andExpect(status().isNotFound()); + mockMvc.perform(post("/api/v1/setup/session").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"123456\"}")) + .andExpect(status().isGone()); + } + + @Test + @Order(5) + void wrongPinsLockPairingOverHttp() throws Exception { + String current = FullContextSupport.currentPin(setup); + String wrong = current.substring(0, 5) + (current.charAt(5) == '0' ? '1' : '0'); + for (int i = 0; i < 5; i++) { + mockMvc.perform(pair(wrong)).andExpect(status().isUnauthorized()); + } + + mockMvc.perform(pair(FullContextSupport.currentPin(setup))) + .andExpect(status().isTooManyRequests()) + .andExpect(header().exists(HttpHeaders.RETRY_AFTER)) + .andExpect(jsonPath("$.error").exists()); + } + + private Cookie startSession() throws Exception { + String value = mockMvc.perform(post("/api/v1/setup/session").contentType(MediaType.APPLICATION_JSON) + .content("{\"pin\": \"" + FullContextSupport.currentPin(setup) + "\"}")) + .andExpect(status().isNoContent()) + .andReturn().getResponse().getCookie(SetupInterceptor.SESSION_COOKIE).getValue(); + return new Cookie(SetupInterceptor.SESSION_COOKIE, value); + } + + private static org.springframework.test.web.servlet.RequestBuilder pair(String pin) { + return post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"" + pin + "\"}"); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ApiAuthTokenFullContextTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiAuthTokenFullContextTest.java new file mode 100644 index 0000000..b994ce3 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiAuthTokenFullContextTest.java @@ -0,0 +1,288 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.nio.file.Path; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import tools.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdServer.repository.PairedClientRepository; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@SpringBootTest +@AutoConfigureMockMvc +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ApiAuthTokenFullContextTest { + + private static final Path DATA_DIR = FullContextSupport.newDataDir(); + private static final String TOKEN = "full-context-token-0123456789-abcdefghijklmnop"; + private static final Set OPEN_ENDPOINTS = Set.of( + "GET /api/v1/health", "GET /api/v1/version", "GET /api/v1/setup", "POST /api/v1/setup/session", "POST /api/v1/pair"); + private static final List PROTECTED_VARIANTS = List.of( + "/api/v1/services;x", + "/api/v1/services;jsessionid=1", + "/api/v1;x/services", + "/api/v1/%73ervices", + "/api/v1/services/", + "/api/v1/services/%2e", + "/api/v1/%2e/services", + "//api/v1/services", + "///api/v1/services", + "/api/v1//services", + "/API/v1/services", + "/api/v1/backups;x/latest/download", + "/api/v1/backups/latest/download/", + "/api/v1/events;x", + "/api/v1/clients;x"); + + @BeforeAll + static void seedCompletedSetup() { + FullContextSupport.openDatabase(DATA_DIR).settings.saveSetting("setup_completed", "2026-11-19 10:00:00"); + } + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) { + FullContextSupport.register(registry, DATA_DIR); + } + + @Autowired + MockMvc mockMvc; + + @Autowired + PairedClientRepository pairedClients; + + @Autowired + SetupService setup; + + @Autowired + @Qualifier("requestMappingHandlerMapping") + RequestMappingHandlerMapping handlerMapping; + + @AfterEach + void forgetTestClient() { + pairedClients.removePairedClient("test"); + } + + @Test + @Order(1) + void pairingWithThePinIssuesAWorkingTokenOnce() throws Exception { + assertTrue(setup.isCompleted()); + assertTrue(setup.isPairingOpen()); + String pin = FullContextSupport.currentPin(setup); + + MvcResult paired = mockMvc.perform(post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON) + .content("{\"pin\": \"" + pin + "\", \"name\": \"Test laptop\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.token").isNotEmpty()) + .andReturn(); + Map body = JsonMapper.builder().build().readValue(paired.getResponse().getContentAsString(), Map.class); + String token = (String) body.get("token"); + String id = (String) body.get("id"); + + MvcResult again = mockMvc.perform(post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON) + .content("{\"pin\": \"" + pin + "\"}")) + .andExpect(status().isOk()) + .andReturn(); + String unusedToken = (String) JsonMapper.builder().build().readValue(again.getResponse().getContentAsString(), Map.class).get("token"); + assertTrue(pairedClients.fetchPairedClients().isEmpty()); + + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isOk()); + mockMvc.perform(get("/api/v1/health").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.backupRetentionCount").exists()); + mockMvc.perform(get("/api/v1/clients").header(HttpHeaders.AUTHORIZATION, "bearer " + token)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(1))) + .andExpect(jsonPath("$[0].current").value(true)); + assertTrue(pairedClients.fetchPairedClientByTokenHash(PairingService.hashToken(token)).isPresent()); + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer " + unusedToken)) + .andExpect(status().isUnauthorized()); + + mockMvc.perform(post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"" + pin + "\"}")) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.error").exists()); + + mockMvc.perform(delete("/api/v1/clients/" + id).header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isNoContent()); + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isUnauthorized()); + } + + @Test + @Order(2) + void aCodeFromAPairedClientPairsAnotherOne() throws Exception { + String token = addClient(); + + MvcResult created = mockMvc.perform(post("/api/v1/pairing-codes").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.code").isNotEmpty()) + .andReturn(); + String code = (String) JsonMapper.builder().build().readValue(created.getResponse().getContentAsString(), Map.class).get("code"); + + MvcResult paired = mockMvc.perform(post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"" + code + "\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.token").isNotEmpty()) + .andReturn(); + String pending = (String) JsonMapper.builder().build().readValue(paired.getResponse().getContentAsString(), Map.class).get("token"); + mockMvc.perform(post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"" + code + "\"}")) + .andExpect(status().isOk()); + + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer " + pending)) + .andExpect(status().isOk()); + mockMvc.perform(post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"" + code + "\"}")) + .andExpect(status().isUnauthorized()); + } + + @Test + @Order(3) + void missingWrongAndRevokedTokensAreRejected() throws Exception { + String token = addClient(); + + mockMvc.perform(get("/api/v1/services")).andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").exists()); + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer nope")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Basic " + token)) + .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, token)) + .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/health").header(HttpHeaders.AUTHORIZATION, "Bearer nope")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isOk()); + + pairedClients.removePairedClient("test"); + + mockMvc.perform(get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isUnauthorized()); + } + + @Test + @Order(4) + void healthWithoutATokenRevealsOnlyWhatDiscoveryNeeds() throws Exception { + mockMvc.perform(get("/api/v1/health")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.healthy").value(true)) + .andExpect(jsonPath("$.backupInterval").exists()) + .andExpect(jsonPath("$.running").doesNotExist()) + .andExpect(jsonPath("$.backupRetentionCount").doesNotExist()); + } + + @Test + @Order(5) + void pathVariantsNeverReachAProtectedHandlerWithoutAToken() throws Exception { + for (String variant : PROTECTED_VARIANTS) { + for (HttpMethod method : List.of(HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE)) { + int status = mockMvc.perform(MockMvcRequestBuilders.request(method, variant) + .contentType(MediaType.APPLICATION_JSON).content("{}")) + .andReturn().getResponse().getStatus(); + assertTrue(status == 401 || status == 404 || status == 405, + method + " " + variant + " answered " + status + " without a token"); + } + } + for (String variant : List.of("/api/v1/services;x", "/api/v1;x/services", "/api/v1/%73ervices", "/api/v1/services/")) { + mockMvc.perform(get(variant)).andExpect(status().isUnauthorized()); + } + } + + @Test + @Order(6) + void aMatrixParameterVariantReachesTheHandlerOnlyWithAValidToken() throws Exception { + String token = addClient(); + + mockMvc.perform(get("/api/v1/services;x").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isOk()); + } + + @Test + @Order(7) + void everyRegisteredApiRouteOutsideTheAllowlistRequiresAToken() throws Exception { + Set reachableWithoutToken = new TreeSet<>(); + Set annotatedPublic = new TreeSet<>(); + int routes = 0; + for (Map.Entry entry : handlerMapping.getHandlerMethods().entrySet()) { + RequestMappingInfo info = entry.getKey(); + Set patterns = info.getPathPatternsCondition().getPatternValues(); + for (String pattern : patterns) { + if (pattern.equals("/error")) { + continue; + } + assertTrue(pattern.startsWith("/api/v1"), "Route outside /api/v1 bypasses the auth interceptor: " + pattern); + Set methods = info.getMethodsCondition().getMethods(); + assertFalse(methods.isEmpty(), "Route without an explicit method: " + pattern); + for (var method : methods) { + routes++; + String key = method.name() + " " + pattern; + if (entry.getValue().hasMethodAnnotation(PublicEndpoint.class)) { + annotatedPublic.add(key); + } + String path = pattern.replaceAll("\\{[^/]+}", "x"); + int status = mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.valueOf(method.name()), path)) + .andReturn().getResponse().getStatus(); + if (status != 401) { + reachableWithoutToken.add(key); + } + } + } + } + + assertTrue(routes >= 20, "Only " + routes + " routes were enumerated"); + assertEquals(OPEN_ENDPOINTS, reachableWithoutToken); + assertEquals(OPEN_ENDPOINTS, annotatedPublic); + } + + @Test + @Order(8) + void theSetupPageIsGoneAndASetupCookieIsUselessAfterCompletion() throws Exception { + mockMvc.perform(get("/config")).andExpect(status().isNotFound()); + mockMvc.perform(get("/config.html")).andExpect(status().isNotFound()); + mockMvc.perform(get("/config;x")).andExpect(status().isNotFound()); + mockMvc.perform(get("/js/config.js")).andExpect(status().isNotFound()); + mockMvc.perform(get("/api/v1/services").cookie(new jakarta.servlet.http.Cookie(SetupInterceptor.SESSION_COOKIE, "anything"))) + .andExpect(status().isUnauthorized()); + } + + private String addClient() { + pairedClients.addPairedClient("test", "Test client", PairingService.hashToken(TOKEN), Instant.now()); + return TOKEN; + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandlerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandlerTest.java new file mode 100644 index 0000000..c441eb3 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandlerTest.java @@ -0,0 +1,61 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.io.EOFException; +import java.io.IOException; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.web.context.request.async.AsyncRequestNotUsableException; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; + +class ApiExceptionHandlerTest { + private final ApiExceptionHandler handler = new ApiExceptionHandler(); + private final Logger logger = (Logger) LoggerFactory.getLogger(ApiExceptionHandler.class); + private final ListAppender events = new ListAppender<>(); + private Level previous; + + @BeforeEach + void capture() { + previous = logger.getLevel(); + logger.setLevel(Level.DEBUG); + events.start(); + logger.addAppender(events); + } + + @AfterEach + void release() { + logger.detachAppender(events); + logger.setLevel(previous); + } + + private List levelsAfterCommit(Exception e) throws IOException { + MockHttpServletResponse response = new MockHttpServletResponse(); + response.getWriter().flush(); + response.flushBuffer(); + assertNull(handler.unexpected(e, response)); + return events.list.stream().map(ILoggingEvent::getLevel).toList(); + } + + @Test + void aFailureAfterTheResponseStartedIsLoggedAsAWarning() throws IOException { + assertEquals(List.of(Level.WARN), levelsAfterCommit(new IOException("disk read failed"))); + } + + @Test + void aClientThatWentAwayIsOnlyLoggedAtDebug() throws IOException { + assertEquals(List.of(Level.DEBUG), levelsAfterCommit(new IOException("Broken pipe", new EOFException()))); + events.list.clear(); + assertEquals(List.of(Level.DEBUG), levelsAfterCommit(new AsyncRequestNotUsableException("gone"))); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ApiTestAuth.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiTestAuth.java new file mode 100644 index 0000000..2709fab --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ApiTestAuth.java @@ -0,0 +1,46 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.Optional; + +import org.springframework.http.HttpHeaders; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import wellatleastitried.mediagarrdServer.model.PairedClient; +import wellatleastitried.mediagarrdServer.service.PairingService; + +final class ApiTestAuth { + + static final String TOKEN = "test-token"; + static final PairedClient CLIENT = new PairedClient("c1", "Test client", Instant.parse("2026-11-19T10:00:00Z"), null); + + private ApiTestAuth() {} + + static void accept(PairingService pairing) { + when(pairing.authenticate(TOKEN)).thenReturn(Optional.of(CLIENT)); + when(pairing.isPaired(CLIENT.id())).thenReturn(true); + } + + static MockHttpServletRequestBuilder get(String url, Object... vars) { + return withToken(MockMvcRequestBuilders.get(url, vars)); + } + + static MockHttpServletRequestBuilder post(String url, Object... vars) { + return withToken(MockMvcRequestBuilders.post(url, vars)); + } + + static MockHttpServletRequestBuilder put(String url, Object... vars) { + return withToken(MockMvcRequestBuilders.put(url, vars)); + } + + static MockHttpServletRequestBuilder delete(String url, Object... vars) { + return withToken(MockMvcRequestBuilders.delete(url, vars)); + } + + private static MockHttpServletRequestBuilder withToken(MockHttpServletRequestBuilder builder) { + return builder.header(HttpHeaders.AUTHORIZATION, "Bearer " + TOKEN); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java new file mode 100644 index 0000000..ba71e2c --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java @@ -0,0 +1,327 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.hamcrest.Matchers.hasSize; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.delete; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.get; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.post; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupFailedException; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.service.RunRejectedException; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@WebMvcTest(BackupController.class) +class BackupControllerTest { + @Autowired + MockMvc mockMvc; + + @MockitoBean + BackupArchiveService archiveService; + + @MockitoBean + BackupOrchestratorService orchestratorService; + + @MockitoBean + RunStatusBroadcaster broadcaster; + + @MockitoBean + SetupService setup; + + @MockitoBean + PairingService pairing; + + @BeforeEach + void authorize() { + ApiTestAuth.accept(pairing); + } + + @Test + void healthReturnsServerStatus() throws Exception { + when(orchestratorService.isRunning()).thenReturn(false); + when(orchestratorService.getInterval()).thenReturn(Duration.ofHours(12)); + when(archiveService.retentionCount()).thenReturn(7); + + mockMvc.perform(get("/api/v1/health")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.healthy").value(true)) + .andExpect(jsonPath("$.backupRetentionCount").value(7)); + } + + @Test + void healthWithoutATokenIsMinimal() throws Exception { + when(orchestratorService.getInterval()).thenReturn(Duration.ofHours(12)); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/health")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.healthy").value(true)) + .andExpect(jsonPath("$.backupInterval").exists()) + .andExpect(jsonPath("$.running").doesNotExist()) + .andExpect(jsonPath("$.backupRetentionCount").doesNotExist()); + } + + @Test + void healthWithAnInvalidTokenIsUnauthorized() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/health").header(HttpHeaders.AUTHORIZATION, "Bearer revoked")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").exists()); + } + + @Test + void everythingElseNeedsAToken() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/backups")).andExpect(status().isUnauthorized()); + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/backups/latest/download")).andExpect(status().isUnauthorized()); + mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/backups/run")).andExpect(status().isUnauthorized()); + mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/backups/backup-1")).andExpect(status().isUnauthorized()); + mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/schedule") + .contentType(MediaType.APPLICATION_JSON).content("{\"backupInterval\": \"PT2H\"}")) + .andExpect(status().isUnauthorized()); + + verifyNoInteractions(orchestratorService, archiveService); + } + + @Test + void runAndListBackups() throws Exception { + String errorMessage = "testErrorMessage"; + BackupArchive archive = new BackupArchive( + "backup-1", + "backup-1.zip", + Path.of("backup-1.zip"), + 12, + Instant.parse("2026-01-01T00:00:00Z") + ); + BackupRunResult result = new BackupRunResult( + "run-1", + "2026-01-01T00:00:00Z", + "2026-01-01T00:01:00Z", + "testStatus", + List.of(), + archive, + errorMessage + ); + when(orchestratorService.runBackup()).thenReturn(result); + when(archiveService.listArchives()).thenReturn(List.of(archive)); + + mockMvc.perform(post("/api/v1/backups/run")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.runId").value("run-1")) + .andExpect(jsonPath("$.startTime").value("2026-01-01T00:00:00Z")) + .andExpect(jsonPath("$.endTime").value("2026-01-01T00:01:00Z")) + .andExpect(jsonPath("$.servicesRan", hasSize(0))) + .andExpect(jsonPath("$.archive.id").value("backup-1")) + .andExpect(jsonPath("$.archive.fileName").value("backup-1.zip")) + .andExpect(jsonPath("$.archive.sizeBytes").value(12)) + .andExpect(jsonPath("$.archive.createdAt").value("2026-01-01T00:00:00Z")) + .andExpect(jsonPath("$.archive.path").doesNotExist()); + + mockMvc.perform(get("/api/v1/backups")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(1))) + .andExpect(jsonPath("$[0].id").value("backup-1")) + .andExpect(jsonPath("$[0].fileName").value("backup-1.zip")) + .andExpect(jsonPath("$[0].sizeBytes").value(12)) + .andExpect(jsonPath("$[0].createdAt").value("2026-01-01T00:00:00Z")) + .andExpect(jsonPath("$[0].path").doesNotExist()); + } + + @Test + void latestAndByIdReturnTheBackupWithoutItsPath() throws Exception { + BackupArchive archive = new BackupArchive("backup-2", "backup-2.zip", Path.of("/srv/backups/backup-2.zip"), 34, Instant.parse("2026-02-01T00:00:00Z")); + when(archiveService.latest()).thenReturn(java.util.Optional.of(archive)); + when(archiveService.byId("backup-2")).thenReturn(java.util.Optional.of(archive)); + + for (String url : List.of("/api/v1/backups/latest", "/api/v1/backups/backup-2")) { + mockMvc.perform(get(url)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value("backup-2")) + .andExpect(jsonPath("$.fileName").value("backup-2.zip")) + .andExpect(jsonPath("$.sizeBytes").value(34)) + .andExpect(jsonPath("$.createdAt").value("2026-02-01T00:00:00Z")) + .andExpect(jsonPath("$.path").doesNotExist()); + } + } + + @Test + void theLatestDownloadStreamsTheNewestArchiveAsAnAttachment(@TempDir Path tempDir) throws Exception { + Path file = tempDir.resolve("latest.zip"); + java.nio.file.Files.writeString(file, "newest-bytes"); + BackupArchive archive = new BackupArchive("20261121-media-backup", "20261121-media-backup.zip", file, 12, Instant.EPOCH); + when(archiveService.latest()).thenReturn(java.util.Optional.of(archive)); + + mockMvc.perform(get("/api/v1/backups/latest/download")) + .andExpect(status().isOk()) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header() + .string(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"20261121-media-backup.zip\"")) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header() + .string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE)) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header() + .string(HttpHeaders.CONTENT_LENGTH, "12")) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.content().string("newest-bytes")); + } + + @Test + void rejectedRunReturnsConflictWithReason() throws Exception { + when(orchestratorService.runBackup()).thenThrow(new RunRejectedException("A backup run is already in progress")); + + mockMvc.perform(post("/api/v1/backups/run")) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error").value("A backup run is already in progress")); + } + + @Test + void failedRunReturnsServerErrorWithReason() throws Exception { + when(orchestratorService.runBackup()).thenThrow(new BackupFailedException("Every service failed, no archive created: radarr: boom")); + + mockMvc.perform(post("/api/v1/backups/run")) + .andExpect(status().isInternalServerError()) + .andExpect(jsonPath("$.error").value("Every service failed, no archive created: radarr: boom")); + } + + @Test + void unexpectedFailureHidesItsDetails() throws Exception { + when(orchestratorService.runBackup()).thenThrow(new IllegalStateException("Failed to create run directory /data/server/backups/run-1")); + + mockMvc.perform(post("/api/v1/backups/run")) + .andExpect(status().isInternalServerError()) + .andExpect(jsonPath("$.error").value("Internal error")); + } + + @Test + void deletingABackupPublishesBackupsChanged() throws Exception { + when(archiveService.deleteById("backup-1")).thenReturn(true); + + mockMvc.perform(delete("/api/v1/backups/backup-1")) + .andExpect(status().isNoContent()); + + org.mockito.Mockito.verify(broadcaster).publishBackupsChanged(); + } + + @Test + void deletingAMissingBackupPublishesNothing() throws Exception { + when(archiveService.deleteById("nope")).thenReturn(false); + + mockMvc.perform(delete("/api/v1/backups/nope")) + .andExpect(status().isNotFound()); + + org.mockito.Mockito.verify(broadcaster, org.mockito.Mockito.never()).publishBackupsChanged(); + } + + @Test + void updatingTheSchedulePublishesConfigChanged() throws Exception { + when(orchestratorService.updateInterval(Duration.ofHours(2))).thenReturn(Duration.ofHours(2)); + + mockMvc.perform(put("/api/v1/schedule") + .contentType(org.springframework.http.MediaType.APPLICATION_JSON) + .content("{\"backupInterval\": \"PT2H\"}")) + .andExpect(status().isOk()); + + org.mockito.Mockito.verify(broadcaster).publishConfigChanged(); + } + + @Test + void notFoundAnswersWithTheErrorShape() throws Exception { + when(archiveService.byId("nope")).thenReturn(java.util.Optional.empty()); + when(archiveService.latest()).thenReturn(java.util.Optional.empty()); + when(archiveService.deleteById("nope")).thenReturn(false); + + mockMvc.perform(get("/api/v1/backups/nope")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Backup not found")); + mockMvc.perform(get("/api/v1/backups/latest")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("No backup archives found")); + mockMvc.perform(get("/api/v1/backups/latest/download")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("No backup archives found")); + mockMvc.perform(get("/api/v1/backups/nope/download")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Backup not found")); + mockMvc.perform(delete("/api/v1/backups/nope")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Backup not found")); + } + + @Test + void aMissingArchiveFileIsNotFoundWithTheErrorShape() throws Exception { + BackupArchive archive = new BackupArchive("gone", "gone.zip", Path.of("/nonexistent/gone.zip"), 1, Instant.EPOCH); + when(archiveService.byId("gone")).thenReturn(java.util.Optional.of(archive)); + + mockMvc.perform(get("/api/v1/backups/gone/download")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Backup file missing on disk")); + } + + @Test + void downloadsCarryAnAttachmentHeaderAndAreNotBrokenByNoStore() throws Exception { + Path file = java.nio.file.Files.createTempFile("download", ".zip"); + java.nio.file.Files.writeString(file, "zip-bytes"); + BackupArchive archive = new BackupArchive("20261120-media-backup", "20261120-media-backup.zip", file, 9, Instant.EPOCH); + when(archiveService.byId("20261120-media-backup")).thenReturn(java.util.Optional.of(archive)); + + mockMvc.perform(get("/api/v1/backups/20261120-media-backup/download")) + .andExpect(status().isOk()) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header() + .string(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"20261120-media-backup.zip\"")) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.content().string("zip-bytes")); + } + + @Test + void anUnauthenticatedCallBeforeSetupSaysSetupIsUnfinished() throws Exception { + when(setup.isCompleted()).thenReturn(false); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/backups")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").value(org.hamcrest.Matchers.containsString("Setup is not finished"))); + } + + @Test + void anUnauthenticatedCallAfterSetupAsksForAToken() throws Exception { + when(setup.isCompleted()).thenReturn(true); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/backups")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").value(org.hamcrest.Matchers.containsString("Authorization required"))); + } + + @Test + void springRejectionsUseTheErrorShapeToo() throws Exception { + mockMvc.perform(post("/api/v1/backups/nope")) + .andExpect(status().isMethodNotAllowed()) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header().exists("Allow")) + .andExpect(jsonPath("$.error").value("Method Not Allowed")); + } + + @Test + void anOverlongBodyIsRefusedBeforeItReachesTheController() throws Exception { + mockMvc.perform(put("/api/v1/schedule") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"backupInterval\": \"" + "P".repeat(RequestBodyLimitFilter.MAX_BODY_BYTES) + "\"}")) + .andExpect(status().isContentTooLarge()) + .andExpect(jsonPath("$.error").value(RequestBodyLimitFilter.MESSAGE)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java new file mode 100644 index 0000000..7c3db04 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java @@ -0,0 +1,321 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.hamcrest.Matchers.hasSize; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.delete; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.get; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.post; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import jakarta.servlet.http.Cookie; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupInProgressException; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.service.BackupRunLifecycle; +import wellatleastitried.mediagarrdServer.service.DockerService; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.ServiceConfigService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@WebMvcTest(ConfigController.class) +@Import(ServiceConfigService.class) +class ConfigControllerTest { + + private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr")); + private static final String RADARR_JSON = """ + {"name": "radarr", "paths": ["/srv/radarr"]} + """; + + @Autowired + MockMvc mockMvc; + + @MockitoBean + BackupArchiveService archiveService; + + @MockitoBean + ServiceRepository services; + + @MockitoBean + DockerService docker; + + @MockitoBean + RunStatusBroadcaster broadcaster; + + @MockitoBean + SetupService setup; + + @MockitoBean + PairingService pairing; + + @MockitoBean + BackupOrchestratorService orchestrator; + + @MockitoBean + BackupRunLifecycle lifecycle; + + @BeforeEach + void setUp() { + ApiTestAuth.accept(pairing); + when(lifecycle.whileIdle(any())).thenAnswer(invocation -> invocation.>getArgument(0).get()); + when(orchestrator.getInterval()).thenReturn(Duration.ofHours(6)); + when(archiveService.retentionCount()).thenReturn(4); + } + + @Test + void rejectsConfigChangesWhileBackupIsRunning() throws Exception { + doThrow(new BackupInProgressException("busy")).when(lifecycle).whileIdle(any()); + + mockMvc.perform(json(post("/api/v1/services"), RADARR_JSON)) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error").value("busy")); + mockMvc.perform(delete("/api/v1/services/radarr")).andExpect(status().isConflict()); + mockMvc.perform(json(put("/api/v1/services/radarr"), RADARR_JSON)).andExpect(status().isConflict()); + mockMvc.perform(json(put("/api/v1/config"), "{\"retentionCount\": 3}")).andExpect(status().isConflict()); + + verify(services, never()).addService(any()); + verify(services, never()).removeService(anyString()); + verify(archiveService, never()).updateSettings(any(), any()); + verify(broadcaster, never()).publishConfigChanged(); + verify(broadcaster, never()).publishBackupsChanged(); + } + + @Test + void requiresSetupSessionUntilSetupIsComplete() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/services")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").exists()); + mockMvc.perform(json(MockMvcRequestBuilders.post("/api/v1/services"), RADARR_JSON)) + .andExpect(status().isUnauthorized()); + mockMvc.perform(json(MockMvcRequestBuilders.put("/api/v1/config"), "{\"backupLocation\": \"/new\"}")) + .andExpect(status().isUnauthorized()); + + verify(services, never()).fetchServices(); + verify(services, never()).addService(any()); + verify(archiveService, never()).updateSettings(any(), any()); + } + + @Test + void aSetupSessionIsEnoughBeforeSetupCompletes() throws Exception { + when(setup.canConfigure("session")).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/services").cookie(new Cookie(SetupInterceptor.SESSION_COOKIE, "session"))) + .andExpect(status().isOk()); + } + + @Test + void aSetupSessionIsIgnoredAfterSetupCompletes() throws Exception { + when(setup.isCompleted()).thenReturn(true); + when(setup.canConfigure("session")).thenReturn(true); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/services").cookie(new Cookie(SetupInterceptor.SESSION_COOKIE, "session"))) + .andExpect(status().isUnauthorized()) + .andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, "Bearer")); + } + + @Test + void aWrongTokenIsRejectedEvenBeforeSetupCompletes() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/services").header(HttpHeaders.AUTHORIZATION, "Bearer wrong")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").value("Invalid or revoked token, pair this client again")); + } + + @Test + void returnsBackupLocation() throws Exception { + when(archiveService.rootDirectory()).thenReturn(Path.of("/backups")); + + mockMvc.perform(get("/api/v1/config")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.backupLocation").value("/backups")) + .andExpect(jsonPath("$.retentionCount").value(4)) + .andExpect(jsonPath("$.backupInterval").exists()); + } + + @Test + void updatesBackupLocationAndRetentionCount() throws Exception { + when(archiveService.rootDirectory()).thenReturn(Path.of("/new")); + + mockMvc.perform(json(put("/api/v1/config"), "{\"backupLocation\": \"/new\", \"retentionCount\": 4}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.backupLocation").value("/new")) + .andExpect(jsonPath("$.retentionCount").value(4)); + + verify(archiveService).updateSettings("/new", 4); + verify(broadcaster).publishBackupsChanged(); + verify(broadcaster).publishConfigChanged(); + } + + @Test + void passesOmittedFieldsAsNull() throws Exception { + when(archiveService.rootDirectory()).thenReturn(Path.of("/backups")); + + mockMvc.perform(json(put("/api/v1/config"), "{\"retentionCount\": 4}")) + .andExpect(status().isOk()); + + verify(archiveService).updateSettings(isNull(), eq(4)); + verify(broadcaster, never()).publishBackupsChanged(); + verify(broadcaster).publishConfigChanged(); + } + + @Test + void rejectsInvalidBackupLocation() throws Exception { + doThrow(new IllegalArgumentException("must be absolute")).when(archiveService).updateSettings("relative", null); + + mockMvc.perform(json(put("/api/v1/config"), "{\"backupLocation\": \"relative\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("must be absolute")); + } + + @Test + void listsServices() throws Exception { + when(services.fetchServices()).thenReturn(List.of(RADARR)); + + mockMvc.perform(get("/api/v1/services")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(1))) + .andExpect(jsonPath("$[0].name").value("radarr")) + .andExpect(jsonPath("$[0].paths[0]").value("/srv/radarr")); + } + + @Test + void addsNormalizedService() throws Exception { + when(services.fetchService("radarr")).thenReturn(Optional.empty()); + + mockMvc.perform(json(post("/api/v1/services"), "{\"name\": \" radarr \", \"paths\": [\"/srv/radarr/\", \"\"]}")) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.name").value("radarr")) + .andExpect(jsonPath("$.paths", hasSize(1))); + + verify(services).addService(RADARR); + verify(orchestrator).servicesChanged(); + verify(broadcaster).publishConfigChanged(); + } + + @Test + void rejectsDuplicateService() throws Exception { + when(services.fetchService("radarr")).thenReturn(Optional.of(RADARR)); + + mockMvc.perform(json(post("/api/v1/services"), RADARR_JSON)) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error").exists()); + + verify(services, never()).addService(any()); + verify(orchestrator, never()).servicesChanged(); + verify(broadcaster, never()).publishConfigChanged(); + } + + @Test + void rejectsInvalidService() throws Exception { + mockMvc.perform(json(post("/api/v1/services"), "{\"name\": \"radarr\", \"paths\": [\"relative\"]}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Path must be absolute: relative")); + + verify(services, never()).addService(any()); + } + + @Test + void updatesServiceKeepingContainersWhenNameUnchanged() throws Exception { + when(services.fetchService("radarr")).thenReturn(Optional.of(RADARR)); + + mockMvc.perform(json(put("/api/v1/services/radarr"), "{\"name\": \"radarr\", \"paths\": [\"/srv/other\"]}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.paths[0]").value("/srv/other")); + + verify(services).updateService("radarr", new ServiceDefinition("radarr", List.of("/srv/other"))); + verify(orchestrator).servicesChanged(); + verify(docker, never()).removeContainers(anyString()); + verify(broadcaster).publishConfigChanged(); + } + + @Test + void renamingServiceRemovesOldContainers() throws Exception { + when(services.fetchService("RADARR")).thenReturn(Optional.of(RADARR)); + when(services.fetchService("movies")).thenReturn(Optional.empty()); + + mockMvc.perform(json(put("/api/v1/services/RADARR"), "{\"name\": \"movies\", \"paths\": [\"/srv/radarr\"]}")) + .andExpect(status().isOk()); + + verify(services).updateService("radarr", new ServiceDefinition("movies", List.of("/srv/radarr"))); + verify(docker).removeContainers("radarr"); + } + + @Test + void renamingOntoExistingServiceConflicts() throws Exception { + when(services.fetchService("radarr")).thenReturn(Optional.of(RADARR)); + when(services.fetchService("sonarr")).thenReturn(Optional.of(new ServiceDefinition("sonarr", List.of("/srv/sonarr")))); + + mockMvc.perform(json(put("/api/v1/services/radarr"), "{\"name\": \"sonarr\", \"paths\": [\"/srv/radarr\"]}")) + .andExpect(status().isConflict()); + + verify(services, never()).updateService(anyString(), any()); + verify(orchestrator, never()).servicesChanged(); + verify(broadcaster, never()).publishConfigChanged(); + } + + @Test + void updatingMissingServiceReturnsNotFound() throws Exception { + when(services.fetchService("radarr")).thenReturn(Optional.empty()); + + mockMvc.perform(json(put("/api/v1/services/radarr"), RADARR_JSON)) + .andExpect(status().isNotFound()); + + verify(orchestrator, never()).servicesChanged(); + } + + @Test + void removesServiceAndItsContainers() throws Exception { + when(services.fetchService("Radarr")).thenReturn(Optional.of(RADARR)); + + mockMvc.perform(delete("/api/v1/services/Radarr")) + .andExpect(status().isNoContent()); + + verify(services).removeService("radarr"); + verify(docker).removeContainers("radarr"); + verify(broadcaster).publishConfigChanged(); + } + + @Test + void removingMissingServiceReturnsNotFound() throws Exception { + when(services.fetchService("radarr")).thenReturn(Optional.empty()); + + mockMvc.perform(delete("/api/v1/services/radarr")) + .andExpect(status().isNotFound()); + + verify(docker, never()).removeContainers(anyString()); + } + + private static MockHttpServletRequestBuilder json(MockHttpServletRequestBuilder request, String body) { + return request.contentType(MediaType.APPLICATION_JSON).content(body); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/DtoWireFormatTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/DtoWireFormatTest.java new file mode 100644 index 0000000..f28a446 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/DtoWireFormatTest.java @@ -0,0 +1,296 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdServer.dto.BackupDto; +import wellatleastitried.mediagarrdServer.dto.BackupRunDto; +import wellatleastitried.mediagarrdServer.dto.CheckState; +import wellatleastitried.mediagarrdServer.dto.ConfigUpdateRequest; +import wellatleastitried.mediagarrdServer.dto.PairRequest; +import wellatleastitried.mediagarrdServer.dto.PairResponse; +import wellatleastitried.mediagarrdServer.dto.PairedClientDto; +import wellatleastitried.mediagarrdServer.dto.PairingCodeDto; +import wellatleastitried.mediagarrdServer.dto.PublicHealthDto; +import wellatleastitried.mediagarrdServer.dto.ScheduleUpdateRequest; +import wellatleastitried.mediagarrdServer.dto.ServerConfigDto; +import wellatleastitried.mediagarrdServer.dto.ServerStatusDto; +import wellatleastitried.mediagarrdServer.dto.SetupCompleteDto; +import wellatleastitried.mediagarrdServer.dto.SetupSessionRequest; +import wellatleastitried.mediagarrdServer.dto.SetupStatusDto; +import wellatleastitried.mediagarrdServer.dto.VersionStatusDto; +import wellatleastitried.mediagarrdServer.model.PairedClient; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@WebMvcTest(DtoWireFormatTest.WireController.class) +@Import(DtoWireFormatTest.WireController.class) +class DtoWireFormatTest { + + private static final Instant MILLIS = Instant.parse("2026-11-11T18:00:00.123Z"); + private static final Instant WHOLE = Instant.parse("2026-11-11T18:00:00Z"); + private static final Instant NANOS = Instant.parse("2026-11-11T18:00:00.123456789Z"); + + @RestController + static class WireController { + + @GetMapping("/wire/backup") + BackupDto backup() { + return new BackupDto("id-1", "backup-1.zip", 1234567890123L, MILLIS); + } + + @GetMapping("/wire/backup-nanos") + BackupDto backupNanos() { + return new BackupDto("id-1", "backup-1.zip", 1L, NANOS); + } + + @GetMapping("/wire/backup-whole") + BackupDto backupWhole() { + return new BackupDto("id-1", "backup-1.zip", 1L, WHOLE); + } + + @GetMapping("/wire/backup-run") + BackupRunDto backupRun() { + return new BackupRunDto("run-1", "2026-11-11T18:00:00Z", "2026-11-11T18:05:00Z", List.of("a", "b"), + new BackupDto("id-1", "backup-1.zip", 10L, WHOLE)); + } + + @GetMapping("/wire/backup-run-empty") + BackupRunDto backupRunEmpty() { + return new BackupRunDto("run-1", "s", "e", List.of(), null); + } + + @GetMapping("/wire/paired-client") + PairedClientDto pairedClient() { + return new PairedClientDto("c-1", "Living room", WHOLE, null, true); + } + + @GetMapping("/wire/paired-client-used") + PairedClientDto pairedClientUsed() { + return new PairedClientDto("c-1", "Living room", WHOLE, MILLIS, false); + } + + @GetMapping("/wire/pairing-code") + PairingCodeDto pairingCode() { + return new PairingCodeDto("ABCD-EFGH", WHOLE); + } + + @GetMapping("/wire/pair-response") + PairResponse pairResponse() { + return new PairResponse("tok", "c-1", "Living room"); + } + + @GetMapping("/wire/public-health") + PublicHealthDto publicHealth() { + return new PublicHealthDto(true, Duration.ofHours(12)); + } + + @GetMapping("/wire/server-config") + ServerConfigDto serverConfig() { + return new ServerConfigDto("/var/lib/mediagarrd/backups", 10, Duration.ofMinutes(90)); + } + + @GetMapping("/wire/server-status") + ServerStatusDto serverStatus() { + return new ServerStatusDto(true, false, 10, Duration.ofSeconds(3661)); + } + + @GetMapping("/wire/setup-status") + SetupStatusDto setupStatus() { + return new SetupStatusDto(false, true); + } + + @GetMapping("/wire/setup-complete") + SetupCompleteDto setupComplete() { + return new SetupCompleteDto("123456"); + } + + @GetMapping("/wire/setup-complete-no-pin") + SetupCompleteDto setupCompleteNoPin() { + return new SetupCompleteDto(null); + } + + @GetMapping("/wire/version-status") + VersionStatusDto versionStatus() { + return new VersionStatusDto("0.1.0", "0.2.0", "https://example.invalid/r", true, CheckState.OK, MILLIS, null); + } + + @GetMapping("/wire/version-status-error") + VersionStatusDto versionStatusError() { + return new VersionStatusDto("0.1.0", null, null, false, CheckState.NO_RELEASES, WHOLE, "none"); + } + + @GetMapping("/wire/paired-client-model") + PairedClient pairedClientModel() { + return new PairedClient("c-1", "Living room", WHOLE, MILLIS); + } + + @GetMapping("/wire/service-definition") + ServiceDefinition serviceDefinition() { + return new ServiceDefinition("plex", List.of("/a", "/b")); + } + + @PostMapping("/wire/echo/config-update") + ConfigUpdateRequest echoConfigUpdate(@RequestBody ConfigUpdateRequest r) { + return r; + } + + @PostMapping("/wire/echo/pair-request") + PairRequest echoPairRequest(@RequestBody PairRequest r) { + return r; + } + + @PostMapping("/wire/echo/schedule-update") + ScheduleUpdateRequest echoScheduleUpdate(@RequestBody ScheduleUpdateRequest r) { + return r; + } + + @PostMapping("/wire/echo/setup-session") + SetupSessionRequest echoSetupSession(@RequestBody SetupSessionRequest r) { + return r; + } + + @PostMapping("/wire/echo/service-definition") + ServiceDefinition echoServiceDefinition(@RequestBody ServiceDefinition r) { + return r; + } + } + + @Autowired + MockMvc mockMvc; + + @MockitoBean + SetupService setup; + + @MockitoBean + PairingService pairing; + + private void assertWire(String path, String expected) throws Exception { + mockMvc.perform(get(path)) + .andExpect(status().isOk()) + .andExpect(content().string(expected)); + } + + private void assertEcho(String path, String request, String expected) throws Exception { + mockMvc.perform(post(path).contentType(MediaType.APPLICATION_JSON).content(request)) + .andExpect(status().isOk()) + .andExpect(content().string(expected)); + } + + @Test + void backupDtoWritesInstantsAsIsoStrings() throws Exception { + assertWire("/wire/backup", + "{\"id\":\"id-1\",\"fileName\":\"backup-1.zip\",\"sizeBytes\":1234567890123,\"createdAt\":\"2026-11-11T18:00:00.123Z\"}"); + assertWire("/wire/backup-whole", + "{\"id\":\"id-1\",\"fileName\":\"backup-1.zip\",\"sizeBytes\":1,\"createdAt\":\"2026-11-11T18:00:00Z\"}"); + assertWire("/wire/backup-nanos", + "{\"id\":\"id-1\",\"fileName\":\"backup-1.zip\",\"sizeBytes\":1,\"createdAt\":\"2026-11-11T18:00:00.123456789Z\"}"); + } + + @Test + void backupRunDtoKeepsNullsAndNestedArchive() throws Exception { + assertWire("/wire/backup-run", + "{\"runId\":\"run-1\",\"startTime\":\"2026-11-11T18:00:00Z\",\"endTime\":\"2026-11-11T18:05:00Z\"," + + "\"servicesRan\":[\"a\",\"b\"],\"archive\":{\"id\":\"id-1\",\"fileName\":\"backup-1.zip\"," + + "\"sizeBytes\":10,\"createdAt\":\"2026-11-11T18:00:00Z\"}}"); + assertWire("/wire/backup-run-empty", + "{\"runId\":\"run-1\",\"startTime\":\"s\",\"endTime\":\"e\",\"servicesRan\":[],\"archive\":null}"); + } + + @Test + void pairedClientDtoWritesNullLastUsedExplicitly() throws Exception { + assertWire("/wire/paired-client", + "{\"id\":\"c-1\",\"name\":\"Living room\",\"createdAt\":\"2026-11-11T18:00:00Z\",\"lastUsedAt\":null,\"current\":true}"); + assertWire("/wire/paired-client-used", + "{\"id\":\"c-1\",\"name\":\"Living room\",\"createdAt\":\"2026-11-11T18:00:00Z\"," + + "\"lastUsedAt\":\"2026-11-11T18:00:00.123Z\",\"current\":false}"); + assertWire("/wire/paired-client-model", + "{\"id\":\"c-1\",\"name\":\"Living room\",\"createdAt\":\"2026-11-11T18:00:00Z\",\"lastUsedAt\":\"2026-11-11T18:00:00.123Z\"}"); + } + + @Test + void pairingDtosKeepTheirShape() throws Exception { + assertWire("/wire/pairing-code", "{\"code\":\"ABCD-EFGH\",\"expiresAt\":\"2026-11-11T18:00:00Z\"}"); + assertWire("/wire/pair-response", "{\"token\":\"tok\",\"id\":\"c-1\",\"name\":\"Living room\"}"); + } + + @Test + void durationsAreWrittenAsIso8601Strings() throws Exception { + assertWire("/wire/public-health", "{\"healthy\":true,\"backupInterval\":\"PT12H\"}"); + assertWire("/wire/server-config", + "{\"backupLocation\":\"/var/lib/mediagarrd/backups\",\"retentionCount\":10,\"backupInterval\":\"PT1H30M\"}"); + assertWire("/wire/server-status", + "{\"healthy\":true,\"running\":false,\"backupRetentionCount\":10,\"backupInterval\":\"PT1H1M1S\"}"); + } + + @Test + void statusDtosKeepTheirShape() throws Exception { + assertWire("/wire/setup-status", "{\"completed\":false,\"authorized\":true}"); + assertWire("/wire/setup-complete", "{\"pairingPin\":\"123456\"}"); + assertWire("/wire/setup-complete-no-pin", "{\"pairingPin\":null}"); + assertWire("/wire/version-status", + "{\"currentVersion\":\"0.1.0\",\"latestVersion\":\"0.2.0\",\"releaseUrl\":\"https://example.invalid/r\"," + + "\"updateAvailable\":true,\"checkState\":\"OK\",\"checkedAt\":\"2026-11-11T18:00:00.123Z\",\"message\":null}"); + assertWire("/wire/version-status-error", + "{\"currentVersion\":\"0.1.0\",\"latestVersion\":null,\"releaseUrl\":null,\"updateAvailable\":false," + + "\"checkState\":\"NO_RELEASES\",\"checkedAt\":\"2026-11-11T18:00:00Z\",\"message\":\"none\"}"); + } + + @Test + void serviceDefinitionKeepsNameAndPaths() throws Exception { + assertWire("/wire/service-definition", "{\"name\":\"plex\",\"paths\":[\"/a\",\"/b\"]}"); + assertEcho("/wire/echo/service-definition", "{\"name\":\"plex\",\"paths\":[\"/a\",\"/b\"]}", + "{\"name\":\"plex\",\"paths\":[\"/a\",\"/b\"]}"); + } + + @Test + void requestDtosReadTheDocumentedBodies() throws Exception { + assertEcho("/wire/echo/config-update", "{\"backupLocation\":\"/data\",\"retentionCount\":3}", + "{\"backupLocation\":\"/data\",\"retentionCount\":3}"); + assertEcho("/wire/echo/config-update", "{}", "{\"backupLocation\":null,\"retentionCount\":null}"); + assertEcho("/wire/echo/pair-request", "{\"pin\":\"123456\",\"name\":\"TV\"}", "{\"pin\":\"123456\",\"name\":\"TV\"}"); + assertEcho("/wire/echo/pair-request", "{\"pin\":\"123456\"}", "{\"pin\":\"123456\",\"name\":null}"); + assertEcho("/wire/echo/setup-session", "{\"pin\":\"123456\"}", "{\"pin\":\"123456\"}"); + } + + @Test + void durationRequestsAcceptIsoStrings() throws Exception { + assertEcho("/wire/echo/schedule-update", "{\"backupInterval\":\"PT6H\"}", "{\"backupInterval\":\"PT6H\"}"); + assertEcho("/wire/echo/schedule-update", "{\"backupInterval\":\"PT90M\"}", "{\"backupInterval\":\"PT1H30M\"}"); + } + + @Test + void unknownPropertiesInRequestsAreIgnored() throws Exception { + assertEcho("/wire/echo/pair-request", "{\"pin\":\"1\",\"name\":\"TV\",\"extra\":true}", "{\"pin\":\"1\",\"name\":\"TV\"}"); + assertEcho("/wire/echo/config-update", "{\"retentionCount\":2,\"unknown\":[1,2]}", + "{\"backupLocation\":null,\"retentionCount\":2}"); + } + + @Test + void malformedBodiesAreRejectedAsBadRequests() throws Exception { + mockMvc.perform(post("/wire/echo/pair-request").contentType(MediaType.APPLICATION_JSON).content("{\"pin\":")) + .andExpect(status().isBadRequest()); + mockMvc.perform(post("/wire/echo/schedule-update").contentType(MediaType.APPLICATION_JSON) + .content("{\"backupInterval\":\"not-a-duration\"}")) + .andExpect(status().isBadRequest()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/FullContextSupport.java b/src/test/java/wellatleastitried/mediagarrdServer/api/FullContextSupport.java new file mode 100644 index 0000000..34d6548 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/FullContextSupport.java @@ -0,0 +1,42 @@ +package wellatleastitried.mediagarrdServer.api; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.util.ReflectionTestUtils; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; +import wellatleastitried.mediagarrdServer.service.SetupService; + +final class FullContextSupport { + + private FullContextSupport() {} + + static Path newDataDir() { + try { + return Files.createTempDirectory("mediagarrd-full-context"); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + static TestDatabase openDatabase(Path dataDir) { + MediaGarrdProperties properties = new MediaGarrdProperties(); + properties.setDatabasePath(dataDir.resolve("mediagarrd.db").toString()); + return new TestDatabase(properties); + } + + static void register(DynamicPropertyRegistry registry, Path dataDir) { + registry.add("mediagarrd.database-path", () -> dataDir.resolve("mediagarrd.db").toString()); + registry.add("mediagarrd.backup-root", () -> dataDir.resolve("backups").toString()); + registry.add("mediagarrd.helper-image", () -> "alpine:3"); + registry.add("mediagarrd.github-api-base-url", () -> "http://127.0.0.1:1"); + } + + static String currentPin(SetupService setup) { + return ReflectionTestUtils.invokeMethod(setup, "currentPin"); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/PairingControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/PairingControllerTest.java new file mode 100644 index 0000000..7a83c8e --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/PairingControllerTest.java @@ -0,0 +1,142 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.hamcrest.Matchers.hasSize; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.delete; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.get; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.post; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import wellatleastitried.mediagarrdServer.dto.PairResponse; +import wellatleastitried.mediagarrdServer.dto.PairingCodeDto; +import wellatleastitried.mediagarrdServer.model.PairedClient; +import wellatleastitried.mediagarrdServer.service.LockedOutException; +import wellatleastitried.mediagarrdServer.service.PairingException; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@WebMvcTest(PairingController.class) +class PairingControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockitoBean + PairingService pairing; + + @MockitoBean + SetupService setup; + + @BeforeEach + void authorize() { + ApiTestAuth.accept(pairing); + } + + @Test + void pairReturnsTheTokenWithoutAnyAuthorization() throws Exception { + when(pairing.pair("123456", "Laptop")).thenReturn(new PairResponse("the-token", "abc", "Laptop")); + + mockMvc.perform(pair("{\"pin\": \"123456\", \"name\": \"Laptop\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.token").value("the-token")) + .andExpect(jsonPath("$.id").value("abc")) + .andExpect(jsonPath("$.name").value("Laptop")); + } + + @Test + void pairMapsRejectionsToStatusesWithErrorBodies() throws Exception { + when(pairing.pair("1", null)).thenThrow(new PairingException(PairingException.Reason.INVALID, "Invalid PIN or pairing code")); + when(pairing.pair("2", null)).thenThrow(new PairingException(PairingException.Reason.CLOSED, "Pairing is closed")); + when(pairing.pair("3", null)).thenThrow(new PairingException(PairingException.Reason.SETUP_INCOMPLETE, "This server has not finished setup yet. Finish it on the server's /config page, then pair.")); + when(pairing.pair("4", null)).thenThrow(new LockedOutException(Duration.ofSeconds(90))); + when(pairing.pair("5", null)).thenThrow(new IllegalArgumentException("Name must be 1 to 64 characters")); + + mockMvc.perform(pair("{\"pin\": \"1\"}")).andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").value("Invalid PIN or pairing code")); + mockMvc.perform(pair("{\"pin\": \"2\"}")).andExpect(status().isForbidden()) + .andExpect(jsonPath("$.error").value("Pairing is closed")); + mockMvc.perform(pair("{\"pin\": \"3\"}")).andExpect(status().isConflict()) + .andExpect(jsonPath("$.error").value("This server has not finished setup yet. Finish it on the server's /config page, then pair.")); + mockMvc.perform(pair("{\"pin\": \"4\"}")).andExpect(status().isTooManyRequests()) + .andExpect(header().string(HttpHeaders.RETRY_AFTER, "90")) + .andExpect(jsonPath("$.error").exists()); + mockMvc.perform(pair("{\"pin\": \"5\"}")).andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").exists()); + } + + @Test + void pairWithAMalformedBodyIsABadRequestInTheErrorShape() throws Exception { + mockMvc.perform(pair("not json")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").exists()); + } + + @Test + void creatingACodeNeedsAToken() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/pairing-codes")).andExpect(status().isUnauthorized()); + when(pairing.createCode()).thenReturn(new PairingCodeDto("ABCDE-FGHJK", Instant.parse("2026-11-19T10:10:00Z"))); + + mockMvc.perform(post("/api/v1/pairing-codes")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.code").value("ABCDE-FGHJK")) + .andExpect(jsonPath("$.expiresAt").exists()); + } + + @Test + void listingMarksTheCallersOwnRecord() throws Exception { + Instant created = Instant.parse("2026-11-19T10:00:00Z"); + when(pairing.list()).thenReturn(List.of(ApiTestAuth.CLIENT, new PairedClient("c2", "Phone", created, created))); + + mockMvc.perform(get("/api/v1/clients")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(2))) + .andExpect(jsonPath("$[0].id").value("c1")) + .andExpect(jsonPath("$[0].current").value(true)) + .andExpect(jsonPath("$[1].current").value(false)) + .andExpect(jsonPath("$[0].token").doesNotExist()) + .andExpect(jsonPath("$[0].tokenHash").doesNotExist()); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/clients")).andExpect(status().isUnauthorized()); + } + + @Test + void revokingARecordAnswers204AndAMissingOneAnswers404() throws Exception { + when(pairing.revoke("c2")).thenReturn(true); + when(pairing.revoke("nope")).thenReturn(false); + + mockMvc.perform(delete("/api/v1/clients/c2")).andExpect(status().isNoContent()); + mockMvc.perform(delete("/api/v1/clients/nope")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Client not found")); + } + + @Test + void revokingNeedsAToken() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/clients/c1")).andExpect(status().isUnauthorized()); + + verify(pairing, never()).revoke(any()); + } + + private static org.springframework.test.web.servlet.RequestBuilder pair(String body) { + return MockMvcRequestBuilders.post("/api/v1/pair").contentType(MediaType.APPLICATION_JSON).content(body); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/RealServletFullContextTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/RealServletFullContextTest.java new file mode 100644 index 0000000..6a69c09 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/RealServletFullContextTest.java @@ -0,0 +1,171 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpRequest.BodyPublishers; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Map; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +import tools.jackson.databind.json.JsonMapper; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +class RealServletFullContextTest { + + private static final Path DATA_DIR = FullContextSupport.newDataDir(); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @BeforeAll + static void seedCompletedSetup() { + FullContextSupport.openDatabase(DATA_DIR).settings.saveSetting("setup_completed", "2026-11-20 10:00:00"); + } + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) { + FullContextSupport.register(registry, DATA_DIR); + } + + @LocalServerPort + int port; + + @Autowired + SetupService setup; + + private final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); + + private URI uri(String path) { + return URI.create("http://localhost:" + port + path); + } + + private HttpResponse send(HttpRequest.Builder request) throws Exception { + return client.send(request.timeout(Duration.ofSeconds(10)).build(), BodyHandlers.ofString()); + } + + private static String pairedToken; + + private synchronized String pair() throws Exception { + if (pairedToken != null) { + return pairedToken; + } + String body = "{\"pin\":\"" + FullContextSupport.currentPin(setup) + "\",\"name\":\"Real servlet\"}"; + HttpResponse response = send(HttpRequest.newBuilder(uri("/api/v1/pair")) + .header("Content-Type", "application/json").POST(BodyPublishers.ofString(body))); + assertEquals(200, response.statusCode(), response.body()); + pairedToken = (String) JSON.readValue(response.body(), Map.class).get("token"); + return pairedToken; + } + + @Test + void aPairedClientCanOpenTheEventStreamAndGetsItsFirstEvent() throws Exception { + String token = pair(); + + HttpResponse response = client.send(HttpRequest.newBuilder(uri("/api/v1/events")) + .header("Authorization", "Bearer " + token).header("Accept", "text/event-stream").GET().build(), BodyHandlers.ofInputStream()); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body(), StandardCharsets.UTF_8))) { + assertEquals(200, response.statusCode()); + assertTrue(response.headers().firstValue("Content-Type").orElse("").startsWith("text/event-stream")); + assertEquals("no-store", response.headers().firstValue("Cache-Control").orElse(null)); + String line = reader.readLine(); + while (line != null && !line.startsWith("event:")) { + line = reader.readLine(); + } + assertEquals("event:state", line); + } + } + + @Test + void theEventStreamRefusesARequestWithoutATokenWithTheErrorShape() throws Exception { + HttpResponse response = send(HttpRequest.newBuilder(uri("/api/v1/events")).GET()); + + assertEquals(401, response.statusCode()); + assertNotNull(JSON.readValue(response.body(), Map.class).get("error")); + } + + @Test + void unknownPathsAndWrongMethodsUseTheErrorShape() throws Exception { + String token = pair(); + + HttpResponse missing = send(HttpRequest.newBuilder(uri("/api/v1/does-not-exist")) + .header("Authorization", "Bearer " + token).GET()); + HttpResponse wrongMethod = send(HttpRequest.newBuilder(uri("/api/v1/backups")) + .header("Authorization", "Bearer " + token).POST(BodyPublishers.noBody())); + HttpResponse staticMissing = send(HttpRequest.newBuilder(uri("/no-such-page.html")).GET()); + + assertEquals(404, missing.statusCode()); + assertEquals(Map.of("error", "Not Found"), JSON.readValue(missing.body(), Map.class)); + assertEquals(405, wrongMethod.statusCode()); + assertEquals(Map.of("error", "Method Not Allowed"), JSON.readValue(wrongMethod.body(), Map.class)); + assertTrue(wrongMethod.headers().firstValue("Allow").isPresent()); + assertEquals(404, staticMissing.statusCode()); + assertEquals(Map.of("error", "Not Found"), JSON.readValue(staticMissing.body(), Map.class)); + } + + @Test + void theErrorDispatchOfTheDisabledSetupPageUsesTheErrorShape() throws Exception { + HttpResponse response = send(HttpRequest.newBuilder(uri("/config")).GET()); + + assertEquals(404, response.statusCode()); + assertEquals(Map.of("error", "Not Found"), JSON.readValue(response.body(), Map.class)); + assertEquals("nosniff", response.headers().firstValue("X-Content-Type-Options").orElse(null)); + } + + @Test + void realResponsesCarryTheSecurityHeaders() throws Exception { + HttpResponse response = send(HttpRequest.newBuilder(uri("/api/v1/health")).GET()); + + assertEquals(200, response.statusCode()); + assertEquals("DENY", response.headers().firstValue("X-Frame-Options").orElse(null)); + assertEquals(SecurityHeadersFilter.CONTENT_SECURITY_POLICY, response.headers().firstValue("Content-Security-Policy").orElse(null)); + assertEquals("nosniff", response.headers().firstValue("X-Content-Type-Options").orElse(null)); + assertEquals("no-referrer", response.headers().firstValue("Referrer-Policy").orElse(null)); + assertEquals("no-store", response.headers().firstValue("Cache-Control").orElse(null)); + } + + @Test + void aChunkedBodyOverTheCapIsRefusedAndASmallOneIsNot() throws Exception { + byte[] big = ("{\"pin\":\"" + "1".repeat(RequestBodyLimitFilter.MAX_BODY_BYTES + 10) + "\"}").getBytes(StandardCharsets.UTF_8); + + HttpResponse refused = send(HttpRequest.newBuilder(uri("/api/v1/pair")) + .header("Content-Type", "application/json") + .POST(BodyPublishers.fromPublisher(BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(big))))); + HttpResponse accepted = send(HttpRequest.newBuilder(uri("/api/v1/pair")) + .header("Content-Type", "application/json") + .POST(BodyPublishers.fromPublisher(BodyPublishers.ofInputStream( + () -> new ByteArrayInputStream("{\"pin\":\"000000\"}".getBytes(StandardCharsets.UTF_8)))))); + + assertEquals(413, refused.statusCode()); + assertEquals(Map.of("error", RequestBodyLimitFilter.MESSAGE), JSON.readValue(refused.body(), Map.class)); + assertTrue(accepted.statusCode() != 413, accepted.body()); + } + + @Test + void anUnknownCharsetInTheContentTypeIsRefusedWith415AndTheErrorShape() throws Exception { + HttpResponse response = send(HttpRequest.newBuilder(uri("/api/v1/pair")) + .header("Content-Type", "application/json; charset=nope-8") + .POST(BodyPublishers.ofString("{\"pin\":\"000000\"}"))); + + assertEquals(415, response.statusCode(), response.body()); + assertTrue(JSON.readValue(response.body(), Map.class).containsKey("error"), response.body()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/RequestBodyLimitFilterTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/RequestBodyLimitFilterTest.java new file mode 100644 index 0000000..9749e59 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/RequestBodyLimitFilterTest.java @@ -0,0 +1,65 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import jakarta.servlet.http.HttpServletRequest; +import tools.jackson.databind.json.JsonMapper; + +class RequestBodyLimitFilterTest { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final RequestBodyLimitFilter filter = new RequestBodyLimitFilter(); + + private MockHttpServletRequest post(String characterEncoding) { + MockHttpServletRequest request = new MockHttpServletRequest("POST", "/api/v1/pair"); + request.setContentType("application/json"); + request.setCharacterEncoding(characterEncoding); + request.setContent("{\"pin\":\"000000\"}".getBytes(StandardCharsets.UTF_8)); + return request; + } + + @Test + void anUnknownCharsetAnswers400WithTheErrorShapeAndNeverReachesTheController() throws Exception { + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain chain = new MockFilterChain(); + + filter.doFilter(post("nope-8"), response, chain); + + assertEquals(400, response.getStatus()); + assertEquals(Map.of("error", RequestBodyLimitFilter.UNSUPPORTED_CHARSET_MESSAGE), JSON.readValue(response.getContentAsString(), Map.class)); + assertNull(chain.getRequest()); + } + + @Test + void anIllegalCharsetNameAnswers400() throws Exception { + MockHttpServletResponse response = new MockHttpServletResponse(); + + filter.doFilter(post("bad name!"), response, new MockFilterChain()); + + assertEquals(400, response.getStatus()); + } + + @Test + void aKnownCharsetIsReadWithThatCharset() throws Exception { + MockHttpServletResponse response = new MockHttpServletResponse(); + AtomicReference body = new AtomicReference<>(); + + filter.doFilter(post("ISO-8859-1"), response, (request, servletResponse) -> { + body.set(((HttpServletRequest) request).getReader().readLine()); + }); + + assertEquals(200, response.getStatus()); + assertEquals("{\"pin\":\"000000\"}", body.get()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java new file mode 100644 index 0000000..9ce661f --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java @@ -0,0 +1,103 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import jakarta.servlet.http.Cookie; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@Timeout(30) +@WebMvcTest(RunEventsController.class) +class RunEventsControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockitoBean + RunStatusBroadcaster broadcaster; + + @MockitoBean + SetupService setup; + + @MockitoBean + PairingService pairing; + + @BeforeEach + void authorize() { + ApiTestAuth.accept(pairing); + } + + @Test + void streamsEventsWithATokenWhetherOrNotSetupIsComplete() throws Exception { + when(broadcaster.subscribe("c1")).thenReturn(new SseEmitter(60_000L)); + + for (boolean completed : new boolean[] {false, true}) { + when(setup.isCompleted()).thenReturn(completed); + + mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(request().asyncStarted()) + .andExpect(status().isOk()); + } + } + + @Test + void refusesEventsWithoutATokenOrWithASetupSession() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(status().isUnauthorized()); + + when(setup.canConfigure("session")).thenReturn(true); + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM) + .cookie(new Cookie(SetupInterceptor.SESSION_COOKIE, "session"))) + .andExpect(status().isUnauthorized()); + + verifyNoInteractions(broadcaster); + } + + @Test + void aClientRevokedWhileSubscribingIsClosedAndRefused() throws Exception { + when(broadcaster.subscribe("c1")).thenReturn(new SseEmitter(60_000L)); + when(pairing.isPaired("c1")).thenReturn(false); + + mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(status().isUnauthorized()); + + verify(broadcaster).closeClient("c1"); + } + + @Test + void answers503WhenTooManySubscribers() throws Exception { + when(broadcaster.subscribe("c1")).thenThrow(new RunStatusBroadcaster.SubscriberLimitException("full")); + + mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(status().isServiceUnavailable()); + } + + @Test + void aTimedOutStreamEndsQuietlyWithoutAnErrorPage() throws Exception { + when(broadcaster.subscribe("c1")).thenThrow(new org.springframework.web.context.request.async.AsyncRequestTimeoutException()); + + var result = mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(status().isOk()) + .andReturn(); + + assertEquals("", result.getResponse().getContentAsString()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ScheduleIntervalApiTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ScheduleIntervalApiTest.java new file mode 100644 index 0000000..5a862af --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ScheduleIntervalApiTest.java @@ -0,0 +1,117 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.put; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.BACKUP_INTERVAL_SETTING; + +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; +import wellatleastitried.mediagarrdServer.service.BackupArchiveService; +import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.service.BackupScheduleService; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@WebMvcTest(BackupController.class) +class ScheduleIntervalApiTest { + + private static final String MESSAGE = "Backup interval must be between 15 minutes and 365 days"; + + @Autowired + MockMvc mockMvc; + + @MockitoBean + BackupArchiveService archiveService; + + @MockitoBean + BackupOrchestratorService orchestratorService; + + @MockitoBean + RunStatusBroadcaster broadcaster; + + @MockitoBean + SetupService setup; + + @MockitoBean + PairingService pairing; + + @TempDir + Path tempDir; + + private TestDatabase db; + private BackupScheduleService schedule; + + @BeforeEach + void setUp() { + ApiTestAuth.accept(pairing); + MediaGarrdProperties properties = new MediaGarrdProperties(); + properties.setDatabasePath(tempDir.resolve("mediagarrd.db").toString()); + db = new TestDatabase(properties); + schedule = new BackupScheduleService(properties, db.settings, db.backups, setup); + when(orchestratorService.updateInterval(any())).thenAnswer(invocation -> schedule.updateInterval(invocation.getArgument(0))); + when(orchestratorService.getInterval()).thenAnswer(invocation -> schedule.getInterval()); + } + + private org.springframework.test.web.servlet.ResultActions putSchedule(String body) throws Exception { + return mockMvc.perform(put("/api/v1/schedule").contentType(MediaType.APPLICATION_JSON).content(body)); + } + + @Test + void rejectedIntervalsAnswer400AndSaveNothing() throws Exception { + putSchedule("{\"backupInterval\": \"PT2H\"}").andExpect(status().isOk()); + Duration before = schedule.getInterval(); + + List bodies = List.of( + "{}", + "{\"backupInterval\": null}", + "{\"backupInterval\": \"PT0S\"}", + "{\"backupInterval\": \"-PT5M\"}", + "{\"backupInterval\": \"PT14M59S\"}", + "{\"backupInterval\": \"PT1S\"}", + "{\"backupInterval\": \"P365DT1S\"}", + "{\"backupInterval\": \"PT600000000000000M\"}", + "{\"backupInterval\": 0}", + "{\"backupInterval\": -60}", + "{\"backupInterval\": 899}", + "{\"backupInterval\": 31536001}", + "{\"backupInterval\": 36000000000000}"); + for (String body : bodies) { + putSchedule(body) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value(MESSAGE)); + } + + assertEquals(before, schedule.getInterval()); + assertEquals(before.toString(), db.settings.fetchSetting(BACKUP_INTERVAL_SETTING).orElseThrow()); + } + + @Test + void boundaryIntervalsAreAccepted() throws Exception { + putSchedule("{\"backupInterval\": \"PT15M\"}").andExpect(status().isOk()); + assertEquals(Duration.ofMinutes(15), schedule.getInterval()); + putSchedule("{\"backupInterval\": \"P365D\"}").andExpect(status().isOk()); + assertEquals(Duration.ofDays(365), schedule.getInterval()); + putSchedule("{\"backupInterval\": 900}").andExpect(status().isOk()); + assertEquals(Duration.ofMinutes(15), schedule.getInterval()); + putSchedule("{\"backupInterval\": 31536000}").andExpect(status().isOk()); + assertEquals(Duration.ofDays(365), schedule.getInterval()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/SetupControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/SetupControllerTest.java new file mode 100644 index 0000000..3ea26bf --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/SetupControllerTest.java @@ -0,0 +1,212 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.hamcrest.Matchers.containsString; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.get; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.Duration; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.RequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import jakarta.servlet.http.Cookie; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; +import wellatleastitried.mediagarrdServer.service.LockedOutException; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupAlreadyCompleteException; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@WebMvcTest(SetupController.class) +class SetupControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockitoBean + SetupService setup; + + @MockitoBean + PairingService pairing; + + @MockitoBean + ServiceRepository services; + + @BeforeEach + void authorize() { + ApiTestAuth.accept(pairing); + } + + @Test + void reportsStatusForTheCallersSession() throws Exception { + when(setup.canConfigure("token")).thenReturn(true); + + mockMvc.perform(get("/api/v1/setup").cookie(new Cookie(SetupInterceptor.SESSION_COOKIE, "token"))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.completed").value(false)) + .andExpect(jsonPath("$.authorized").value(true)); + + mockMvc.perform(get("/api/v1/setup")) + .andExpect(jsonPath("$.authorized").value(false)); + } + + @Test + void correctPinSetsHttpOnlySessionCookie() throws Exception { + when(setup.startSession("123456")).thenReturn(Optional.of("token")); + + mockMvc.perform(pin("123456")) + .andExpect(status().isNoContent()) + .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString(SetupInterceptor.SESSION_COOKIE + "=token"))) + .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString("HttpOnly"))) + .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString("SameSite=Strict"))); + } + + @Test + void wrongPinIsUnauthorized() throws Exception { + when(setup.startSession("000000")).thenReturn(Optional.empty()); + + mockMvc.perform(pin("000000")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error").exists()) + .andExpect(header().doesNotExist(HttpHeaders.SET_COOKIE)); + } + + @Test + void pinIsGoneAfterSetupCompletes() throws Exception { + when(setup.isCompleted()).thenReturn(true); + + mockMvc.perform(pin("123456")).andExpect(status().isGone()); + + verify(setup, never()).startSession(any()); + } + + @Test + void lockedPinAnswers429WithRetryAfter() throws Exception { + when(setup.startSession("000000")).thenThrow(new LockedOutException(Duration.ofMinutes(7))); + + mockMvc.perform(pin("000000")) + .andExpect(status().isTooManyRequests()) + .andExpect(header().string(HttpHeaders.RETRY_AFTER, "420")) + .andExpect(jsonPath("$.error").exists()); + } + + @Test + void completeRequiresSession() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/setup/complete")).andExpect(status().isUnauthorized()); + + verify(setup, never()).complete(); + } + + @Test + void completeRequiresAtLeastOneService() throws Exception { + when(setup.canConfigure(any())).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of()); + + mockMvc.perform(post("/api/v1/setup/complete")) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error").value("Add at least one service before finishing setup")); + + verify(setup, never()).complete(); + } + + @Test + void completeFinishesSetupAndClearsCookie() throws Exception { + when(setup.canConfigure(any())).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(new ServiceDefinition("radarr", List.of("/srv/radarr")))); + when(setup.complete()).thenReturn("123456"); + + mockMvc.perform(post("/api/v1/setup/complete")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.pairingPin").value("123456")) + .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString("Max-Age=0"))) + .andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-store")); + + verify(setup).complete(); + } + + @Test + void completeAnswersAnExplicitNullPinWhenNoPinApplies() throws Exception { + when(setup.canConfigure(any())).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(new ServiceDefinition("radarr", List.of("/srv/radarr")))); + when(setup.complete()).thenReturn(null); + + mockMvc.perform(post("/api/v1/setup/complete")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"pairingPin\":null}", true)); + } + + @Test + void completeIsGoneWhenARacingRequestCompletedFirst() throws Exception { + when(setup.canConfigure(any())).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(new ServiceDefinition("radarr", List.of("/srv/radarr")))); + when(setup.complete()).thenThrow(new SetupAlreadyCompleteException()); + + mockMvc.perform(post("/api/v1/setup/complete")).andExpect(status().isGone()); + } + + @Test + void completeIsAGenericServerErrorWhenSavingFails() throws Exception { + when(setup.canConfigure(any())).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(new ServiceDefinition("radarr", List.of("/srv/radarr")))); + when(setup.complete()).thenThrow(new IllegalStateException("Failed to save setting")); + + mockMvc.perform(post("/api/v1/setup/complete")) + .andExpect(status().isInternalServerError()) + .andExpect(jsonPath("$.error").value("Internal error")); + } + + @Test + void completeIsGoneWhenAlreadyCompleted() throws Exception { + when(setup.isCompleted()).thenReturn(true); + when(setup.canConfigure(any())).thenReturn(true); + + mockMvc.perform(post("/api/v1/setup/complete")).andExpect(status().isGone()); + + verify(setup, never()).complete(); + } + + @Test + void setupPageIsServedOnlyUntilSetupCompletes() throws Exception { + mockMvc.perform(get("/config")).andExpect(status().isOk()); + + when(setup.isCompleted()).thenReturn(true); + + mockMvc.perform(get("/config")).andExpect(status().isNotFound()); + mockMvc.perform(get("/config.html")).andExpect(status().isNotFound()); + mockMvc.perform(get("/js/config.js")).andExpect(status().isNotFound()); + } + + private static org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder pin(String pin) { + return post("/api/v1/setup/session").contentType(MediaType.APPLICATION_JSON).content("{\"pin\": \"" + pin + "\"}"); + } + + @Test + void theSessionCookieIsSecureOnlyOverHttps() throws Exception { + when(setup.startSession("123456")).thenReturn(Optional.of("token")); + + mockMvc.perform(pin("123456")) + .andExpect(header().string(HttpHeaders.SET_COOKIE, org.hamcrest.Matchers.not(containsString("Secure")))); + mockMvc.perform(pin("123456").header("X-Forwarded-Proto", "https")) + .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString("Secure"))); + mockMvc.perform(pin("123456").secure(true)) + .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString("Secure"))); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/SetupPageAssetsTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/SetupPageAssetsTest.java new file mode 100644 index 0000000..506f644 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/SetupPageAssetsTest.java @@ -0,0 +1,166 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; + +class SetupPageAssetsTest { + + private static final Path STATIC = Path.of("src/main/resources/static"); + + private static String read(String name) throws IOException { + return Files.readString(STATIC.resolve(name)); + } + + @Test + void thePagesNeedNoInlineScriptOrStyleSoTheCspHolds() throws IOException { + for (String page : new String[] {"config.html", "index.html"}) { + String html = read(page); + assertFalse(Pattern.compile("]*\\bsrc=)").matcher(html).find(), page + " has an inline script"); + assertFalse(html.contains(" scripts = Files.walk(STATIC.resolve("js"))) { + for (Path script : scripts.filter(path -> path.toString().endsWith(".js")).toList()) { + String code = Files.readString(script); + for (String forbidden : new String[] {"innerHTML", "insertAdjacentHTML", "eval(", "cssText", "setAttribute('style'"}) { + assertFalse(code.contains(forbidden), script + " uses " + forbidden); + } + } + } + } + + @Test + void aFailedUnlockKeepsTheWorkspaceHiddenAndShowsTheError() throws IOException { + String config = read("js/config.js"); + + assertTrue(config.contains("workspace.hidden = true;")); + assertTrue(read("config.html").contains("id=\"fatal\" role=\"alert\"")); + } + + @Test + void thePinFormIsAccessibleAndRefocusedAfterAMistake() throws IOException { + String html = read("config.html"); + String setup = read("js/setup.js"); + + assertTrue(html.contains("aria-describedby=\"pinError\"")); + assertTrue(html.contains("id=\"pinError\" data-error role=\"alert\" aria-live=\"polite\"")); + assertTrue(setup.contains("form.elements.pin.focus()")); + } + + @Test + void theFinishButtonIsFoundByItsOwnAttribute() throws IOException { + assertTrue(read("config.html").contains("data-finish")); + assertTrue(read("js/setup.js").contains("querySelector('[data-finish]')")); + } + + @Test + void theFinishReplyShowsThePairingPinWithACopyButtonAndNeverStoresIt() throws IOException { + String html = read("config.html"); + String setup = read("js/setup.js"); + String config = read("js/config.js"); + + assertTrue(html.contains("id=\"pairingResult\" hidden")); + assertTrue(html.contains("data-copy-pin")); + assertTrue(html.contains("data-without-pin")); + assertTrue(html.indexOf("id=\"pairingResult\"") < html.indexOf("
")); + assertTrue(setup.contains("code.textContent = pairingPin;")); + assertTrue(setup.contains("result.pairingPin")); + assertFalse(setup.contains("localStorage") || setup.contains("sessionStorage") || setup.contains("location.")); + assertTrue(config.contains("document.getElementById('pairingResult')")); + assertTrue(read("css/mediagarrd.css").contains(".pin-row { display: flex; flex-wrap: wrap;")); + } + + @Test + void aRateLimitedUnlockShowsTheWaitFromRetryAfter() throws IOException { + assertTrue(read("js/api.js").contains("Retry-After")); + assertTrue(read("js/setup.js").contains("e.retryAfter")); + } + + @Test + void aPartiallySavedSettingsFormIsRefreshedAndExplained() throws IOException { + String settings = read("js/settings.js"); + + assertTrue(settings.contains("were saved, but the interval was not")); + assertTrue(settings.contains("api.getConfig().then(show)")); + } + + @Test + void theServiceFormAndTableAreLabelled() throws IOException { + String html = read("config.html"); + + assertTrue(html.contains("Host paths to back up")); + assertTrue(html.contains("aria-label=\"Host path\"")); + assertTrue(html.contains("aria-label=\"Remove path\"")); + assertTrue(html.contains("")); + assertEquals(3, html.split("]*>[^<]*

\\s*
* { min-width: 0; }")); + assertTrue(css.contains(".button-row { display: flex; flex-wrap: wrap;")); + assertTrue(css.contains(".input-row { display: grid; grid-template-columns: minmax(0, 1fr) auto;")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java new file mode 100644 index 0000000..2e2d718 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java @@ -0,0 +1,54 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.Instant; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +import wellatleastitried.mediagarrdServer.dto.CheckState; +import wellatleastitried.mediagarrdServer.dto.VersionStatusDto; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.SetupService; +import wellatleastitried.mediagarrdServer.service.UpdateCheckService; + +@WebMvcTest(VersionController.class) +class VersionControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockitoBean + UpdateCheckService updateCheckService; + + @MockitoBean + SetupService setup; + + @MockitoBean + PairingService pairing; + + @Test + void reportsTheVersionStatusWithoutATokenOrSetupSession() throws Exception { + when(setup.isCompleted()).thenReturn(false); + when(updateCheckService.status()).thenReturn(new VersionStatusDto( + "0.1.0", "0.2.0", "https://github.com/MediaGarrd/Server/releases/tag/v0.2.0", true, + CheckState.OK, Instant.parse("2026-11-11T18:00:00Z"), null)); + + mockMvc.perform(get("/api/v1/version")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.currentVersion").value("0.1.0")) + .andExpect(jsonPath("$.latestVersion").value("0.2.0")) + .andExpect(jsonPath("$.releaseUrl").value("https://github.com/MediaGarrd/Server/releases/tag/v0.2.0")) + .andExpect(jsonPath("$.updateAvailable").value(true)) + .andExpect(jsonPath("$.checkState").value("OK")) + .andExpect(jsonPath("$.checkedAt").value("2026-11-11T18:00:00Z")) + .andExpect(jsonPath("$.message").doesNotExist()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/WebhookControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/WebhookControllerTest.java new file mode 100644 index 0000000..99f5bde --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/WebhookControllerTest.java @@ -0,0 +1,217 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.get; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.post; +import static wellatleastitried.mediagarrdServer.api.ApiTestAuth.put; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.FAILURE_WEBHOOK_SETTING; + +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import jakarta.servlet.http.Cookie; +import wellatleastitried.mediagarrdServer.repository.SettingsRepository; +import wellatleastitried.mediagarrdServer.service.PairingService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.SetupService; +import wellatleastitried.mediagarrdServer.service.WebhookService; + +@WebMvcTest(WebhookController.class) +@Import(WebhookService.class) +class WebhookControllerTest { + + private static final String SECRET_URL = "https://discord.com/api/webhooks/123456/SECRETTOKEN123"; + + @Autowired + MockMvc mockMvc; + + @MockitoBean + SettingsRepository settings; + + @MockitoBean + RunStatusBroadcaster broadcaster; + + @MockitoBean + SetupService setup; + + @MockitoBean + PairingService pairing; + + private final ListAppender logs = new ListAppender<>(); + private final Logger rootLogger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + + @BeforeEach + void setUp() { + ApiTestAuth.accept(pairing); + logs.start(); + rootLogger.addAppender(logs); + } + + @AfterEach + void tearDown() { + rootLogger.detachAppender(logs); + } + + @Test + void reportsNotConfiguredByDefault() throws Exception { + when(settings.fetchSetting(FAILURE_WEBHOOK_SETTING)).thenReturn(Optional.empty()); + + mockMvc.perform(get("/api/v1/notifications/webhook")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"configured\":false,\"target\":null}", true)); + } + + @Test + void theGetMasksTheUrlDownToSchemeAndHost() throws Exception { + when(settings.fetchSetting(FAILURE_WEBHOOK_SETTING)).thenReturn(Optional.of(SECRET_URL)); + + MvcResult result = mockMvc.perform(get("/api/v1/notifications/webhook")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"configured\":true,\"target\":\"https://discord.com\"}", true)) + .andReturn(); + + String body = result.getResponse().getContentAsString(); + assertFalse(body.contains("SECRETTOKEN123") || body.contains("webhooks")); + } + + @Test + void thePutSavesTheUrlAndAnswersWithTheMaskedStatus() throws Exception { + when(settings.fetchSetting(FAILURE_WEBHOOK_SETTING)).thenReturn(Optional.of(SECRET_URL)); + + MvcResult result = mockMvc.perform(json(put("/api/v1/notifications/webhook"), "{\"url\": \"" + SECRET_URL + "\"}")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"configured\":true,\"target\":\"https://discord.com\"}", true)) + .andReturn(); + + verify(settings).saveSetting(FAILURE_WEBHOOK_SETTING, SECRET_URL); + verify(broadcaster).publishConfigChanged(); + assertFalse(result.getResponse().getContentAsString().contains("SECRETTOKEN123")); + assertFalse(logText().contains("SECRETTOKEN123")); + } + + @Test + void thePutClearsWithAnEmptyStringOrNull() throws Exception { + when(settings.fetchSetting(FAILURE_WEBHOOK_SETTING)).thenReturn(Optional.of("")); + + mockMvc.perform(json(put("/api/v1/notifications/webhook"), "{\"url\": \"\"}")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"configured\":false,\"target\":null}", true)); + mockMvc.perform(json(put("/api/v1/notifications/webhook"), "{\"url\": null}")) + .andExpect(status().isOk()); + mockMvc.perform(json(put("/api/v1/notifications/webhook"), "{}")) + .andExpect(status().isOk()); + + verify(settings, org.mockito.Mockito.times(3)).saveSetting(FAILURE_WEBHOOK_SETTING, ""); + } + + @Test + void aBadUrlIsA400WithAFixedMessageThatNeverEchoesTheInput() throws Exception { + String body = "{\"url\": \"https://discord.com/api/webhooks/123/SECRETTOKEN123|\"}"; + + MvcResult result = mockMvc.perform(json(put("/api/v1/notifications/webhook"), body)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Webhook URL is not a valid URL")) + .andReturn(); + + verify(settings, never()).saveSetting(anyString(), anyString()); + verify(broadcaster, never()).publishConfigChanged(); + assertFalse(result.getResponse().getContentAsString().contains("SECRETTOKEN123")); + assertFalse(logText().contains("SECRETTOKEN123")); + } + + @Test + void userInfoAndWrongSchemesAreRejected() throws Exception { + mockMvc.perform(json(put("/api/v1/notifications/webhook"), "{\"url\": \"https://user:pw@example.com/x\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Webhook URL must not contain user info")); + mockMvc.perform(json(put("/api/v1/notifications/webhook"), "{\"url\": \"file:///etc/passwd\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Webhook URL must use http or https")); + mockMvc.perform(json(put("/api/v1/notifications/webhook"), "{\"url\": 5}")) + .andExpect(status().isBadRequest()); + } + + @Test + void aTestWithoutAWebhookIsA400() throws Exception { + when(settings.fetchSetting(FAILURE_WEBHOOK_SETTING)).thenReturn(Optional.empty()); + + mockMvc.perform(post("/api/v1/notifications/webhook/test")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("No webhook is configured")); + } + + @Test + void aTestAnswersWithTheDeliveryResultAndThenThe429Cooldown() throws Exception { + when(settings.fetchSetting(FAILURE_WEBHOOK_SETTING)).thenReturn(Optional.of("http://127.0.0.1:1/hook")); + + mockMvc.perform(post("/api/v1/notifications/webhook/test")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"delivered\":false,\"status\":null,\"error\":\"Could not connect\"}", true)); + + mockMvc.perform(post("/api/v1/notifications/webhook/test")) + .andExpect(status().isTooManyRequests()) + .andExpect(header().exists(HttpHeaders.RETRY_AFTER)) + .andExpect(jsonPath("$.error").value(org.hamcrest.Matchers.startsWith("Wait "))); + } + + @Test + void theEndpointsNeedATokenOrASetupSession() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/notifications/webhook")).andExpect(status().isUnauthorized()); + mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/notifications/webhook").contentType(MediaType.APPLICATION_JSON).content("{}")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/notifications/webhook/test")).andExpect(status().isUnauthorized()); + + verify(settings, never()).saveSetting(anyString(), anyString()); + } + + @Test + void aSetupSessionIsEnoughBeforeSetupCompletesAndIgnoredAfter() throws Exception { + when(setup.canConfigure("session")).thenReturn(true); + when(settings.fetchSetting(eq(FAILURE_WEBHOOK_SETTING))).thenReturn(Optional.empty()); + + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/notifications/webhook").cookie(new Cookie(SetupInterceptor.SESSION_COOKIE, "session"))) + .andExpect(status().isOk()); + + when(setup.isCompleted()).thenReturn(true); + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/notifications/webhook").cookie(new Cookie(SetupInterceptor.SESSION_COOKIE, "session"))) + .andExpect(status().isUnauthorized()); + } + + private String logText() { + StringBuilder text = new StringBuilder(); + for (ILoggingEvent event : logs.list) { + text.append(event.getFormattedMessage()).append('\n'); + } + return text.toString(); + } + + private static MockHttpServletRequestBuilder json(MockHttpServletRequestBuilder request, String body) { + return request.contentType(MediaType.APPLICATION_JSON).content(body); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/model/BackupArchiveTest.java b/src/test/java/wellatleastitried/mediagarrdServer/model/BackupArchiveTest.java new file mode 100644 index 0000000..b98caa6 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/model/BackupArchiveTest.java @@ -0,0 +1,41 @@ +package wellatleastitried.mediagarrdServer.model; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class BackupArchiveTest { + + @TempDir + Path tempDir; + + @Test + void checksumIsFullLengthSha256Hex() throws Exception { + Path file = Files.writeString(tempDir.resolve("a.zip"), "abc"); + + assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", archive(file).generateChecksum()); + } + + @Test + void checksumKeepsLeadingZeros() throws Exception { + Path file = Files.writeString(tempDir.resolve("b.zip"), "message digest 179"); + + String checksum = archive(file).generateChecksum(); + + assertEquals(64, checksum.length()); + } + + @Test + void missingFileHasEmptyChecksum() { + assertEquals("", archive(tempDir.resolve("missing.zip")).generateChecksum()); + } + + private static BackupArchive archive(Path path) { + return new BackupArchive("id", path.getFileName().toString(), path, 0, Instant.EPOCH); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/model/ServiceDefinitionTest.java b/src/test/java/wellatleastitried/mediagarrdServer/model/ServiceDefinitionTest.java new file mode 100644 index 0000000..ca67ba3 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/model/ServiceDefinitionTest.java @@ -0,0 +1,67 @@ +package wellatleastitried.mediagarrdServer.model; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +class ServiceDefinitionTest { + + @Test + void normalizesNameAndPaths() { + ServiceDefinition service = new ServiceDefinition(" radarr ", + Arrays.asList(" /srv/radarr/config/ ", null, "", "/srv/radarr/./data", "/srv/radarr/config")); + + assertEquals("radarr", service.name()); + assertEquals(List.of("/srv/radarr/config", "/srv/radarr/data"), service.paths()); + } + + @Test + void treatsMissingFieldsAsEmpty() { + ServiceDefinition service = new ServiceDefinition(null, null); + + assertEquals("", service.name()); + assertEquals(List.of(), service.paths()); + } + + @ParameterizedTest + @ValueSource(strings = {"radarr", "Radarr-4K", "qbit.torrent", "a", "service_2"}) + void acceptsValidNames(String name) { + assertDoesNotThrow(() -> new ServiceDefinition(name, List.of("/srv/data")).validate()); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {"../etc", "-radarr", ".hidden", "has space", "a/b", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}) + void rejectsInvalidNames(String name) { + assertThrows(IllegalArgumentException.class, () -> new ServiceDefinition(name, List.of("/srv/data")).validate()); + } + + @ParameterizedTest + @ValueSource(strings = {"relative/path", "/", "/..", "/srv/bad\npath"}) + void rejectsInvalidPaths(String path) { + assertThrows(IllegalArgumentException.class, () -> new ServiceDefinition("radarr", List.of(path)).validate()); + } + + @Test + void requiresAtLeastOnePath() { + assertThrows(IllegalArgumentException.class, () -> new ServiceDefinition("radarr", List.of(" ")).validate()); + } + + @Test + void limitsThePathCountAndPathLength() { + java.util.List many = java.util.stream.IntStream.range(0, ServiceDefinition.MAX_PATHS + 1).mapToObj(i -> "/p" + i).toList(); + org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> new ServiceDefinition("svc", many).validate()); + String longPath = "/" + "a".repeat(ServiceDefinition.MAX_PATH_LENGTH); + org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, + () -> new ServiceDefinition("svc", java.util.List.of(longPath)).validate()); + new ServiceDefinition("svc", java.util.stream.IntStream.range(0, ServiceDefinition.MAX_PATHS).mapToObj(i -> "/p" + i).toList()).validate(); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/repository/BackupRecordRepositoryTest.java b/src/test/java/wellatleastitried/mediagarrdServer/repository/BackupRecordRepositoryTest.java new file mode 100644 index 0000000..455c603 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/repository/BackupRecordRepositoryTest.java @@ -0,0 +1,96 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.nio.file.Path; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; +import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; + +class BackupRecordRepositoryTest extends DatabaseTestBase { + + @Test + void storesBackupRecordWithEveryServiceResult() { + db.backups.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00", + serviceResult("jellyfin", COMPLETED, null), + serviceResult("sonarr", PARTIAL, "one path failed"), + serviceResult("qbittorrent", FAILED, "no paths copied"))); + + FetchedBackupRecord record = db.backups.fetchBackupById("run-1").orElseThrow(); + + assertEquals("run-1", record.archiveId()); + assertEquals("2026-01-01 00:00:00", record.startTime()); + assertEquals(COMPLETED, record.status()); + assertEquals(Path.of("run-1.zip").toString(), record.filePath()); + assertEquals( + Set.of( + new FetchedBackupServiceRecord("jellyfin", COMPLETED, "2026-01-01 00:00:00", "2026-01-01 00:00:01", null), + new FetchedBackupServiceRecord("sonarr", PARTIAL, "2026-01-01 00:00:00", "2026-01-01 00:00:01", "one path failed"), + new FetchedBackupServiceRecord("qbittorrent", FAILED, "2026-01-01 00:00:00", "2026-01-01 00:00:01", "no paths copied")), + Set.copyOf(record.fetchedServices())); + } + + @Test + void storesFailedRunWithoutArchive() { + db.backups.addNewBackupRecord(new BackupRunResult("failed-1", "2026-01-01 00:00:00", "2026-01-01 00:00:01", FAILED, + List.of(serviceResult("radarr", FAILED, "boom")), null, "radarr: boom")); + + FetchedBackupRecord record = db.backups.fetchBackupById("failed-1").orElseThrow(); + + assertEquals(FAILED, record.status()); + assertNull(record.filePath()); + assertEquals("radarr: boom", record.errorMessage()); + assertEquals(1, record.fetchedServices().size()); + } + + @Test + void fetchesLatestBackupRecordByStartTime() { + db.backups.addNewBackupRecord(backupRun("older", "2026-01-01 00:00:00")); + db.backups.addNewBackupRecord(backupRun("newer", "2026-02-01 00:00:00")); + + assertEquals("newer", db.backups.fetchLatestBackupRecord().orElseThrow().archiveId()); + } + + @Test + void returnsEmptyForMissingBackupRecords() { + assertTrue(db.backups.fetchBackupById("missing").isEmpty()); + assertTrue(db.backups.fetchLatestBackupRecord().isEmpty()); + } + + @Test + void deletingBackupRecordCascadesToServiceRows() throws Exception { + db.backups.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00", serviceResult("radarr", COMPLETED, null))); + assertEquals(1, count("backup_services")); + + db.backups.deleteBackupRecordById("run-1"); + + assertEquals(0, count("backup_services")); + assertTrue(db.backups.fetchBackupById("run-1").isEmpty()); + } + + @Test + void lastSuccessfulStartTimeIgnoresFailedRunsAndCountsPartialOnes() { + assertTrue(db.backups.fetchLastSuccessfulStartTime().isEmpty()); + + db.backups.addNewBackupRecord(backupRun("good", "2026-01-01 00:00:00")); + db.backups.addNewBackupRecord(new BackupRunResult("failed-1", "2026-03-01 00:00:00", "2026-03-01 00:00:01", FAILED, + List.of(), null, "boom")); + assertEquals(java.time.LocalDateTime.of(2026, 1, 1, 0, 0).atZone(java.time.ZoneId.systemDefault()).toInstant(), + db.backups.fetchLastSuccessfulStartTime().orElseThrow()); + + db.backups.addNewBackupRecord(new BackupRunResult("partial-1", "2026-02-01 00:00:00", "2026-02-01 00:00:01", PARTIAL, + List.of(), null, null)); + assertEquals(java.time.LocalDateTime.of(2026, 2, 1, 0, 0).atZone(java.time.ZoneId.systemDefault()).toInstant(), + db.backups.fetchLastSuccessfulStartTime().orElseThrow()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/repository/DatabaseTestBase.java b/src/test/java/wellatleastitried/mediagarrdServer/repository/DatabaseTestBase.java new file mode 100644 index 0000000..e43157a --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/repository/DatabaseTestBase.java @@ -0,0 +1,75 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; + +abstract class DatabaseTestBase { + + @TempDir + Path tempDir; + + MediaGarrdProperties properties; + TestDatabase db; + + @BeforeEach + void setUp() { + properties = new MediaGarrdProperties(); + properties.setDatabasePath(tempDir.resolve("nested/mediagarrd.db").toString()); + db = new TestDatabase(properties); + } + + Path databaseFile() { + return Path.of(properties.getDatabasePath()); + } + + List quarantinedContents() throws IOException { + try (var files = Files.list(databaseFile().getParent())) { + return files + .filter(file -> file.getFileName().toString().startsWith("mediagarrd.db.corrupt-")) + .map(file -> { + try { + return Files.readString(file); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }) + .toList(); + } + } + + Connection rawConnection() throws SQLException { + return DriverManager.getConnection("jdbc:sqlite:" + properties.getDatabasePath()); + } + + int count(String table) throws SQLException { + try (var connection = rawConnection(); var rs = connection.createStatement().executeQuery("SELECT COUNT(*) FROM " + table)) { + return rs.getInt(1); + } + } + + static BackupRunResult backupRun(String id, String startTime, BackupServiceResult... services) { + BackupArchive archive = new BackupArchive(id, id + ".zip", Path.of(id + ".zip"), 0, Instant.parse("2026-01-01T00:00:00Z")); + return new BackupRunResult(id, startTime, startTime, COMPLETED, List.of(services), archive, null); + } + + static BackupServiceResult serviceResult(String name, String status, String error) { + return new BackupServiceResult(null, status, "2026-01-01 00:00:00", "2026-01-01 00:00:01", name, error); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/repository/PairedClientRepositoryTest.java b/src/test/java/wellatleastitried/mediagarrdServer/repository/PairedClientRepositoryTest.java new file mode 100644 index 0000000..a1f5d58 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/repository/PairedClientRepositoryTest.java @@ -0,0 +1,58 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.Test; + +class PairedClientRepositoryTest extends DatabaseTestBase { + + @Test + void pairedClientsTableIsAddedToAnExistingDatabase() throws Exception { + db = null; + Files.delete(Path.of(properties.getDatabasePath())); + try (var connection = rawConnection(); var statement = connection.createStatement()) { + statement.execute("CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)"); + statement.execute("PRAGMA user_version = 2"); + } + + TestDatabase upgraded = new TestDatabase(properties); + + assertEquals(0, upgraded.pairedClients.countPairedClients()); + upgraded.pairedClients.addPairedClient("c1", "Laptop", "hash-1", Instant.parse("2026-11-19T10:00:00Z")); + assertEquals("Laptop", upgraded.pairedClients.fetchPairedClientByTokenHash("hash-1").orElseThrow().name()); + assertTrue(upgraded.pairedClients.fetchPairedClientByTokenHash("other").isEmpty()); + } + + @Test + void pairedClientsCanBeTouchedListedAndRemoved() { + Instant created = Instant.parse("2026-11-19T10:00:00Z"); + db.pairedClients.addPairedClient("c1", "Laptop", "hash-1", created); + db.pairedClients.addPairedClient("c2", "Phone", "hash-2", created.plusSeconds(5)); + + db.pairedClients.touchPairedClient("c2", created.plusSeconds(60)); + + var clients = db.pairedClients.fetchPairedClients(); + assertEquals(List.of("c1", "c2"), clients.stream().map(c -> c.id()).toList()); + assertNull(clients.get(0).lastUsedAt()); + assertEquals(created.plusSeconds(60), clients.get(1).lastUsedAt()); + assertTrue(db.pairedClients.removePairedClient("c1")); + assertFalse(db.pairedClients.removePairedClient("c1")); + assertEquals(1, db.pairedClients.countPairedClients()); + } + + @Test + void tokenHashesAreUnique() { + db.pairedClients.addPairedClient("c1", "Laptop", "hash-1", Instant.now()); + + assertThrows(IllegalStateException.class, () -> db.pairedClients.addPairedClient("c2", "Phone", "hash-1", Instant.now())); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/repository/ServiceRepositoryTest.java b/src/test/java/wellatleastitried/mediagarrdServer/repository/ServiceRepositoryTest.java new file mode 100644 index 0000000..740cba4 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/repository/ServiceRepositoryTest.java @@ -0,0 +1,66 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +class ServiceRepositoryTest extends DatabaseTestBase { + + private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr/config", "/srv/radarr/data")); + + @Test + void storesAndFetchesServicesWithPathOrderPreserved() { + assertEquals(List.of(), db.services.fetchServices()); + + db.services.addService(RADARR); + + assertEquals(Optional.of(RADARR), db.services.fetchService("radarr")); + assertEquals(Optional.of(RADARR), db.services.fetchService("RADARR")); + assertEquals(List.of(RADARR), db.services.fetchServices()); + } + + @Test + void listsServicesSortedByNameIgnoringCase() { + db.services.addService(new ServiceDefinition("sonarr", List.of("/a"))); + db.services.addService(new ServiceDefinition("Jellyfin", List.of("/b"))); + db.services.addService(new ServiceDefinition("radarr", List.of("/c"))); + + assertEquals(List.of("Jellyfin", "radarr", "sonarr"), db.services.fetchServices().stream().map(ServiceDefinition::name).toList()); + } + + @Test + void rejectsDuplicateServiceNamesIgnoringCase() { + db.services.addService(RADARR); + + assertThrows(IllegalStateException.class, () -> db.services.addService(new ServiceDefinition("Radarr", List.of("/other")))); + } + + @Test + void updatesServiceNameAndPaths() { + db.services.addService(RADARR); + ServiceDefinition renamed = new ServiceDefinition("radarr-4k", List.of("/srv/radarr-4k")); + + assertTrue(db.services.updateService("radarr", renamed)); + + assertTrue(db.services.fetchService("radarr").isEmpty()); + assertEquals(Optional.of(renamed), db.services.fetchService("radarr-4k")); + assertFalse(db.services.updateService("missing", renamed)); + } + + @Test + void removesService() { + db.services.addService(RADARR); + + assertTrue(db.services.removeService("radarr")); + assertFalse(db.services.removeService("radarr")); + assertEquals(List.of(), db.services.fetchServices()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/repository/SettingsRepositoryTest.java b/src/test/java/wellatleastitried/mediagarrdServer/repository/SettingsRepositoryTest.java new file mode 100644 index 0000000..625240d --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/repository/SettingsRepositoryTest.java @@ -0,0 +1,21 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +class SettingsRepositoryTest extends DatabaseTestBase { + + @Test + void savesAndOverwritesSettings() { + assertTrue(db.settings.fetchSetting("backup_root").isEmpty()); + + db.settings.saveSetting("backup_root", "/first"); + db.settings.saveSetting("backup_root", "/second"); + + assertEquals(Optional.of("/second"), db.settings.fetchSetting("backup_root")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/repository/SqliteDatabaseTest.java b/src/test/java/wellatleastitried/mediagarrdServer/repository/SqliteDatabaseTest.java new file mode 100644 index 0000000..bc2323a --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/repository/SqliteDatabaseTest.java @@ -0,0 +1,371 @@ +package wellatleastitried.mediagarrdServer.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.Test; + +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +class SqliteDatabaseTest extends DatabaseTestBase { + + private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr/config", "/srv/radarr/data")); + + @Test + void createsDatabaseFileAndParentDirectories() { + assertTrue(Files.isRegularFile(tempDir.resolve("nested/mediagarrd.db"))); + assertTrue(db.database.verifyDatabaseIntegrity()); + } + + @Test + void migrationRemovesOrphanedServiceRows() throws Exception { + try (var connection = rawConnection(); var statement = connection.createStatement()) { + statement.execute("INSERT INTO backup_services (backup_id, service_name, status) VALUES (42, 'radarr', 'completed')"); + statement.execute("PRAGMA user_version = 1"); + } + + new TestDatabase(properties); + + assertEquals(0, count("backup_services")); + try (var connection = rawConnection(); var rs = connection.createStatement().executeQuery("PRAGMA user_version")) { + assertEquals(2, rs.getInt(1)); + } + } + + @Test + void persistsDataAcrossInstances() { + db.services.addService(RADARR); + db.settings.saveSetting("backup_root", "/backups"); + + TestDatabase reopened = new TestDatabase(properties); + + assertEquals(List.of(RADARR), reopened.services.fetchServices()); + assertEquals(Optional.of("/backups"), reopened.settings.fetchSetting("backup_root")); + } + + @Test + void failsLoudlyWhenDatabaseIsUnusable() { + properties.setDatabasePath(tempDir.toString()); + TestDatabase broken = new TestDatabase(properties); + + assertFalse(broken.database.verifyDatabaseIntegrity()); + assertThrows(IllegalStateException.class, broken.services::fetchServices); + assertThrows(IllegalStateException.class, () -> broken.services.addService(RADARR)); + assertThrows(IllegalStateException.class, () -> broken.settings.fetchSetting("backup_root")); + } + + @Test + void verifiesOnlyOnceWhileTheSchemaIsUnchanged() { + AtomicInteger verifications = new AtomicInteger(); + TestDatabase counted = new TestDatabase(new SqliteDatabase(properties) { + @Override + protected synchronized boolean verifyDatabaseIntegrity() { + verifications.incrementAndGet(); + return super.verifyDatabaseIntegrity(); + } + }); + + counted.services.addService(RADARR); + counted.services.fetchServices(); + counted.settings.fetchSetting("backup_root"); + + assertEquals(1, verifications.get()); + } + + @Test + void rebuildsWhenTheDatabaseFileIsDeleted() throws Exception { + db.services.addService(RADARR); + + Files.delete(databaseFile()); + + assertEquals(List.of(), db.services.fetchServices()); + db.services.addService(RADARR); + assertEquals(List.of(RADARR), db.services.fetchServices()); + } + + @Test + void rebuildsWhenTheDatabaseDirectoryIsDeleted() throws Exception { + Files.delete(databaseFile()); + Files.delete(databaseFile().getParent()); + + db.settings.saveSetting("backup_root", "/backups"); + + assertEquals(Optional.of("/backups"), db.settings.fetchSetting("backup_root")); + } + + @Test + void rebuildsWhenATableIsDropped() throws Exception { + try (var connection = rawConnection(); var statement = connection.createStatement()) { + statement.execute("DROP TABLE services"); + } + + db.services.addService(RADARR); + + assertEquals(List.of(RADARR), db.services.fetchServices()); + } + + @Test + void migratesWhenAnOlderDatabaseIsSwappedIn() throws Exception { + try (var connection = rawConnection(); var statement = connection.createStatement()) { + statement.execute("INSERT INTO backup_services (backup_id, service_name, status) VALUES (42, 'radarr', 'completed')"); + statement.execute("PRAGMA user_version = 1"); + } + + db.services.fetchServices(); + + assertEquals(0, count("backup_services")); + } + + @Test + void movesACorruptDatabaseAsideOnStartup() throws Exception { + Files.writeString(databaseFile(), "x".repeat(4096)); + + TestDatabase recovered = new TestDatabase(properties); + + recovered.services.addService(RADARR); + assertEquals(List.of(RADARR), recovered.services.fetchServices()); + assertEquals(List.of("x".repeat(4096)), quarantinedContents()); + } + + @Test + void movesACorruptDatabaseAsideWhileRunning() throws Exception { + db.services.addService(RADARR); + Files.writeString(databaseFile(), "x".repeat(4096)); + + assertEquals(List.of(), db.services.fetchServices()); + assertEquals(1, quarantinedContents().size()); + } + + @Test + void notifiesListenersOnceAfterARuntimeRebuildFromAnotherThread() throws Exception { + List threads = new java.util.concurrent.CopyOnWriteArrayList<>(); + CountDownLatch notified = new CountDownLatch(1); + db.database.addRebuildListener(() -> { + threads.add(Thread.currentThread().getName()); + notified.countDown(); + }); + Files.writeString(databaseFile(), "x".repeat(4096)); + + db.services.fetchServices(); + db.services.fetchServices(); + + assertTrue(notified.await(10, TimeUnit.SECONDS)); + assertEquals(1, threads.size()); + assertFalse(threads.contains(Thread.currentThread().getName())); + } + + @Test + void doesNotNotifyListenersForAMigrationOnly() throws Exception { + CountDownLatch notified = new CountDownLatch(1); + db.database.addRebuildListener(notified::countDown); + try (var connection = rawConnection(); var statement = connection.createStatement()) { + statement.execute("DROP TABLE services"); + } + + db.services.fetchServices(); + + assertFalse(notified.await(300, TimeUnit.MILLISECONDS)); + } + + @Test + void snapshotIsAValidCopyWithTheSameRowsAndVersion() throws Exception { + db.services.addService(RADARR); + db.settings.saveSetting("backup_root", "/backups"); + db.backups.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00", serviceResult("radarr", COMPLETED, null))); + Path snapshot = tempDir.resolve("snapshot.db"); + + db.database.snapshotTo(snapshot); + + try (var connection = DriverManager.getConnection("jdbc:sqlite:" + snapshot); var statement = connection.createStatement()) { + assertEquals("ok", statement.executeQuery("PRAGMA quick_check").getString(1)); + assertEquals(2, statement.executeQuery("PRAGMA user_version").getInt(1)); + assertEquals("/backups", statement.executeQuery("SELECT value FROM settings WHERE key = 'backup_root'").getString(1)); + assertEquals("radarr", statement.executeQuery("SELECT name FROM services").getString(1)); + assertEquals("run-1", statement.executeQuery("SELECT archive_id FROM backups").getString(1)); + assertEquals("radarr", statement.executeQuery("SELECT service_name FROM backup_services").getString(1)); + } + assertEquals(List.of(RADARR), db.services.fetchServices()); + } + + @Test + void snapshotHandlesQuotesInTheTargetPath() throws Exception { + Path snapshot = Files.createDirectories(tempDir.resolve("it's here")).resolve("snapshot.db"); + + db.database.snapshotTo(snapshot); + + assertTrue(Files.isRegularFile(snapshot)); + } + + @Test + void snapshotRefusesToOverwriteAnExistingFile() throws Exception { + Path existing = tempDir.resolve("existing.db"); + Files.writeString(existing, "keep me"); + + assertThrows(IOException.class, () -> db.database.snapshotTo(existing)); + + assertEquals("keep me", Files.readString(existing)); + } + + @Test + void snapshotFailsForAMissingDatabaseWithoutCreatingOne() throws Exception { + Files.delete(databaseFile()); + Path snapshot = tempDir.resolve("snapshot.db"); + + assertThrows(IOException.class, () -> db.database.snapshotTo(snapshot)); + + assertFalse(Files.exists(databaseFile())); + assertFalse(Files.exists(snapshot)); + } + + @Test + void snapshotFailsForACorruptDatabaseWithoutMovingItAside() throws Exception { + Files.writeString(databaseFile(), "x".repeat(4096)); + Path snapshot = tempDir.resolve("snapshot.db"); + + assertThrows(SQLException.class, () -> db.database.snapshotTo(snapshot)); + + assertFalse(Files.exists(snapshot)); + assertEquals("x".repeat(4096), Files.readString(databaseFile())); + assertEquals(List.of(), quarantinedContents()); + } + + @Test + void writesWaitWhileTheSnapshotIsBeingTaken() throws Exception { + CountDownLatch snapshotting = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + TestDatabase paused = new TestDatabase(new SqliteDatabase(properties) { + @Override + protected Connection openSnapshotConnection(Path file) throws SQLException { + snapshotting.countDown(); + try { + release.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return super.openSnapshotConnection(file); + } + }); + paused.settings.saveSetting("backup_root", "/before"); + + CompletableFuture snapshot = CompletableFuture.runAsync(() -> { + try { + paused.database.snapshotTo(tempDir.resolve("snapshot.db")); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }); + assertTrue(snapshotting.await(5, TimeUnit.SECONDS)); + + CompletableFuture write = CompletableFuture.runAsync(() -> paused.settings.saveSetting("backup_root", "/during")); + CompletableFuture delete = CompletableFuture.runAsync(() -> paused.backups.deleteBackupRecordById("none")); + CompletableFuture insert = CompletableFuture.runAsync(() -> + paused.backups.addNewBackupRecord(backupRun("run-2", "2026-01-01 00:00:00", serviceResult("radarr", COMPLETED, null)))); + assertThrows(TimeoutException.class, () -> write.get(300, TimeUnit.MILLISECONDS)); + assertFalse(delete.isDone()); + assertFalse(insert.isDone()); + + release.countDown(); + snapshot.get(5, TimeUnit.SECONDS); + write.get(5, TimeUnit.SECONDS); + delete.get(5, TimeUnit.SECONDS); + insert.get(5, TimeUnit.SECONDS); + + try (var connection = DriverManager.getConnection("jdbc:sqlite:" + tempDir.resolve("snapshot.db")); + var statement = connection.createStatement()) { + assertEquals("/before", statement.executeQuery("SELECT value FROM settings WHERE key = 'backup_root'").getString(1)); + assertFalse(statement.executeQuery("SELECT 1 FROM backups").next()); + } + assertEquals(Optional.of("/during"), paused.settings.fetchSetting("backup_root")); + assertTrue(paused.backups.fetchBackupById("run-2").isPresent()); + } + + @Test + void snapshotsDoNotDeadlockWithIntegrityChecksAndWrites() { + assertTimeoutPreemptively(Duration.ofSeconds(60), () -> { + List> work = new ArrayList<>(); + for (int i = 0; i < 4; i++) { + int worker = i; + work.add(CompletableFuture.runAsync(() -> { + for (int n = 0; n < 15; n++) { + try { + db.database.snapshotTo(tempDir.resolve("snapshot-" + worker + "-" + n + ".db")); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + })); + work.add(CompletableFuture.runAsync(() -> { + for (int n = 0; n < 30; n++) { + db.settings.saveSetting("backup_root", "/" + n); + db.services.fetchServices(); + db.database.verifyDatabaseIntegrity(); + } + })); + } + CompletableFuture.allOf(work.toArray(CompletableFuture[]::new)).get(); + }); + } + + @Test + void theDatabaseFileIsOwnerOnlyAndItsNewDirectoryIsPrivate() throws IOException { + org.junit.jupiter.api.Assumptions.assumeTrue(java.nio.file.FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); + + assertEquals("rw-------", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(databaseFile()))); + assertEquals("rwx------", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(databaseFile().getParent()))); + } + + @Test + void anExistingDatabaseFileIsTightenedButItsDirectoryIsLeftAlone() throws IOException { + org.junit.jupiter.api.Assumptions.assumeTrue(java.nio.file.FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); + Path directory = Files.createDirectories(tempDir.resolve("existing")); + Files.setPosixFilePermissions(directory, java.nio.file.attribute.PosixFilePermissions.fromString("rwxr-xr-x")); + MediaGarrdPropertiesHolder.open(directory.resolve("old.db")); + Files.setPosixFilePermissions(directory.resolve("old.db"), java.nio.file.attribute.PosixFilePermissions.fromString("rw-r--r--")); + + MediaGarrdPropertiesHolder.open(directory.resolve("old.db")); + + assertEquals("rw-------", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(directory.resolve("old.db")))); + assertEquals("rwxr-xr-x", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(directory))); + } + + @Test + void aFailedTransactionIsRolledBackAndRethrown() throws Exception { + try (var connection = rawConnection()) { + connection.setAutoCommit(false); + assertThrows(SQLException.class, () -> db.database.inTransaction(connection, c -> { + c.createStatement().executeUpdate("INSERT INTO settings (key, value) VALUES ('k', 'v')"); + c.createStatement().executeUpdate("INSERT INTO no_such_table VALUES (1)"); + return null; + })); + } + assertEquals(0, count("settings")); + } + + private static final class MediaGarrdPropertiesHolder { + static void open(Path file) { + var properties = new wellatleastitried.mediagarrdServer.MediaGarrdProperties(); + properties.setDatabasePath(file.toString()); + new TestDatabase(properties); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/repository/TestDatabase.java b/src/test/java/wellatleastitried/mediagarrdServer/repository/TestDatabase.java new file mode 100644 index 0000000..7eae601 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/repository/TestDatabase.java @@ -0,0 +1,24 @@ +package wellatleastitried.mediagarrdServer.repository; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; + +public final class TestDatabase { + + public final SqliteDatabase database; + public final BackupRecordRepository backups; + public final ServiceRepository services; + public final SettingsRepository settings; + public final PairedClientRepository pairedClients; + + public TestDatabase(MediaGarrdProperties properties) { + this(new SqliteDatabase(properties)); + } + + public TestDatabase(SqliteDatabase database) { + this.database = database; + this.backups = new BackupRecordRepository(database); + this.services = new ServiceRepository(database); + this.settings = new SettingsRepository(database); + this.pairedClients = new PairedClientRepository(database); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java new file mode 100644 index 0000000..c88ed6f --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java @@ -0,0 +1,104 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.dir; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.file; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.link; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.tar; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Date; + +import org.apache.commons.compress.archivers.tar.TarConstants; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.Item; + +@Timeout(120) +class ArchiveInteropTest { + + private static final long MTIME = 1_700_000_001_000L; + + @TempDir + Path dir; + + private Path archive() throws Exception { + Item folder = dir("data/"); + folder.entry().setMode(040750); + folder.entry().setModTime(new Date(MTIME)); + folder.entry().setUserId(1000); + folder.entry().setGroupId(1001); + Item secret = file("data/id_rsa", "key"); + secret.entry().setMode(0100600); + secret.entry().setModTime(new Date(MTIME)); + secret.entry().setUserId(1000); + secret.entry().setGroupId(1001); + Item text = file("data/café ünï.txt", "compressible ".repeat(1000)); + text.entry().setModTime(new Date(MTIME + 2000)); + text.entry().setUserId(5); + text.entry().setGroupId(6); + Item empty = dir("data/empty/"); + empty.entry().setModTime(new Date(MTIME)); + Item symlink = link("data/latest", TarConstants.LF_SYMLINK, "id_rsa"); + symlink.entry().setModTime(new Date(MTIME)); + Item hardLink = link("data/id_rsa.bak", TarConstants.LF_LINK, "data/id_rsa"); + Item movie = file("data/movie.mkv", "stored ".repeat(1000)); + movie.entry().setModTime(new Date(MTIME)); + Path part = dir.resolve("0.part"); + ServiceBackupRunner.archive(tar(folder, secret, text, empty, symlink, hardLink, movie), "/srv/data", part, new ZipCompression(1)); + return ArchiveTestSupport.merge(dir, part); + } + + @Test + void bsdtarRestoresContentsModesTimesAndSymlinksFromSeekableAndStreamedArchives() throws Exception { + assumeTrue(ArchiveTestSupport.available("bsdtar")); + Path archive = archive(); + for (boolean streamed : new boolean[] {false, true}) { + Path target = Files.createDirectories(dir.resolve(streamed ? "streamed" : "seekable")); + if (streamed) { + ArchiveTestSupport.run(archive, "bsdtar", "-xpf", "-", "-C", target.toString()); + } else { + ArchiveTestSupport.run(null, "bsdtar", "-xpf", archive.toString(), "-C", target.toString()); + } + + Path data = target.resolve("srv/data"); + assertEquals("key", Files.readString(data.resolve("id_rsa"))); + assertEquals("key", Files.readString(data.resolve("id_rsa.bak"))); + assertEquals("compressible ".repeat(1000), Files.readString(data.resolve("café ünï.txt"), StandardCharsets.UTF_8)); + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(data.resolve("id_rsa")))); + assertEquals("rwxr-x---", PosixFilePermissions.toString(Files.getPosixFilePermissions(data))); + assertEquals(MTIME / 1000, Files.getLastModifiedTime(data.resolve("id_rsa")).toMillis() / 1000); + assertEquals((MTIME + 2000) / 1000, Files.getLastModifiedTime(data.resolve("café ünï.txt")).toMillis() / 1000); + assertEquals(MTIME / 1000, Files.getLastModifiedTime(data).toMillis() / 1000); + assertTrue(Files.isSymbolicLink(data.resolve("latest"))); + assertEquals("id_rsa", Files.readSymbolicLink(data.resolve("latest")).toString()); + assertTrue(Files.isDirectory(data.resolve("empty"))); + } + } + + @Test + void listingsShowNumericOwnersFromTheLocalHeaders() throws Exception { + assumeTrue(ArchiveTestSupport.available("bsdtar")); + Path archive = archive(); + + for (String listing : new String[] { + ArchiveTestSupport.run(null, "bsdtar", "-tvf", archive.toString(), "--numeric-owner"), + ArchiveTestSupport.run(archive, "bsdtar", "-tvf", "-", "--numeric-owner")}) { + assertTrue(listing.matches("(?s).*-rw-------\\s+\\d+\\s+1000\\s+1001\\s+3\\s.*id_rsa\\n.*"), listing); + assertTrue(listing.matches("(?s).*\\s5\\s+6\\s.*caf.*"), listing); + assertTrue(listing.matches("(?s).*drwxr-x---\\s+\\d+\\s+1000\\s+1001.*srv/data/\\n.*"), listing); + } + } + + @Test + void everyReaderAcceptsTheArchive() throws Exception { + ZipPartWriterTest.verifyWithTools(archive(), 7); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveScaleTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveScaleTest.java new file mode 100644 index 0000000..09b32d9 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveScaleTest.java @@ -0,0 +1,144 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Iterator; +import java.util.List; +import java.util.Random; +import java.util.stream.IntStream; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.service.GeneratedTar.Spec; + +@Tag("scale") +@Timeout(value = 60, unit = java.util.concurrent.TimeUnit.MINUTES) +class ArchiveScaleTest { + + private static final long FOUR_GIB = 0x100000000L; + private static final byte[] SMALL = "small file content\n".getBytes(java.nio.charset.StandardCharsets.UTF_8); + + @TempDir + Path dir; + + private Thread sampler; + private volatile boolean sampling; + private volatile long peakHeap; + private long started; + + @BeforeEach + void startSampling() { + assumeTrue(Runtime.getRuntime().maxMemory() <= 128L * 1024 * 1024, "run through scaleTest, which caps the heap"); + started = System.nanoTime(); + sampling = true; + sampler = new Thread(() -> { + while (sampling) { + Runtime runtime = Runtime.getRuntime(); + peakHeap = Math.max(peakHeap, runtime.totalMemory() - runtime.freeMemory()); + try { + Thread.sleep(20); + } catch (InterruptedException e) { + return; + } + } + }, "heap-sampler"); + sampler.setDaemon(true); + sampler.start(); + } + + @AfterEach + void report(org.junit.jupiter.api.TestInfo info) throws Exception { + sampling = false; + sampler.join(); + System.out.printf("SCALE %s: %d s, max heap %d MiB, peak sampled used heap %d MiB, tmpdir %s%n", info.getDisplayName(), + (System.nanoTime() - started) / 1_000_000_000L, Runtime.getRuntime().maxMemory() >> 20, peakHeap >> 20, System.getProperty("java.io.tmpdir")); + } + + private static byte[] randomBlock() { + byte[] block = new byte[64 * 1024]; + new Random(42).nextBytes(block); + return block; + } + + private Path archive(Iterator specs, String hostPath, int level) throws Exception { + Path part = dir.resolve("0.part"); + try (var tar = new GeneratedTar(specs)) { + ServiceBackupRunner.archive(tar, hostPath, part, new ZipCompression(level)); + } + System.out.printf("SCALE part %d MiB%n", Files.size(part) >> 20); + Path merged = dir.resolve("merged.zip"); + ZipPartMerger.Result result = ZipPartMerger.merge(List.of(), List.of(part), merged, dir); + Files.delete(part); + Files.delete(ZipPartWriter.indexOf(part)); + System.out.printf("SCALE archive %d MiB, %d entries, sha256 %s%n", Files.size(merged) >> 20, result.entries(), result.checksum()); + return merged; + } + + @Test + void threeHundredThousandSmallFilesBuildAnArchiveReadableByEveryTool() throws Exception { + int count = 300_000; + Iterator specs = java.util.stream.Stream.concat( + java.util.stream.Stream.of(Spec.directory("many/")), + IntStream.range(0, count).mapToObj(i -> Spec.file("many/dir" + (i % 100) + "/file-" + i + ".txt", SMALL.length, SMALL))).iterator(); + + Path merged = archive(specs, "/srv/many", 1); + + ZipPartWriterTest.verifyWithTools(merged, count + 1); + } + + @Test + void aStoredEntryJustUnderFourGiBUsesALocalZip64ExtraWithClassicCentralSizes() throws Exception { + long size = 0xF0000000L + 0x100000L; + + Path merged = archive(List.of(Spec.file("movies/film.mkv", size, randomBlock())).iterator(), "/srv/movies", 1); + + assertTrue(size < 0xFFFFFFFFL); + ZipPartWriterTest.verifyWithTools(merged, 1); + } + + @Test + void aStoredEntryOverFourGiBFollowedBySmallEntriesPushesOffsetsPastFourGiB() throws Exception { + long size = FOUR_GIB + 300_000_000L; + int small = 1000; + Iterator specs = java.util.stream.Stream.concat( + java.util.stream.Stream.of(Spec.file("movies/big.mkv", size, randomBlock())), + IntStream.range(0, small).mapToObj(i -> Spec.file("movies/small-" + i + ".txt", SMALL.length, SMALL))).iterator(); + + Path merged = archive(specs, "/srv/movies", 1); + + assertTrue(Files.size(merged) > FOUR_GIB); + ZipPartWriterTest.verifyWithTools(merged, small + 1); + extractOne(merged, "srv/movies/small-999.txt", new String(SMALL, java.nio.charset.StandardCharsets.UTF_8)); + } + + @Test + void aDeflatedEntryOverFourGiBOfRepeatedBytesOverflowsOnlyTheUncompressedSize() throws Exception { + long size = FOUR_GIB + 200_000_000L; + + Path merged = archive(List.of(Spec.file("logs/huge.log", size, new byte[64 * 1024])).iterator(), "/srv/logs", 1); + + assertTrue(Files.size(merged) < FOUR_GIB); + ZipPartWriterTest.verifyWithTools(merged, 1); + } + + private void extractOne(Path archive, String name, String expected) throws IOException, InterruptedException { + if (ArchiveTestSupport.available("bsdtar")) { + assertEquals(expected, ArchiveTestSupport.run(null, "bsdtar", "-xOf", archive.toString(), name)); + assertEquals(expected, ArchiveTestSupport.run(archive, "bsdtar", "-xOf", "-", name)); + } + if (ArchiveTestSupport.available("unzip")) { + assertEquals(expected, ArchiveTestSupport.run(null, "unzip", "-p", archive.toString(), name)); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveTestSupport.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveTestSupport.java new file mode 100644 index 0000000..066fd67 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveTestSupport.java @@ -0,0 +1,92 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipFile; + +final class ArchiveTestSupport { + + private ArchiveTestSupport() {} + + static Path merge(Path scratch, Path... parts) throws IOException { + return merge(scratch, List.of(), List.of(parts)); + } + + static Path merge(Path scratch, List snapshotParts, List parts) throws IOException { + Path archive = scratch.resolve("merged-" + System.nanoTime() + ".zip"); + ZipPartMerger.merge(snapshotParts, parts, archive, scratch); + return archive; + } + + static Map contents(Path zipPath) throws IOException { + Map entries = new TreeMap<>(); + try (ZipFile zip = ZipFile.builder().setPath(zipPath).get()) { + for (ZipArchiveEntry entry : Collections.list(zip.getEntries())) { + try (InputStream in = zip.getInputStream(entry)) { + entries.put(entry.getName(), new String(in.readAllBytes(), StandardCharsets.UTF_8)); + } + } + } + return entries; + } + + static Map partContents(Path scratch, Path... parts) throws IOException { + return contents(merge(scratch, parts)); + } + + static boolean available(String tool) { + try { + Process process = new ProcessBuilder(tool, "--help").redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.DISCARD).start(); + process.waitFor(20, TimeUnit.SECONDS); + return true; + } catch (IOException | InterruptedException e) { + return false; + } + } + + record Output(String text, long lines) {} + + static String run(Path stdin, String... command) throws IOException, InterruptedException { + return runCounting(stdin, command).text(); + } + + static Output runCounting(Path stdin, String... command) throws IOException, InterruptedException { + Path output = Files.createTempFile("tool-output", ".txt"); + try { + ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(output.toFile()); + if (stdin != null) { + builder.redirectInput(stdin.toFile()); + } + Process process = builder.start(); + if (!process.waitFor(30, TimeUnit.MINUTES)) { + process.destroyForcibly(); + throw new IOException("Timed out: " + String.join(" ", command)); + } + String text = head(output); + assertEquals(0, process.exitValue(), String.join(" ", command) + "\n" + text); + try (var lines = Files.lines(output, StandardCharsets.ISO_8859_1)) { + return new Output(text, lines.count()); + } + } finally { + Files.deleteIfExists(output); + } + } + + private static String head(Path file) throws IOException { + try (InputStream in = Files.newInputStream(file)) { + return new String(in.readNBytes(1_000_000), StandardCharsets.UTF_8); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java new file mode 100644 index 0000000..0fc098b --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java @@ -0,0 +1,573 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.RETENTION_COUNT_SETTING; +import static wellatleastitried.mediagarrdServer.service.ArchiveTestSupport.contents; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.dir; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.file; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.link; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.tar; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.DriverManager; +import java.time.Instant; +import java.util.List; +import java.util.Map; + +import org.apache.commons.compress.archivers.tar.TarConstants; +import org.apache.commons.compress.archivers.zip.UnixStat; +import org.apache.commons.compress.archivers.zip.X7875_NewUnix; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipFile; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; +import wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.Item; + +class BackupArchiveServiceTest { + + @TempDir + Path tempDir; + + private MediaGarrdProperties properties; + private TestDatabase db; + private BackupArchiveService service; + + @BeforeEach + void setUp() { + properties = new MediaGarrdProperties(); + properties.setBackupRoot(tempDir.resolve("backups").toString()); + properties.setDatabasePath(tempDir.resolve("mediagarrd.db").toString()); + properties.setRetentionCount(2); + db = new TestDatabase(properties); + service = new BackupArchiveService(properties, db.settings, db.backups); + } + + @Test + void mergesEveryServiceIntoOneArchiveLaidOutByAbsolutePath() throws Exception { + Path run = service.createRunDirectory(); + part(run, "radarr", 0, "/srv/radarr/config", tar(dir("config/"), file("config/config.xml", ""))); + part(run, "nginx", 0, "/etc/nginx/sites-available/default", tar(file("default", "server {}"))); + part(run, "nginx", 1, "/etc/nginx/sites-enabled", + tar(dir("sites-enabled/"), link("sites-enabled/default", TarConstants.LF_SYMLINK, "../sites-available/default"))); + + BackupArchive archive = service.createArchive(run); + service.removeRunDirectory(run); + + assertTrue(archive.fileName().endsWith(BackupArchiveService.ARCHIVE_SUFFIX)); + assertEquals(archive.fileName().replace(".zip", ""), archive.id()); + assertFalse(Files.exists(run)); + assertEquals(archive.id(), service.latest().orElseThrow().id()); + assertEquals( + List.of("etc/nginx/sites-available/default", "etc/nginx/sites-enabled/", "etc/nginx/sites-enabled/default", + "srv/radarr/config/", "srv/radarr/config/config.xml"), + List.copyOf(contents(archive.path()).keySet())); + assertEquals("", contents(archive.path()).get("srv/radarr/config/config.xml")); + try (ZipFile zip = ZipFile.builder().setPath(archive.path()).get()) { + ZipArchiveEntry link = zip.getEntry("etc/nginx/sites-enabled/default"); + assertTrue(link.isUnixSymlink()); + assertEquals("../sites-available/default", zip.getUnixSymlink(link)); + } + } + + @Test + void mergeKeepsMetadataAndIncludesHardLinkParts() throws Exception { + Path run = service.createRunDirectory(); + Item secret = file("ssh/id_rsa", "key"); + secret.entry().setMode(0100600); + secret.entry().setUserId(1000); + part(run, "ssh", 0, "/home/user/ssh", + tar(dir("ssh/"), secret, link("ssh/id_rsa.bak", TarConstants.LF_LINK, "ssh/id_rsa"))); + + BackupArchive archive = service.createArchive(run); + + try (ZipFile zip = ZipFile.builder().setPath(archive.path()).get()) { + ZipArchiveEntry key = zip.getEntry("home/user/ssh/id_rsa"); + assertEquals(UnixStat.FILE_FLAG | 0600, key.getUnixMode()); + assertEquals(1000, ((X7875_NewUnix) key.getExtraField(new X7875_NewUnix().getHeaderId())).getUID()); + assertEquals(UnixStat.FILE_FLAG | 0600, zip.getEntry("home/user/ssh/id_rsa.bak").getUnixMode()); + } + assertEquals("key", contents(archive.path()).get("home/user/ssh/id_rsa.bak")); + } + + @Test + void aDuplicateNameAcrossPartsFailsTheMergeAndLeavesNoArchive() throws Exception { + Path run = service.createRunDirectory(); + part(run, "a", 0, "/srv/shared", tar(dir("shared/"), file("shared/x", "1"))); + part(run, "b", 0, "/srv/shared", tar(dir("shared/"), file("shared/x", "1"))); + + assertThrows(IllegalStateException.class, () -> service.createArchive(run)); + + try (var files = Files.list(service.rootDirectory())) { + assertEquals(List.of(BackupArchiveService.RUNS_DIRECTORY), files.map(path -> path.getFileName().toString()).toList()); + } + assertFalse(Files.exists(run.resolve("merge-names.idx"))); + } + + @Test + void partsAreWrittenInSortedPathOrderWithTheSnapshotFirst() throws Exception { + db.settings.saveSetting("backup_root", "/marker"); + DatabaseHostPathResolver hostPaths = mock(DatabaseHostPathResolver.class); + when(hostPaths.resolve(db.database.databaseFile())).thenReturn(Path.of("/srv/zzz/mediagarrd.db")); + Path run = service.createRunDirectory(); + Item restricted = dir("a/"); + restricted.entry().setMode(040700); + part(run, "second", 0, "/srv/b", tar(dir("b/"), file("b/x", "1"))); + part(run, "first", 1, "/srv/a", tar(restricted, dir("a/c/"), file("a/c/x", "1"), file("a/y", "2"))); + part(run, "first", 0, "/srv/a0", tar(file("a0", "0"))); + assertEquals(COMPLETED, new DatabaseSnapshotService(db.database, hostPaths, new ZipCompression(1)).snapshot(run).status()); + + BackupArchive archive = service.createArchive(run); + + try (ZipFile zip = ZipFile.builder().setPath(archive.path()).get()) { + List order = java.util.Collections.list(zip.getEntriesInPhysicalOrder()).stream().map(ZipArchiveEntry::getName).toList(); + assertEquals(List.of("srv/zzz/mediagarrd.db", "srv/a0", "srv/a/", "srv/a/c/", "srv/a/c/x", "srv/a/y", "srv/b/", "srv/b/x"), order); + assertEquals(UnixStat.DIR_FLAG | 0700, zip.getEntry("srv/a/").getUnixMode()); + } + } + + @Test + void ignoresStrayFilesInRunDirectory() throws Exception { + Path run = service.createRunDirectory(); + Files.writeString(run.resolve("notes.txt"), "not a part"); + part(run, "radarr", 0, "/srv/radarr", tar(file("radarr", "x"))); + + assertEquals(Map.of("srv/radarr", "x"), contents(service.createArchive(run).path())); + } + + @Test + void failedMergeLeavesNoArchiveBehind() throws Exception { + Path run = service.createRunDirectory(); + Files.writeString(run.resolve("corrupt.part"), "not a part"); + + assertThrows(IllegalStateException.class, () -> service.createArchive(run)); + + try (var files = Files.list(service.rootDirectory())) { + assertEquals(List.of(BackupArchiveService.RUNS_DIRECTORY), files.map(path -> path.getFileName().toString()).toList()); + } + } + + @Test + void retentionKeepsNewestArchivesAndIgnoresUnrelatedZips() throws Exception { + Path unrelated = Files.createDirectories(service.rootDirectory()).resolve("keep-me.zip"); + Files.writeString(unrelated, "not a backup"); + + seedArchives(2); + createArchive(); + + assertEquals(2, service.listArchives().size()); + assertTrue(Files.exists(unrelated)); + } + + @Test + void deletesArchiveAndItsRecordById() throws Exception { + BackupArchive archive = createArchive(); + + assertTrue(service.deleteById(archive.id())); + + assertFalse(service.deleteById(archive.id())); + assertTrue(service.listArchives().isEmpty()); + assertTrue(db.backups.fetchBackupById(archive.id()).isEmpty()); + } + + @Test + void retentionDeletesRecordsOfRemovedArchives() throws Exception { + BackupArchive oldest = seedArchives(2).get(0); + BackupArchive newest = createArchive(); + + assertTrue(db.backups.fetchBackupById(oldest.id()).isEmpty()); + assertTrue(db.backups.fetchBackupById(newest.id()).isPresent()); + } + + @Test + void updatesAndPersistsRootDirectory() { + Path newRoot = tempDir.resolve("elsewhere/backups"); + + assertEquals(newRoot, service.updateRootDirectory(" " + newRoot + "/ ")); + + assertEquals(newRoot, service.rootDirectory()); + assertTrue(Files.isDirectory(newRoot)); + assertEquals(newRoot, new BackupArchiveService(properties, db.settings, db.backups).rootDirectory()); + } + + @Test + void createsArchivesInUpdatedRootDirectory() throws Exception { + Path newRoot = tempDir.resolve("moved"); + service.updateRootDirectory(newRoot.toString()); + + BackupArchive archive = createArchive(); + + assertEquals(newRoot, archive.path().getParent()); + assertEquals(1, service.listArchives().size()); + } + + @Test + void rejectsInvalidRootDirectories() throws Exception { + Path file = Files.writeString(tempDir.resolve("file"), "x"); + + assertThrows(IllegalArgumentException.class, () -> service.updateRootDirectory(null)); + assertThrows(IllegalArgumentException.class, () -> service.updateRootDirectory(" ")); + assertThrows(IllegalArgumentException.class, () -> service.updateRootDirectory("relative/backups")); + assertThrows(IllegalArgumentException.class, () -> service.updateRootDirectory(file.toString())); + assertEquals(tempDir.resolve("backups"), service.rootDirectory()); + } + + @Test + void persistsRetentionCountAndAppliesItOnNextArchive() throws Exception { + seedArchives(2); + + service.updateSettings(null, 1); + + assertEquals(1, service.retentionCount()); + assertEquals(2, service.listArchives().size()); + createArchive(); + assertEquals(1, service.listArchives().size()); + assertEquals(1, new BackupArchiveService(properties, db.settings, db.backups).retentionCount()); + } + + @Test + void usesPropertyRetentionUntilOneIsSaved() { + assertEquals(2, service.retentionCount()); + + properties.setRetentionCount(0); + assertEquals(1, new BackupArchiveService(properties, db.settings, db.backups).retentionCount()); + } + + @Test + void ignoresCorruptStoredRetention() { + db.settings.saveSetting(RETENTION_COUNT_SETTING, "lots"); + assertEquals(2, new BackupArchiveService(properties, db.settings, db.backups).retentionCount()); + + db.settings.saveSetting(RETENTION_COUNT_SETTING, "0"); + assertEquals(2, new BackupArchiveService(properties, db.settings, db.backups).retentionCount()); + } + + @Test + void updatesLocationAndRetentionTogether() { + Path newRoot = tempDir.resolve("both"); + + service.updateSettings(newRoot.toString(), 5); + + BackupArchiveService restarted = new BackupArchiveService(properties, db.settings, db.backups); + assertEquals(newRoot, restarted.rootDirectory()); + assertEquals(5, restarted.retentionCount()); + } + + @Test + void rejectsInvalidSettingsWithoutPartialWrites() { + assertThrows(IllegalArgumentException.class, () -> service.updateSettings(null, null)); + assertThrows(IllegalArgumentException.class, () -> service.updateSettings(null, 0)); + assertThrows(IllegalArgumentException.class, () -> service.updateSettings(tempDir.resolve("never").toString(), -1)); + + assertFalse(Files.exists(tempDir.resolve("never"))); + assertEquals(tempDir.resolve("backups"), service.rootDirectory()); + assertEquals(2, service.retentionCount()); + assertTrue(db.settings.fetchSetting(RETENTION_COUNT_SETTING).isEmpty()); + } + + @Test + void startupCleanupRemovesStaleArtifacts() throws Exception { + Path run = service.createRunDirectory(); + Files.writeString(run.resolve("partial.txt"), "x"); + Path tempZip = Files.writeString(service.rootDirectory().resolve("old" + BackupArchiveService.TEMP_SUFFIX), "x"); + + service.cleanupStaleArtifactsOnStartup(); + + assertFalse(Files.exists(run)); + assertFalse(Files.exists(tempZip)); + } + + @Test + void startupCleanupLeavesTheUsersOwnFilesAndFoldersAlone() throws Exception { + Path root = service.rootDirectory(); + Path ownRuns = Files.createDirectories(root.resolve("runs").resolve("mine")); + Path ownFile = Files.writeString(ownRuns.resolve("keep.txt"), "x"); + Path unrelatedTemp = Files.writeString(root.resolve("notes.zip.tmp"), "x"); + Path nonMediaGarrdTemp = Files.writeString(root.resolve("photos.zip.tmp"), "x"); + + service.cleanupStaleArtifactsOnStartup(); + + assertTrue(Files.exists(ownFile)); + assertTrue(Files.exists(unrelatedTemp)); + assertTrue(Files.exists(nonMediaGarrdTemp)); + } + + @Test + void runDirectoriesLiveInAMediaGarrdSpecificFolder() { + Path run = service.createRunDirectory(); + + assertEquals(service.rootDirectory().resolve(BackupArchiveService.RUNS_DIRECTORY), run.getParent()); + } + + @Test + void syncingAFileSucceedsAndSyncingAMissingDirectoryIsIgnored() throws Exception { + Path file = Files.writeString(tempDir.resolve("sync.bin"), "x"); + + BackupArchiveService.syncFile(file); + BackupArchiveService.syncDirectory(tempDir); + BackupArchiveService.syncDirectory(tempDir.resolve("missing")); + + assertTrue(Files.exists(file)); + } + + @Test + void theDatabaseSnapshotWinsOverServiceCopiesThatAreExcludedWhileCopying() throws Exception { + db.settings.saveSetting("backup_root", "/marker"); + DatabaseHostPathResolver hostPaths = mock(DatabaseHostPathResolver.class); + String entry = "srv/mediagarrd/db/mediagarrd.db"; + when(hostPaths.resolve(db.database.databaseFile())).thenReturn(Path.of("/" + entry)); + Path run = service.createRunDirectory(); + var excluded = DatabaseSnapshotService.reservedNames(Path.of("/" + entry)); + Path directory = Files.createDirectories(run.resolve("Mediagarrd")); + ServiceBackupRunner.archive(tar( + dir("db/"), + file("db/mediagarrd.db", "LIVE COPY"), + file("db/mediagarrd.db-journal", "stale journal"), + file("db/mediagarrd.db-wal", "wal"), + file("db/mediagarrd.db-shm", "shm"), + file("db/notes.txt", "keep")), "/srv/mediagarrd/db", directory.resolve("0.part"), new ZipCompression(1), excluded, java.util.Set.of()); + + var snapshot = new DatabaseSnapshotService(db.database, hostPaths, new ZipCompression(1)).snapshot(run); + BackupArchive archive = service.createArchive(run); + + assertEquals(COMPLETED, snapshot.status()); + assertEquals( + List.of("srv/mediagarrd/db/", entry, "srv/mediagarrd/db/notes.txt"), + List.copyOf(contents(archive.path()).keySet())); + assertEquals("keep", contents(archive.path()).get("srv/mediagarrd/db/notes.txt")); + Path extracted = tempDir.resolve("extracted.db"); + try (ZipFile zip = ZipFile.builder().setPath(archive.path()).get()) { + Files.copy(zip.getInputStream(zip.getEntry(entry)), extracted); + } + try (var connection = DriverManager.getConnection("jdbc:sqlite:" + extracted); + var statement = connection.createStatement()) { + assertEquals("ok", statement.executeQuery("PRAGMA quick_check").getString(1)); + assertEquals("/marker", statement.executeQuery("SELECT value FROM settings WHERE key = 'backup_root'").getString(1)); + } + } + + @Test + void aLiveDatabaseCopyThatSlippedPastTheExclusionFailsTheMerge() throws Exception { + DatabaseHostPathResolver hostPaths = mock(DatabaseHostPathResolver.class); + when(hostPaths.resolve(db.database.databaseFile())).thenReturn(Path.of("/srv/mediagarrd/db/mediagarrd.db")); + Path run = service.createRunDirectory(); + part(run, "Mediagarrd", 0, "/srv/mediagarrd/db", tar(dir("db/"), file("db/mediagarrd.db-wal", "wal"))); + new DatabaseSnapshotService(db.database, hostPaths, new ZipCompression(1)).snapshot(run); + + assertThrows(IllegalStateException.class, () -> service.createArchive(run)); + + try (var files = Files.list(service.rootDirectory())) { + assertEquals(List.of(BackupArchiveService.RUNS_DIRECTORY), files.map(path -> path.getFileName().toString()).toList()); + } + } + + @Test + @Timeout(30) + void carriesAChecksumOfTheFinalFileComputedWhileWriting() throws Exception { + Path run = service.createRunDirectory(); + part(run, "radarr", 0, "/srv/radarr", tar(file("radarr", "x".repeat(100_000)))); + part(run, "plex", 0, "/srv/plex/movie.mkv", tar(file("movie.mkv", "y".repeat(50_000)))); + + BackupArchive archive = service.createArchive(run); + + byte[] expected = java.security.MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(archive.path())); + assertEquals(java.util.HexFormat.of().formatHex(expected), archive.checksum()); + assertEquals(archive.checksum(), archive.resolvedChecksum()); + assertEquals(Files.size(archive.path()), archive.sizeBytes()); + assertFalse(Files.exists(archive.path().resolveSibling(archive.fileName() + ".tmp"))); + } + + @Test + @Timeout(30) + void storesTheChecksumFromWritingInTheBackupRecord() throws Exception { + BackupArchive archive = createArchive(); + + byte[] expected = java.security.MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(archive.path())); + try (var connection = DriverManager.getConnection("jdbc:sqlite:" + tempDir.resolve("mediagarrd.db")); + var statement = connection.createStatement(); + var result = statement.executeQuery("SELECT checksum FROM backups")) { + assertEquals(java.util.HexFormat.of().formatHex(expected), result.getString(1)); + } + } + + @Test + @Timeout(30) + void mergesPartsWithMixedStoredAndDeflatedEntries() throws Exception { + String text = "compressible text ".repeat(2000); + Path run = service.createRunDirectory(); + partWith(run, "stored", 0, "/srv/stored", tar(dir("stored/"), file("stored/a.txt", text)), 0); + partWith(run, "mixed", 0, "/srv/mixed", tar(file("mixed/b.txt", text), file("mixed/c.mkv", text)), 9); + partWith(run, "fast", 0, "/srv/fast", tar(file("fast/d.txt", text)), 1); + + BackupArchive archive = service.createArchive(run); + + assertEquals(text, contents(archive.path()).get("srv/stored/a.txt")); + assertEquals(text, contents(archive.path()).get("srv/mixed/b.txt")); + assertEquals(text, contents(archive.path()).get("srv/mixed/c.mkv")); + assertEquals(text, contents(archive.path()).get("srv/fast/d.txt")); + try (ZipFile zip = ZipFile.builder().setPath(archive.path()).get()) { + assertEquals(java.util.zip.ZipEntry.STORED, zip.getEntry("srv/stored/a.txt").getMethod()); + assertEquals(java.util.zip.ZipEntry.DEFLATED, zip.getEntry("srv/mixed/b.txt").getMethod()); + assertEquals(java.util.zip.ZipEntry.STORED, zip.getEntry("srv/mixed/c.mkv").getMethod()); + assertEquals(java.util.zip.ZipEntry.DEFLATED, zip.getEntry("srv/fast/d.txt").getMethod()); + for (ZipArchiveEntry entry : java.util.Collections.list(zip.getEntries())) { + assertFalse(entry.getGeneralPurposeBit().usesDataDescriptor(), entry.getName()); + } + } + java.util.Map streamed = new java.util.TreeMap<>(); + try (var in = new org.apache.commons.compress.archivers.zip.ZipArchiveInputStream(Files.newInputStream(archive.path()))) { + ZipArchiveEntry entry; + while ((entry = in.getNextEntry()) != null) { + streamed.put(entry.getName(), new String(in.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)); + } + } + assertEquals(contents(archive.path()), streamed); + } + + private static void partWith(Path run, String service, int index, String hostPath, java.io.InputStream tar, int level) throws Exception { + Path directory = Files.createDirectories(run.resolve(service)); + ServiceBackupRunner.archive(tar, hostPath, directory.resolve(index + ServiceBackupRunner.PART_SUFFIX), new ZipCompression(level)); + } + + private static void part(Path run, String service, int index, String hostPath, java.io.InputStream tar) throws Exception { + Path directory = Files.createDirectories(run.resolve(service)); + ServiceBackupRunner.archive(tar, hostPath, directory.resolve(index + ServiceBackupRunner.PART_SUFFIX), new ZipCompression(1)); + } + + private List seedArchives(int count) throws Exception { + Path root = Files.createDirectories(service.rootDirectory()); + List seeded = new java.util.ArrayList<>(); + for (int i = 1; i <= count; i++) { + String fileName = String.format("202101%02d", i) + "-000000-000-media-backup.zip"; + Path path = Files.writeString(root.resolve(fileName), "seeded " + i); + Files.setLastModifiedTime(path, java.nio.file.attribute.FileTime.fromMillis(10_000L * i)); + BackupArchive archive = new BackupArchive(fileName.replace(".zip", ""), fileName, path, Files.size(path), Instant.ofEpochMilli(10_000L * i)); + db.backups.addNewBackupRecord(new BackupRunResult(archive.id(), "start", "end", COMPLETED, List.of(), archive, null)); + seeded.add(archive); + } + return seeded; + } + + private BackupArchive createArchive() throws Exception { + Path run = service.createRunDirectory(); + part(run, "marker", 0, "/srv/marker", tar(file("marker", "ok"))); + BackupArchive archive = service.createArchive(run); + service.removeRunDirectory(run); + db.backups.addNewBackupRecord(new BackupRunResult(archive.id(), "start", "end", COMPLETED, List.of(), archive, null)); + return archive; + } + + @Test + void retentionKeepsOldArchivesThatHaveNoRecord() throws Exception { + Path root = Files.createDirectories(service.rootDirectory()); + Path unrecorded = root.resolve("20200101-000000-000-media-backup.zip"); + Files.writeString(unrecorded, "left by an earlier install"); + Files.setLastModifiedTime(unrecorded, java.nio.file.attribute.FileTime.fromMillis(1_000)); + + seedArchives(3); + createArchive(); + + assertTrue(Files.exists(unrecorded)); + assertTrue(service.listArchives().stream().anyMatch(archive -> archive.path().equals(unrecorded))); + assertEquals(3, service.listArchives().size()); + } + + @Test + void ordersAndReportsArchivesByTheTimestampInTheirNameNotTheirModifiedTime() throws Exception { + Path root = Files.createDirectories(service.rootDirectory()); + Path newest = archiveFile(root, "20260105-120000-123-media-backup.zip", 1_000); + Path middle = archiveFile(root, "20260103-000000-000-media-backup.zip", 3_000_000_000L); + Path oldest = archiveFile(root, "20260101-000000-000-media-backup.zip", 2_000_000_000L); + + List archives = service.listArchives(); + + assertEquals(List.of(newest, middle, oldest), archives.stream().map(BackupArchive::path).toList()); + assertEquals(Instant.parse("2026-01-05T12:00:00.123Z"), archives.get(0).createdAt()); + assertEquals(newest, service.latest().orElseThrow().path()); + } + + @Test + void retentionPrunesByTheTimestampInTheNameNotTheModifiedTime() throws Exception { + Path root = Files.createDirectories(service.rootDirectory()); + Path first = archiveFile(root, "20210101-000000-000-media-backup.zip", 9_000_000_000L); + Path second = archiveFile(root, "20210102-000000-000-media-backup.zip", 8_000_000_000L); + Path third = archiveFile(root, "20210103-000000-000-media-backup.zip", 7_000_000_000L); + for (Path path : List.of(first, second, third)) { + String id = path.getFileName().toString().replace(".zip", ""); + BackupArchive archive = new BackupArchive(id, path.getFileName().toString(), path, 1, Instant.EPOCH); + db.backups.addNewBackupRecord(new BackupRunResult(id, "start", "end", COMPLETED, List.of(), archive, null)); + } + + BackupArchive created = createArchive(); + + assertFalse(Files.exists(first)); + assertFalse(Files.exists(second)); + assertTrue(Files.exists(third)); + assertTrue(Files.exists(created.path())); + } + + @Test + void anArchiveWhoseNameHasNoTimestampFallsBackToItsModifiedTime() throws Exception { + Path root = Files.createDirectories(service.rootDirectory()); + Path odd = archiveFile(root, "manual-media-backup.zip", 1_700_000_000_000L); + Path named = archiveFile(root, "20200101-000000-000-media-backup.zip", 5); + + List archives = service.listArchives(); + + assertEquals(List.of(odd, named), archives.stream().map(BackupArchive::path).toList()); + assertEquals(Instant.ofEpochMilli(1_700_000_000_000L), archives.get(0).createdAt()); + } + + private static Path archiveFile(Path root, String name, long modifiedMillis) throws Exception { + Path path = Files.writeString(root.resolve(name), "x"); + Files.setLastModifiedTime(path, java.nio.file.attribute.FileTime.fromMillis(modifiedMillis)); + return path; + } + + @Test + void archiveIdsDropOnlyTheTrailingZipExtension() throws Exception { + Path root = Files.createDirectories(service.rootDirectory()); + Files.writeString(root.resolve("a.zip-media-backup.zip"), "x"); + + assertEquals("a.zip-media-backup", service.listArchives().get(0).id()); + } + + @Test + void newDirectoriesAndArchivesAreOwnerOnlyButExistingOnesAreLeftAlone() throws Exception { + org.junit.jupiter.api.Assumptions.assumeTrue(java.nio.file.FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); + Path existing = Files.createDirectories(tempDir.resolve("existing")); + Files.setPosixFilePermissions(existing, java.nio.file.attribute.PosixFilePermissions.fromString("rwxr-xr-x")); + service.updateRootDirectory(existing.toString()); + + BackupArchive archive = createArchive(); + + assertEquals("rwxr-xr-x", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(existing))); + assertEquals("rw-------", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(archive.path()))); + Path created = tempDir.resolve("fresh/backups"); + service.updateRootDirectory(created.toString()); + assertEquals("rwx------", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(created))); + assertEquals("rwx------", java.nio.file.attribute.PosixFilePermissions.toString(Files.getPosixFilePermissions(service.createRunDirectory()))); + } + + @Test + void rejectsOverlongAndControlCharacterLocations() { + assertThrows(IllegalArgumentException.class, () -> service.updateRootDirectory("/" + "a".repeat(BackupArchiveService.MAX_LOCATION_LENGTH))); + assertThrows(IllegalArgumentException.class, () -> service.updateRootDirectory("/tmp/x\ninjected")); + IllegalArgumentException nul = assertThrows(IllegalArgumentException.class, () -> service.updateRootDirectory("/tmp/x\0y")); + assertEquals("Backup location must not contain control characters", nul.getMessage()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java new file mode 100644 index 0000000..b92dd93 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java @@ -0,0 +1,320 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.dir; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.file; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.link; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.tar; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +import org.apache.commons.compress.archivers.tar.TarConstants; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.BackupRecordRepository; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; +import wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.Item; + +@Timeout(60) +class BackupCopyRoundsTest { + + private static final BackupArchive ARCHIVE = new BackupArchive("archive-1", "archive-1.zip", Path.of("archive-1.zip"), 1, Instant.EPOCH); + private static final Path DATABASE = Path.of("/srv/app/db/mediagarrd.db"); + + @TempDir + Path run; + + private final DockerService docker = mock(DockerService.class); + private final BackupArchiveService archives = mock(BackupArchiveService.class); + private final DatabaseSnapshotService snapshots = mock(DatabaseSnapshotService.class); + private final ServiceRepository serviceRepository = mock(ServiceRepository.class); + private final Map> sources = new HashMap<>(); + private final BackupOrchestratorService orchestrator = new BackupOrchestratorService( + new ServiceBackupRunner(docker, new ZipCompression(1)), archives, mock(BackupScheduleService.class), snapshots, serviceRepository, mock(BackupRecordRepository.class), new BackupRunLifecycle(mock(RunStatusBroadcaster.class)), mock(WebhookService.class)); + + @BeforeEach + void setUp() throws Exception { + when(archives.createRunDirectory()).thenReturn(run); + when(archives.createArchive(run)).thenReturn(ARCHIVE); + when(docker.containerFor(any())).thenReturn("cid"); + when(docker.copyFrom(eq("cid"), anyString())).thenAnswer(invocation -> { + Supplier source = sources.get(invocation.getArgument(1)); + if (source == null) { + throw new IllegalStateException("no such path"); + } + return source.get(); + }); + snapshotSucceeds(); + } + + @AfterEach + void tearDown() { + orchestrator.shutdownRunnerExecutor(); + } + + private void snapshotSucceeds() { + when(snapshots.snapshotWithHostPath(run)).thenReturn(new DatabaseSnapshotService.Outcome(result("_mediagarrd-server", COMPLETED), DATABASE)); + } + + private static BackupServiceResult result(String name, String status) { + return new BackupServiceResult(null, status, "start", "end", name, null); + } + + private void serve(String path, Item... items) { + sources.put(path, () -> { + try { + return tar(items); + } catch (IOException e) { + throw new IllegalStateException(e); + } + }); + } + + private BackupRunResult runBackup(ServiceDefinition... services) { + when(serviceRepository.fetchServices()).thenReturn(List.of(services)); + return orchestrator.runBackup(); + } + + private Map part(String service, int index) throws IOException { + return ArchiveTestSupport.partContents(run, run.resolve(service).resolve(index + ServiceBackupRunner.PART_SUFFIX)); + } + + private static BackupServiceResult resultOf(BackupRunResult run, String service) { + return run.serviceResults().stream().filter(r -> r.serviceName().equals(service)).findFirst().orElseThrow(); + } + + @Test + void aNestedPathIsSkippedWhenItsOwnerCopiedItAndCountsAsCompleted() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media", "/srv/media/config")); + serve("/srv/media", dir("media/"), file("media/a", "1"), dir("media/config/"), file("media/config/c", "2")); + + BackupRunResult result = runBackup(media); + + assertEquals(COMPLETED, result.status()); + assertEquals(COMPLETED, resultOf(result, "media").status()); + verify(docker, times(1)).copyFrom(eq("cid"), eq("/srv/media")); + verify(docker, never()).copyFrom(eq("cid"), eq("/srv/media/config")); + assertEquals(Map.of("srv/media/", "", "srv/media/a", "1", "srv/media/config/", "", "srv/media/config/c", "2"), part("media", 0)); + assertFalse(Files.exists(run.resolve("media/1.part"))); + } + + @Test + void aNestedPathInAnotherServiceIsSkippedAndReportedByItsOwnOutcome() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media")); + ServiceDefinition config = new ServiceDefinition("config", List.of("/srv/media/config")); + serve("/srv/media", dir("media/"), dir("media/config/"), file("media/config/c", "2")); + + BackupRunResult result = runBackup(media, config); + + assertEquals(COMPLETED, result.status()); + assertEquals(COMPLETED, resultOf(result, "config").status()); + assertNull(resultOf(result, "config").errorMessage()); + verify(docker, never()).copyFrom(eq("cid"), eq("/srv/media/config")); + } + + @Test + void whenTheOwnerFailsTheCoveredPathIsCopiedOnItsOwn() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media")); + ServiceDefinition config = new ServiceDefinition("config", List.of("/srv/media/config")); + sources.put("/srv/media", () -> { + throw new IllegalStateException("owner broke"); + }); + serve("/srv/media/config", dir("config/"), file("config/c", "2")); + + BackupRunResult result = runBackup(media, config); + + assertEquals(PARTIAL, result.status()); + assertEquals(FAILED, resultOf(result, "media").status()); + assertEquals(COMPLETED, resultOf(result, "config").status()); + assertEquals(Map.of("srv/media/config/", "", "srv/media/config/c", "2"), part("config", 0)); + } + + @Test + void aCoveredPathThatFailsOnItsOwnAfterAFailedOwnerFailsOnlyItsService() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media")); + ServiceDefinition config = new ServiceDefinition("config", List.of("/srv/media/config")); + ServiceDefinition other = new ServiceDefinition("other", List.of("/srv/other")); + sources.put("/srv/media", () -> { + throw new IllegalStateException("owner broke"); + }); + serve("/srv/other", dir("other/")); + + BackupRunResult result = runBackup(media, config, other); + + assertEquals(PARTIAL, result.status()); + assertEquals(FAILED, resultOf(result, "config").status()); + assertEquals("/srv/media/config: no such path", resultOf(result, "config").errorMessage()); + } + + @Test + void aSymbolicLinkAtTheCoveredPathIsNotStoredSoTheCoveredPathIsCopiedItself() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/a")); + ServiceDefinition linked = new ServiceDefinition("linked", List.of("/srv/a/link")); + serve("/srv/a", dir("a/"), link("a/link", TarConstants.LF_SYMLINK, "/mnt/x")); + serve("/srv/a/link", dir("link/"), file("link/data", "real")); + + BackupRunResult result = runBackup(media, linked); + + assertEquals(COMPLETED, result.status()); + verify(docker).copyFrom("cid", "/srv/a/link"); + assertEquals(Map.of("srv/a/link/", "", "srv/a/link/data", "real"), part("linked", 0)); + assertFalse(part("media", 0).containsKey("srv/a/link")); + } + + @Test + void aChainOfNestedPathsFallsBackOneRoundAtATimeWithoutDuplicates() throws Exception { + ServiceDefinition outer = new ServiceDefinition("outer", List.of("/srv/a")); + ServiceDefinition middle = new ServiceDefinition("middle", List.of("/srv/a/b")); + ServiceDefinition inner = new ServiceDefinition("inner", List.of("/srv/a/b/c")); + sources.put("/srv/a", () -> { + throw new IllegalStateException("outer broke"); + }); + serve("/srv/a/b", dir("b/"), dir("b/c/"), file("b/c/x", "1")); + + BackupRunResult result = runBackup(outer, middle, inner); + + assertEquals(FAILED, resultOf(result, "outer").status()); + assertEquals(COMPLETED, resultOf(result, "middle").status()); + assertEquals(COMPLETED, resultOf(result, "inner").status()); + verify(docker, never()).copyFrom(eq("cid"), eq("/srv/a/b/c")); + assertEquals(3, part("middle", 0).size()); + } + + @Test + void ofSeveralServicesWithTheSamePathOnlyTheFirstByNameCopiesIt() throws Exception { + ServiceDefinition b = new ServiceDefinition("b", List.of("/srv/shared")); + ServiceDefinition a = new ServiceDefinition("a", List.of("/srv/shared")); + ServiceDefinition c = new ServiceDefinition("c", List.of("/srv/shared")); + serve("/srv/shared", dir("shared/"), file("shared/x", "1")); + + BackupRunResult result = runBackup(b, a, c); + + assertEquals(COMPLETED, result.status()); + verify(docker, times(1)).copyFrom("cid", "/srv/shared"); + assertTrue(Files.exists(run.resolve("a/0.part"))); + assertFalse(Files.exists(run.resolve("b/0.part"))); + assertFalse(Files.exists(run.resolve("c/0.part"))); + } + + @Test + void whenTheOwnerOfSeveralEqualPathsFailsExactlyOneOtherCopiesIt() throws Exception { + ServiceDefinition a = new ServiceDefinition("a", List.of("/srv/shared")); + ServiceDefinition b = new ServiceDefinition("b", List.of("/srv/shared")); + ServiceDefinition c = new ServiceDefinition("c", List.of("/srv/shared")); + int[] calls = {0}; + sources.put("/srv/shared", () -> { + if (calls[0]++ == 0) { + throw new IllegalStateException("first broke"); + } + try { + return tar(dir("shared/"), file("shared/x", "1")); + } catch (IOException e) { + throw new IllegalStateException(e); + } + }); + + BackupRunResult result = runBackup(a, b, c); + + assertEquals(2, calls[0]); + assertEquals(FAILED, resultOf(result, "a").status()); + assertEquals(COMPLETED, resultOf(result, "b").status()); + assertEquals(COMPLETED, resultOf(result, "c").status()); + assertTrue(Files.exists(run.resolve("b/0.part"))); + assertFalse(Files.exists(run.resolve("c/0.part"))); + } + + @Test + void aServiceKeepsItsOwnPathsWhileOneOfThemIsCoveredElsewhere() throws Exception { + ServiceDefinition media = new ServiceDefinition("media", List.of("/srv/media")); + ServiceDefinition mixed = new ServiceDefinition("mixed", List.of("/srv/media/config", "/etc/mixed")); + serve("/srv/media", dir("media/"), dir("media/config/")); + serve("/etc/mixed", dir("mixed/"), file("mixed/m", "m")); + + BackupRunResult result = runBackup(media, mixed); + + assertEquals(COMPLETED, resultOf(result, "mixed").status()); + assertFalse(Files.exists(run.resolve("mixed/0.part"))); + assertEquals(Map.of("etc/mixed/", "", "etc/mixed/m", "m"), part("mixed", 1)); + } + + @Test + void theDatabaseAndItsSidecarsAreLeftOutOfServiceCopiesWhenTheSnapshotSucceeded() throws Exception { + ServiceDefinition app = new ServiceDefinition("app", List.of("/srv/app")); + serve("/srv/app", dir("app/"), dir("app/db/"), file("app/db/mediagarrd.db", "live"), file("app/db/mediagarrd.db-wal", "wal"), + file("app/db/mediagarrd.db-shm", "shm"), file("app/db/mediagarrd.db-journal", "j"), link("app/db/hard", TarConstants.LF_LINK, "app/db/mediagarrd.db"), + file("app/db/notes", "keep")); + + runBackup(app); + + assertEquals(Map.of("srv/app/", "", "srv/app/db/", "", "srv/app/db/notes", "keep"), part("app", 0)); + } + + @Test + void theLiveDatabaseIsKeptWhenTheSnapshotFails() throws Exception { + when(snapshots.snapshotWithHostPath(run)).thenReturn(new DatabaseSnapshotService.Outcome(result("_mediagarrd-server", FAILED), DATABASE)); + ServiceDefinition app = new ServiceDefinition("app", List.of("/srv/app")); + serve("/srv/app", dir("app/"), dir("app/db/"), file("app/db/mediagarrd.db", "live"), file("app/db/mediagarrd.db-wal", "wal")); + + BackupRunResult result = runBackup(app); + + assertEquals(PARTIAL, result.status()); + assertEquals(Map.of("srv/app/", "", "srv/app/db/", "", "srv/app/db/mediagarrd.db", "live", "srv/app/db/mediagarrd.db-wal", "wal"), part("app", 0)); + } + + @Test + void nothingIsExcludedWhenTheSnapshotThrows() throws Exception { + when(snapshots.snapshotWithHostPath(run)).thenThrow(new IllegalStateException("docker down")); + ServiceDefinition app = new ServiceDefinition("app", List.of("/srv/app")); + serve("/srv/app", dir("app/"), file("app/mediagarrd.db", "live")); + + BackupRunResult result = runBackup(app); + + assertEquals(PARTIAL, result.status()); + assertEquals(Map.of("srv/app/", "", "srv/app/mediagarrd.db", "live"), part("app", 0)); + verify(archives, atLeastOnce()).createArchive(run); + } + + @Test + void theSnapshotIsTakenOnceBeforeAnyCopyStarts() throws Exception { + ServiceDefinition app = new ServiceDefinition("app", List.of("/srv/app")); + serve("/srv/app", dir("app/")); + + runBackup(app); + + var order = org.mockito.Mockito.inOrder(snapshots, docker); + order.verify(snapshots).snapshotWithHostPath(run); + order.verify(docker).copyFrom("cid", "/srv/app"); + verify(snapshots, times(1)).snapshotWithHostPath(run); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java new file mode 100644 index 0000000..3d3b7fb --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java @@ -0,0 +1,672 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.nio.file.Path; +import java.time.Instant; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.mockito.ArgumentCaptor; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.BackupRecordRepository; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; +import wellatleastitried.mediagarrdServer.repository.SettingsRepository; + +@Timeout(30) +class BackupOrchestratorServiceTest { + + private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr")); + private static final ServiceDefinition SONARR = new ServiceDefinition("sonarr", List.of("/srv/sonarr")); + private static final String SNAPSHOT = DatabaseSnapshotService.SERVICE_NAME; + private static final Path RUN_DIR = Path.of("/tmp/run"); + private static final BackupArchive ARCHIVE = new BackupArchive("archive-1", "archive-1.zip", Path.of("archive-1.zip"), 1, Instant.EPOCH); + + private final ServiceBackupRunner runner = mock(ServiceBackupRunner.class); + private final BackupArchiveService archives = mock(BackupArchiveService.class); + private final BackupScheduleService schedule = mock(BackupScheduleService.class); + private final ServiceRepository services = mock(ServiceRepository.class); + private final BackupRecordRepository backups = mock(BackupRecordRepository.class); + private final DatabaseSnapshotService snapshots = mock(DatabaseSnapshotService.class); + private final RunStatusBroadcaster broadcaster = mock(RunStatusBroadcaster.class); + private final BackupRunLifecycle lifecycle = new BackupRunLifecycle(broadcaster); + private final WebhookService webhook = mock(WebhookService.class); + private final BackupOrchestratorService orchestrator = new BackupOrchestratorService(runner, archives, schedule, snapshots, services, backups, lifecycle, webhook); + + @BeforeEach + void setUp() { + when(archives.createRunDirectory()).thenReturn(RUN_DIR); + when(archives.createArchive(RUN_DIR)).thenReturn(ARCHIVE); + when(snapshots.snapshotWithHostPath(RUN_DIR)).thenReturn(snapshotOutcome(COMPLETED)); + } + + @AfterEach + void tearDown() { + orchestrator.shutdownRunnerExecutor(); + } + + @Test + void refusesToRunWithoutServices() { + when(services.fetchServices()).thenReturn(List.of()); + + assertThrows(RunRejectedException.class, orchestrator::runBackup); + + verify(archives, never()).createRunDirectory(); + assertFalse(orchestrator.isRunning()); + verify(broadcaster, never()).publishStarted(any()); + verify(broadcaster, never()).publishFinished(any(), any(), any()); + verify(schedule, never()).deferNextRun(); + verify(webhook, never()).notifyRun(any()); + verify(webhook, never()).notifyFailure(any()); + } + + @Test + void aRejectedManualRunLeavesTheRealScheduleUntouched() { + MediaGarrdProperties properties = new MediaGarrdProperties(); + BackupScheduleService realSchedule = new BackupScheduleService(properties, mock(SettingsRepository.class), mock(BackupRecordRepository.class), mock(SetupService.class)); + BackupOrchestratorService manual = new BackupOrchestratorService(runner, archives, realSchedule, snapshots, services, backups, new BackupRunLifecycle(broadcaster), webhook); + when(services.fetchServices()).thenReturn(List.of()); + Instant before = realSchedule.getNextRun(); + + assertThrows(RunRejectedException.class, manual::runBackup); + + assertEquals(before, realSchedule.getNextRun()); + manual.shutdownRunnerExecutor(); + } + + @Test + void aScheduledRunWithoutServicesDefersTheNextCheck() { + when(schedule.dueNow()).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of()); + + orchestrator.scheduledRun(); + + verify(schedule).deferNextRun(); + verify(broadcaster, never()).publishStarted(any()); + } + + @Test + void aScheduledRunRejectedBecauseOneIsInProgressDoesNotDefer() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(); + return round(RADARR, COMPLETED); + }); + when(schedule.dueNow()).thenReturn(true); + + CompletableFuture manual = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(started.await(5, TimeUnit.SECONDS)); + assertThrows(RunRejectedException.class, () -> orchestrator.runBackup(true)); + + verify(schedule, never()).deferNextRun(); + release.countDown(); + manual.get(5, TimeUnit.SECONDS); + } + + @Test + void aDueScheduledRunWithServicesRunsABackup() { + when(schedule.dueNow()).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(RADARR, COMPLETED)); + + orchestrator.scheduledRun(); + + verify(schedule).markRunStarted(); + verify(archives).createArchive(RUN_DIR); + verify(broadcaster).publishFinished(eq(COMPLETED), any(), any()); + } + + @Test + void aScheduledCheckThatIsNotDueDoesNothing() { + when(schedule.dueNow()).thenReturn(false); + + orchestrator.scheduledRun(); + + verify(services, never()).fetchServices(); + verify(broadcaster, never()).publishStarted(any()); + verify(schedule, never()).markRunStarted(); + verify(schedule, never()).deferNextRun(); + } + + @Test + void aScheduledCheckDuringARunSkipsWithoutLookingAtTheSchedule() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(); + return round(RADARR, COMPLETED); + }); + CompletableFuture manual = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(started.await(5, TimeUnit.SECONDS)); + + orchestrator.scheduledRun(); + + verify(schedule, never()).dueNow(); + verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); + release.countDown(); + manual.get(5, TimeUnit.SECONDS); + } + + @Test + void aRunRejectedBecauseOneIsInProgressSendsNoWebhook() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(); + return round(RADARR, COMPLETED); + }); + CompletableFuture manual = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(started.await(5, TimeUnit.SECONDS)); + + assertThrows(RunRejectedException.class, orchestrator::runBackup); + + release.countDown(); + manual.get(5, TimeUnit.SECONDS); + verify(webhook, never()).notifyFailure(any()); + verify(webhook, org.mockito.Mockito.times(1)).notifyRun(any()); + } + + @Test + void aFailureBeforeTheRunStartsSendsNoWebhook() { + when(services.fetchServices()).thenThrow(new IllegalStateException("database locked")); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + verify(webhook, never()).notifyFailure(any()); + verify(webhook, never()).notifyRun(any()); + } + + @Test + void aFailureAfterTheRunStartsSendsAFailedWebhookAndRethrows() { + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(RADARR, COMPLETED)); + when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); + + IllegalStateException e = assertThrows(IllegalStateException.class, orchestrator::runBackup); + + assertEquals("disk full", e.getMessage()); + verify(webhook).notifyFailure("disk full"); + verify(webhook, never()).notifyRun(any()); + } + + @Test + void aScheduledRunThatEndsPartialSendsAWebhook() { + when(schedule.dueNow()).thenReturn(true); + givenResults(COMPLETED, FAILED); + + orchestrator.scheduledRun(); + + ArgumentCaptor sent = ArgumentCaptor.forClass(BackupRunResult.class); + verify(webhook).notifyRun(sent.capture()); + assertEquals(PARTIAL, sent.getValue().status()); + } + + @Test + void aCompletedRunStillHandsTheResultToTheWebhookService() { + givenResults(COMPLETED, COMPLETED); + + BackupRunResult result = orchestrator.runBackup(); + + verify(webhook).notifyRun(result); + verify(webhook, never()).notifyFailure(any()); + } + + @Test + void aRunWhereEveryServiceFailsSendsOneFailedWebhook() { + givenResults(FAILED, FAILED); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + ArgumentCaptor sent = ArgumentCaptor.forClass(BackupRunResult.class); + verify(webhook).notifyRun(sent.capture()); + assertEquals(FAILED, sent.getValue().status()); + assertNull(sent.getValue().archive()); + verify(webhook, never()).notifyFailure(any()); + } + + @Test + void aFailedRecordWithAnArchiveSendsAFailedWebhook() { + givenResults(PARTIAL, FAILED); + + orchestrator.runBackup(); + + ArgumentCaptor sent = ArgumentCaptor.forClass(BackupRunResult.class); + verify(webhook).notifyRun(sent.capture()); + assertEquals(FAILED, sent.getValue().status()); + assertEquals(ARCHIVE, sent.getValue().archive()); + } + + @Test + void aScheduledRunThatFailsDoesNotStopTheScheduler() { + when(schedule.dueNow()).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenThrow(new IllegalStateException("crashed")); + when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); + + org.junit.jupiter.api.Assertions.assertDoesNotThrow(orchestrator::scheduledRun); + org.junit.jupiter.api.Assertions.assertDoesNotThrow(orchestrator::scheduledRun); + + verify(broadcaster, org.mockito.Mockito.times(2)).publishFinished(eq(FAILED), any(), any()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void aScheduledRunWhoseArchivingFailsDoesNotStopTheScheduler() { + when(schedule.dueNow()).thenReturn(true); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(RADARR, COMPLETED)); + when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); + + org.junit.jupiter.api.Assertions.assertDoesNotThrow(orchestrator::scheduledRun); + org.junit.jupiter.api.Assertions.assertDoesNotThrow(orchestrator::scheduledRun); + + verify(archives, org.mockito.Mockito.times(2)).createArchive(RUN_DIR); + verify(broadcaster, org.mockito.Mockito.times(2)).publishFinished(eq(FAILED), any(), any()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void changingServicesReleasesTheDeferral() { + orchestrator.servicesChanged(); + + verify(schedule).releaseDeferral(); + } + + @Test + void completedWhenEveryServiceSucceeds() { + givenResults(COMPLETED, COMPLETED); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(COMPLETED, result.status()); + assertEquals("", result.errorMessage()); + assertEquals(List.of("radarr", "sonarr", SNAPSHOT), result.serviceNames()); + result.serviceResults().forEach(r -> assertEquals("archive-1", r.runId())); + verify(schedule).markRunStarted(); + verify(backups).addNewBackupRecord(result); + verify(archives).removeRunDirectory(RUN_DIR); + } + + @Test + void partialWhenSomeServicesFail() { + givenResults(COMPLETED, FAILED); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(PARTIAL, result.status()); + assertEquals("sonarr: boom", result.errorMessage()); + verify(broadcaster).publishFinished(eq(PARTIAL), any(), any()); + } + + @Test + void partialWhenOnlyTheDatabaseSnapshotFails() { + givenResults(COMPLETED, COMPLETED); + when(snapshots.snapshotWithHostPath(RUN_DIR)).thenReturn(snapshotOutcome(FAILED)); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(PARTIAL, result.status()); + assertEquals(SNAPSHOT + ": boom", result.errorMessage()); + assertEquals(ARCHIVE, result.archive()); + result.serviceResults().forEach(r -> assertEquals("archive-1", r.runId())); + verify(backups).addNewBackupRecord(result); + } + + @Test + void snapshotFailureIsAddedToTheServiceErrors() { + givenResults(COMPLETED, FAILED); + when(snapshots.snapshotWithHostPath(RUN_DIR)).thenReturn(snapshotOutcome(FAILED)); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(PARTIAL, result.status()); + assertEquals("sonarr: boom\n" + SNAPSHOT + ": boom", result.errorMessage()); + } + + @Test + void aThrowingSnapshotStillProducesAPartialArchive() { + givenResults(COMPLETED, COMPLETED); + when(snapshots.snapshotWithHostPath(RUN_DIR)).thenThrow(new IllegalStateException("docker down")); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(PARTIAL, result.status()); + assertEquals(SNAPSHOT + ": docker down", result.errorMessage()); + assertEquals(ARCHIVE, result.archive()); + verify(backups).addNewBackupRecord(result); + } + + @Test + void snapshotRunsBeforeTheCopiesAndTheArchiveIsCreatedLast() { + givenResults(COMPLETED, COMPLETED); + + orchestrator.runBackup(); + + var order = inOrder(snapshots, runner, archives); + order.verify(snapshots).snapshotWithHostPath(RUN_DIR); + order.verify(runner, org.mockito.Mockito.atLeastOnce()).copyPaths(any(), any(), eq(RUN_DIR), any(), any()); + order.verify(archives).createArchive(RUN_DIR); + } + + @Test + void failedWhenNoServiceCompletes() { + givenResults(PARTIAL, FAILED); + + assertEquals(FAILED, orchestrator.runBackup().status()); + } + + @Test + void skipsArchiveWhenEveryServiceFails() { + givenResults(FAILED, FAILED); + + IllegalStateException e = assertThrows(IllegalStateException.class, orchestrator::runBackup); + + assertTrue(e.getMessage().contains("radarr: boom\nsonarr: boom")); + verify(archives, never()).createArchive(any()); + verify(archives).removeRunDirectory(RUN_DIR); + assertFalse(orchestrator.isRunning()); + + ArgumentCaptor recorded = ArgumentCaptor.forClass(BackupRunResult.class); + verify(backups).addNewBackupRecord(recorded.capture()); + BackupRunResult run = recorded.getValue(); + assertEquals(FAILED, run.status()); + assertNull(run.archive()); + assertEquals("radarr: boom\nsonarr: boom", run.errorMessage()); + run.serviceResults().forEach(r -> assertEquals(run.runId(), r.runId())); + verify(broadcaster).publishFinished(eq(FAILED), any(), any()); + } + + @Test + void runnerExceptionsBecomeFailedResults() { + when(services.fetchServices()).thenReturn(List.of(RADARR, SONARR)); + when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenThrow(new IllegalStateException("crashed")); + when(runner.copyPaths(eq(SONARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(SONARR, COMPLETED)); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(PARTIAL, result.status()); + assertEquals("radarr: crashed", result.errorMessage()); + } + + @Test + void cleansUpWhenArchivingFails() { + givenResults(COMPLETED, COMPLETED); + when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + verify(archives).removeRunDirectory(RUN_DIR); + verify(backups, never()).addNewBackupRecord(any()); + assertFalse(orchestrator.isRunning()); + verify(broadcaster).publishFinished(eq(FAILED), any(), any()); + } + + @Test + void rejectsConcurrentRuns() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(); + return round(RADARR, COMPLETED); + }); + + CompletableFuture first = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(started.await(5, TimeUnit.SECONDS)); + + assertTrue(orchestrator.isRunning()); + assertThrows(RunRejectedException.class, orchestrator::runBackup); + + release.countDown(); + assertEquals(COMPLETED, first.get(5, TimeUnit.SECONDS).status()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void configChangesAreRejectedDuringABackupRun() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(); + return round(RADARR, COMPLETED); + }); + + CompletableFuture run = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(started.await(5, TimeUnit.SECONDS)); + + assertThrows(BackupInProgressException.class, () -> lifecycle.whileIdle(() -> "changed")); + + release.countDown(); + run.get(5, TimeUnit.SECONDS); + assertEquals("changed", lifecycle.whileIdle(() -> "changed")); + } + + @Test + void backupWaitsForInFlightConfigChange() throws Exception { + CountDownLatch changing = new CountDownLatch(1); + CountDownLatch finishChange = new CountDownLatch(1); + givenResults(COMPLETED, COMPLETED); + + CompletableFuture change = CompletableFuture.supplyAsync(() -> lifecycle.whileIdle(() -> { + changing.countDown(); + try { + finishChange.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return "changed"; + })); + assertTrue(changing.await(5, TimeUnit.SECONDS)); + + CompletableFuture run = CompletableFuture.supplyAsync(orchestrator::runBackup); + Thread.sleep(100); + assertFalse(run.isDone()); + verify(services, never()).fetchServices(); + + finishChange.countDown(); + assertEquals("changed", change.get(5, TimeUnit.SECONDS)); + assertEquals(COMPLETED, run.get(5, TimeUnit.SECONDS).status()); + } + + @Test + void publishesStartedBeforeWorkAndFinishedWithTheRunStatus() { + givenResults(COMPLETED, COMPLETED); + + orchestrator.runBackup(); + + var order = inOrder(broadcaster, runner, services); + order.verify(services).fetchServices(); + order.verify(broadcaster).publishStarted(any()); + order.verify(runner, org.mockito.Mockito.atLeastOnce()).copyPaths(any(), any(), any(), any(), any()); + order.verify(broadcaster).publishFinished(eq(COMPLETED), any(), any()); + verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); + verify(broadcaster, org.mockito.Mockito.times(1)).publishFinished(any(), any(), any()); + } + + @Test + void publishesFailedWhenTheRunDirectoryCannotBeCreated() { + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(archives.createRunDirectory()).thenThrow(new IllegalStateException("no space")); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + verify(broadcaster).publishStarted(any()); + verify(broadcaster).publishFinished(eq(FAILED), any(), any()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void publishesFailedWhenRecordingTheRunThrows() { + givenResults(COMPLETED, COMPLETED); + doThrow(new IllegalStateException("db locked")).when(backups).addNewBackupRecord(any()); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + verify(broadcaster).publishFinished(eq(FAILED), any(), any()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void runningIsFalseWhenFinishedIsPublished() { + givenResults(COMPLETED, COMPLETED); + AtomicBoolean runningAtFinish = new AtomicBoolean(true); + doAnswer(invocation -> { + runningAtFinish.set(orchestrator.isRunning()); + return null; + }).when(broadcaster).publishFinished(any(), any(), any()); + + orchestrator.runBackup(); + + assertFalse(runningAtFinish.get()); + } + + @Test + void aFailingCleanupDoesNotStickTheRunningFlag() { + givenResults(COMPLETED, COMPLETED); + doThrow(new IllegalStateException("cannot delete")).when(archives).removeRunDirectory(RUN_DIR); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(COMPLETED, result.status()); + assertFalse(orchestrator.isRunning()); + verify(broadcaster).publishFinished(eq(COMPLETED), any(), any()); + assertEquals("changed", lifecycle.whileIdle(() -> "changed")); + assertEquals(COMPLETED, orchestrator.runBackup().status()); + } + + @Test + void aFailingCleanupDoesNotHideTheRunsOwnFailure() { + givenResults(COMPLETED, COMPLETED); + when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); + doThrow(new IllegalStateException("cannot delete")).when(archives).removeRunDirectory(RUN_DIR); + + IllegalStateException e = assertThrows(IllegalStateException.class, orchestrator::runBackup); + + assertEquals("disk full", e.getMessage()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void aFailingPublishNeverBreaksTheRun() { + givenResults(COMPLETED, COMPLETED); + doThrow(new IllegalStateException("boom")).when(broadcaster).publishStarted(any()); + doThrow(new IllegalStateException("boom")).when(broadcaster).publishFinished(any(), any(), any()); + + assertEquals(COMPLETED, orchestrator.runBackup().status()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void aRejectedConcurrentRunPublishesNothingExtra() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(services.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(); + return round(RADARR, COMPLETED); + }); + + CompletableFuture first = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(started.await(5, TimeUnit.SECONDS)); + assertThrows(RunRejectedException.class, orchestrator::runBackup); + verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); + verify(broadcaster, never()).publishFinished(any(), any(), any()); + + release.countDown(); + first.get(5, TimeUnit.SECONDS); + verify(broadcaster, org.mockito.Mockito.times(1)).publishFinished(eq(COMPLETED), any(), any()); + } + + @Test + void aFinishIsNeverOvertakenByTheNextRunsStart() throws Exception { + givenResults(COMPLETED, COMPLETED); + CountDownLatch inFinish = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + doAnswer(invocation -> { + inFinish.countDown(); + release.await(); + return null; + }).doNothing().when(broadcaster).publishFinished(any(), any(), any()); + + CompletableFuture first = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(inFinish.await(5, TimeUnit.SECONDS)); + CompletableFuture second = CompletableFuture.supplyAsync(orchestrator::runBackup); + Thread.sleep(200); + + assertFalse(second.isDone()); + verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); + + release.countDown(); + first.get(5, TimeUnit.SECONDS); + second.get(5, TimeUnit.SECONDS); + var order = inOrder(broadcaster); + order.verify(broadcaster).publishStarted(any()); + order.verify(broadcaster).publishFinished(any(), any(), any()); + order.verify(broadcaster).publishStarted(any()); + order.verify(broadcaster).publishFinished(any(), any(), any()); + } + + private void givenResults(String radarrStatus, String sonarrStatus) { + when(services.fetchServices()).thenReturn(List.of(RADARR, SONARR)); + when(runner.copyPaths(eq(RADARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(RADARR, radarrStatus)); + when(runner.copyPaths(eq(SONARR), any(), eq(RUN_DIR), any(), any())).thenReturn(round(SONARR, sonarrStatus)); + } + + private static DatabaseSnapshotService.Outcome snapshotOutcome(String status) { + return new DatabaseSnapshotService.Outcome(result(SNAPSHOT, status), Path.of("/srv/mediagarrd/db/mediagarrd.db")); + } + + private static ServiceBackupRunner.ServiceRound round(ServiceDefinition service, String status) { + String path = service.paths().get(0); + return switch (status) { + case COMPLETED -> new ServiceBackupRunner.ServiceRound(null, List.of(new ServiceBackupRunner.PathCopy(0, path, true, null, Set.of()))); + case PARTIAL -> new ServiceBackupRunner.ServiceRound(null, List.of( + new ServiceBackupRunner.PathCopy(0, path, true, null, Set.of()), new ServiceBackupRunner.PathCopy(1, path, false, "boom", Set.of()))); + default -> new ServiceBackupRunner.ServiceRound(null, List.of(new ServiceBackupRunner.PathCopy(0, path, false, "boom", Set.of()))); + }; + } + + private static BackupServiceResult result(String name, String status) { + return new BackupServiceResult(null, status, "start", "end", name, COMPLETED.equals(status) ? null : "boom"); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupRunLifecycleTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupRunLifecycleTest.java new file mode 100644 index 0000000..6563931 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupRunLifecycleTest.java @@ -0,0 +1,128 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; + +import java.time.Instant; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import wellatleastitried.mediagarrdServer.model.BackupRunResult; + +class BackupRunLifecycleTest { + + private final RunStatusBroadcaster broadcaster = mock(RunStatusBroadcaster.class); + private final BackupRunLifecycle lifecycle = new BackupRunLifecycle(broadcaster); + private final Instant start = Instant.parse("2026-11-20T10:00:00Z"); + + private static BackupRunResult result(String status) { + return new BackupRunResult("run", "s", "e", status, List.of(), null, null); + } + + @Test + void aStartedRunPublishesStartedThenFinishedWithItsStatus() { + lifecycle.run(start, run -> { + run.markStarted(); + assertTrue(lifecycle.isRunning()); + return result(COMPLETED); + }); + + InOrder order = inOrder(broadcaster); + order.verify(broadcaster).publishStarted(start); + order.verify(broadcaster).publishFinished(eq(COMPLETED), eq(start), any()); + assertFalse(lifecycle.isRunning()); + } + + @Test + void aBodyThatThrowsFinishesAsFailedAndReleasesTheRun() { + assertThrows(IllegalStateException.class, () -> lifecycle.run(start, run -> { + run.markStarted(); + throw new IllegalStateException("boom"); + })); + + verify(broadcaster).publishFinished(eq(FAILED), eq(start), any()); + assertFalse(lifecycle.isRunning()); + assertEquals(COMPLETED, lifecycle.run(start, run -> result(COMPLETED)).status()); + } + + @Test + void aRunThatNeverStartedPublishesNothing() { + assertThrows(RunRejectedException.class, () -> lifecycle.run(start, run -> { + throw new RunRejectedException("No services are configured for backup"); + })); + + verify(broadcaster, never()).publishStarted(any()); + verify(broadcaster, never()).publishFinished(any(), any(), any()); + assertFalse(lifecycle.isRunning()); + } + + @Test + void markingStartedTwicePublishesOneStartedEvent() { + lifecycle.run(start, run -> { + run.markStarted(); + run.markStarted(); + return result(COMPLETED); + }); + + verify(broadcaster, times(1)).publishStarted(start); + } + + @Test + void aSecondRunIsRejectedWhileOneIsRunning() throws Exception { + CountDownLatch inside = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CompletableFuture first = CompletableFuture.supplyAsync(() -> lifecycle.run(start, run -> { + inside.countDown(); + await(release); + return result(COMPLETED); + })); + assertTrue(inside.await(5, TimeUnit.SECONDS)); + + assertThrows(RunRejectedException.class, () -> lifecycle.run(start, run -> result(COMPLETED))); + + release.countDown(); + first.get(5, TimeUnit.SECONDS); + } + + @Test + void whileIdleIsRefusedWhileARunHoldsTheConfigLockAndWorksAfterwards() throws Exception { + CountDownLatch inside = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CompletableFuture running = CompletableFuture.supplyAsync(() -> lifecycle.run(start, run -> { + inside.countDown(); + await(release); + return result(COMPLETED); + })); + assertTrue(inside.await(5, TimeUnit.SECONDS)); + + assertThrows(BackupInProgressException.class, () -> lifecycle.whileIdle(() -> "changed")); + + release.countDown(); + running.get(5, TimeUnit.SECONDS); + assertEquals("changed", lifecycle.whileIdle(() -> "changed")); + } + + private static void await(CountDownLatch latch) { + try { + latch.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java new file mode 100644 index 0000000..b364699 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java @@ -0,0 +1,408 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.BACKUP_INTERVAL_SETTING; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.SETUP_COMPLETED_SETTING; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.PARTIAL; + +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.BackupArchive; +import wellatleastitried.mediagarrdServer.model.BackupRunResult; +import wellatleastitried.mediagarrdServer.repository.BackupRecordRepository; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; +import wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils; + +class BackupScheduleServiceTest { + + @TempDir + Path tempDir; + + private MediaGarrdProperties properties; + private TestDatabase db; + private MutableClock clock; + private SetupService setup; + + @BeforeEach + void setUp() { + properties = new MediaGarrdProperties(); + properties.setDatabasePath(tempDir.resolve("mediagarrd.db").toString()); + db = new TestDatabase(properties); + clock = new MutableClock(); + setup = newSetup(); + } + + private BackupScheduleService service() { + return new BackupScheduleService(properties, db.settings, db.backups, setup, clock); + } + + private void recordBackup(String id, String status, Instant startedAt) { + String start = MediaGarrdUtils.formatTime(startedAt); + BackupArchive archive = "failed".equals(status) ? null + : new BackupArchive(id, id + ".zip", Path.of(id + ".zip"), 0, startedAt); + db.backups.addNewBackupRecord(new BackupRunResult(id, start, start, status, List.of(), archive, null)); + } + + private void completeSetup() { + db.settings.saveSetting(SETUP_COMPLETED_SETTING, "2026-11-19 09:00:00"); + setup = newSetup(); + } + + private SetupService newSetup() { + return new SetupService(db.settings, db.pairedClients, false, clock); + } + + @Test + void updatesAndEvaluatesDueState() { + BackupScheduleService service = service(); + service.updateInterval(Duration.ofMinutes(15)); + + assertEquals(Duration.ofMinutes(15), service.getInterval()); + assertFalse(service.dueNow()); + + clock.advance(Duration.ofMinutes(15)); + + assertTrue(service.dueNow()); + } + + @Test + void notDueUntilIntervalElapses() { + properties.setBackupInterval(Duration.ofHours(1)); + BackupScheduleService service = service(); + + assertFalse(service.dueNow()); + + clock.advance(Duration.ofMinutes(59)); + assertFalse(service.dueNow()); + + clock.advance(Duration.ofMinutes(1)); + assertTrue(service.dueNow()); + } + + @Test + void persistsUpdatedIntervalAcrossRestarts() { + properties.setBackupInterval(Duration.ofHours(3)); + BackupScheduleService first = service(); + assertEquals(Duration.ofHours(3), first.getInterval()); + + first.updateInterval(Duration.ofMinutes(45)); + + assertEquals(Optional.of("PT45M"), db.settings.fetchSetting(BACKUP_INTERVAL_SETTING)); + assertEquals(Duration.ofMinutes(45), service().getInterval()); + } + + @Test + void aRestartRunsAnOverdueBackupRightAway() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + recordBackup("run-1", COMPLETED, clock.instant().minus(Duration.ofHours(13))); + + BackupScheduleService restarted = service(); + + assertTrue(restarted.dueNow()); + assertEquals(clock.instant(), restarted.getNextRun()); + } + + @Test + void aRestartKeepsTheOriginalDueTimeWhenNotYetDue() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + Instant last = clock.instant().minus(Duration.ofHours(5)); + recordBackup("run-1", PARTIAL, last); + + BackupScheduleService restarted = service(); + + assertFalse(restarted.dueNow()); + assertEquals(last.plus(Duration.ofHours(12)), restarted.getNextRun()); + clock.advance(Duration.ofHours(7)); + assertTrue(restarted.dueNow()); + } + + @Test + void aSuccessfulBackupAnchorsEvenWhenSetupIsNotCompleted() { + properties.setBackupInterval(Duration.ofHours(12)); + recordBackup("run-1", COMPLETED, clock.instant().minus(Duration.ofHours(13))); + + assertTrue(service().dueNow()); + } + + @Test + void noBackupEverIsDueNowOnceSetupIsCompleted() { + completeSetup(); + + assertTrue(service().dueNow()); + } + + @Test + void failedBackupsDoNotCount() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + recordBackup("failed-1", FAILED, clock.instant().minus(Duration.ofHours(1))); + + assertTrue(service().dueNow()); + } + + @Test + void aFailedBackupAfterASuccessfulOneIsIgnored() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + Instant good = clock.instant().minus(Duration.ofHours(2)); + recordBackup("run-1", COMPLETED, good); + recordBackup("failed-1", FAILED, clock.instant().minus(Duration.ofHours(1))); + + assertEquals(good.plus(Duration.ofHours(12)), service().getNextRun()); + } + + @Test + void noBackupEverWaitsAnIntervalWhileSetupIsNotCompleted() { + properties.setBackupInterval(Duration.ofHours(12)); + + BackupScheduleService service = service(); + + assertFalse(service.dueNow()); + assertEquals(clock.instant().plus(Duration.ofHours(12)), service.getNextRun()); + } + + @Test + void completingSetupMakesTheFirstBackupDue() { + properties.setBackupInterval(Duration.ofHours(12)); + BackupScheduleService service = service(); + assertFalse(service.dueNow()); + + setup.complete(); + + assertTrue(service.dueNow()); + } + + @Test + void aBackupDateInTheFutureIsDueNow() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + recordBackup("run-1", COMPLETED, clock.instant().plus(Duration.ofDays(3))); + + BackupScheduleService restarted = service(); + + assertTrue(restarted.dueNow()); + assertEquals(clock.instant(), restarted.getNextRun()); + } + + @Test + void changingTheIntervalRecomputesFromTheLastBackup() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + Instant last = clock.instant().minus(Duration.ofHours(5)); + recordBackup("run-1", COMPLETED, last); + BackupScheduleService service = service(); + + service.updateInterval(Duration.ofHours(24)); + assertEquals(last.plus(Duration.ofHours(24)), service.getNextRun()); + assertFalse(service.dueNow()); + + service.updateInterval(Duration.ofHours(2)); + assertEquals(clock.instant(), service.getNextRun()); + assertTrue(service.dueNow()); + } + + @Test + void changingTheIntervalWithoutABackupFollowsSetupState() { + BackupScheduleService beforeSetup = service(); + beforeSetup.updateInterval(Duration.ofHours(2)); + assertEquals(clock.instant().plus(Duration.ofHours(2)), beforeSetup.getNextRun()); + + completeSetup(); + BackupScheduleService afterSetup = service(); + afterSetup.updateInterval(Duration.ofHours(2)); + assertEquals(clock.instant(), afterSetup.getNextRun()); + } + + @Test + void changingTheIntervalDuringARunDoesNotMakeAnotherRunDue() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + recordBackup("run-1", COMPLETED, clock.instant().minus(Duration.ofHours(13))); + BackupScheduleService service = service(); + assertTrue(service.dueNow()); + service.markRunStarted(); + + service.updateInterval(Duration.ofHours(6)); + + assertFalse(service.dueNow()); + assertEquals(clock.instant().plus(Duration.ofHours(6)), service.getNextRun()); + } + + @Test + void changingTheIntervalAfterAFailedRunWaitsAFullInterval() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + BackupScheduleService service = service(); + service.markRunStarted(); + clock.advance(Duration.ofMinutes(10)); + + service.updateInterval(Duration.ofHours(1)); + + assertFalse(service.dueNow()); + assertEquals(clock.instant().plus(Duration.ofMinutes(50)), service.getNextRun()); + } + + @Test + void aNewerRecordedBackupWinsOverAnEarlierRunStart() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + BackupScheduleService service = service(); + service.markRunStarted(); + clock.advance(Duration.ofHours(1)); + Instant recorded = clock.instant(); + recordBackup("run-1", COMPLETED, recorded); + + service.updateInterval(Duration.ofHours(3)); + + assertEquals(recorded.plus(Duration.ofHours(3)), service.getNextRun()); + } + + @Test + void anUnreadableBackupHistoryFallsBackToAFullInterval() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + BackupRecordRepository broken = mock(BackupRecordRepository.class); + when(broken.fetchLastSuccessfulStartTime()).thenThrow(new IllegalStateException("database unavailable")); + + BackupScheduleService service = new BackupScheduleService(properties, db.settings, broken, setup, clock); + + assertFalse(service.dueNow()); + assertEquals(clock.instant().plus(Duration.ofHours(12)), service.getNextRun()); + } + + @Test + void outOfRangeIntervalsAreRejectedAndChangeNothing() { + BackupScheduleService service = service(); + service.updateInterval(Duration.ofHours(3)); + Instant nextRun = service.getNextRun(); + String message = "Backup interval must be between 15 minutes and 365 days"; + + for (Duration bad : new Duration[] {null, Duration.ZERO, Duration.ofMinutes(-5), Duration.ofMinutes(15).minusSeconds(1), + Duration.ofSeconds(1), Duration.ofDays(365).plusSeconds(1), Duration.ofMinutes(600000000000000L), Duration.ofSeconds(Long.MAX_VALUE)}) { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> service.updateInterval(bad)); + assertEquals(message, e.getMessage()); + } + + assertEquals(Duration.ofHours(3), service.getInterval()); + assertEquals(nextRun, service.getNextRun()); + assertEquals(Duration.ofHours(3).toString(), db.settings.fetchSetting(BACKUP_INTERVAL_SETTING).orElseThrow()); + } + + @Test + void boundaryIntervalsAreAccepted() { + BackupScheduleService service = service(); + + assertEquals(Duration.ofMinutes(15), service.updateInterval(Duration.ofMinutes(15))); + assertEquals(Duration.ofDays(365), service.updateInterval(Duration.ofDays(365))); + service.markRunStarted(); + service.deferNextRun(); + assertEquals(clock.instant().plus(Duration.ofDays(365)), service.getNextRun()); + assertEquals(Duration.ofDays(365).toString(), db.settings.fetchSetting(BACKUP_INTERVAL_SETTING).orElseThrow()); + } + + @Test + void ignoresOutOfRangeStoredIntervalAndStartsWithARecordedBackup() { + properties.setBackupInterval(Duration.ofHours(2)); + recordBackup("last", COMPLETED, clock.instant().minus(Duration.ofHours(1))); + + for (String stored : new String[] {"PT600000000000000M", "PT14M", "P366D", "PT1S"}) { + db.settings.saveSetting(BACKUP_INTERVAL_SETTING, stored); + BackupScheduleService service = service(); + assertEquals(Duration.ofHours(2), service.getInterval()); + assertEquals(clock.instant().plus(Duration.ofHours(1)), service.getNextRun()); + } + } + + @Test + void outOfRangeEnvironmentDefaultFallsBackToTwelveHours() { + recordBackup("last", COMPLETED, clock.instant().minus(Duration.ofHours(1))); + + for (Duration bad : new Duration[] {Duration.ofMinutes(5), Duration.ofDays(400), Duration.ofMinutes(600000000000000L), Duration.ZERO, null}) { + properties.setBackupInterval(bad); + BackupScheduleService service = service(); + assertEquals(Duration.ofHours(12), service.getInterval()); + assertEquals(clock.instant().plus(Duration.ofHours(11)), service.getNextRun()); + } + } + + @Test + void acceptsBoundaryValuesFromStorageAndEnvironment() { + db.settings.saveSetting(BACKUP_INTERVAL_SETTING, "PT15M"); + assertEquals(Duration.ofMinutes(15), service().getInterval()); + db.settings.saveSetting(BACKUP_INTERVAL_SETTING, "P365D"); + assertEquals(Duration.ofDays(365), service().getInterval()); + + db.settings.saveSetting(BACKUP_INTERVAL_SETTING, "junk"); + properties.setBackupInterval(Duration.ofDays(365)); + assertEquals(Duration.ofDays(365), service().getInterval()); + } + + @Test + void ignoresCorruptStoredInterval() { + properties.setBackupInterval(Duration.ofHours(2)); + db.settings.saveSetting(BACKUP_INTERVAL_SETTING, "every tuesday"); + assertEquals(Duration.ofHours(2), service().getInterval()); + + db.settings.saveSetting(BACKUP_INTERVAL_SETTING, "PT0S"); + assertEquals(Duration.ofHours(2), service().getInterval()); + } + + @Test + void deferringTheNextRunStopsItBeingDueUntilTheIntervalElapses() { + BackupScheduleService service = service(); + service.updateInterval(Duration.ofMinutes(15)); + clock.advance(Duration.ofMinutes(15)); + assertTrue(service.dueNow()); + + service.updateInterval(Duration.ofHours(1)); + clock.advance(Duration.ofMinutes(10)); + service.deferNextRun(); + + assertFalse(service.dueNow()); + Instant expected = clock.instant().plus(Duration.ofHours(1)); + assertEquals(expected, service.getNextRun()); + + clock.advance(Duration.ofHours(1)); + assertTrue(service.dueNow()); + } + + @Test + void addingAServiceAfterADeferralMakesTheScheduleDueNow() { + BackupScheduleService service = service(); + service.deferNextRun(); + assertFalse(service.dueNow()); + + service.releaseDeferral(); + + assertTrue(service.dueNow()); + } + + @Test + void releasingWithoutADeferralChangesNothing() { + BackupScheduleService service = service(); + Instant before = service.getNextRun(); + + service.releaseDeferral(); + + assertEquals(before, service.getNextRun()); + assertFalse(service.dueNow()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java new file mode 100644 index 0000000..47a680b --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java @@ -0,0 +1,76 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class ContainerEnvironmentTest { + + private static final String ID = "0123456789abcdef".repeat(4); + + @TempDir + Path tempDir; + + @Test + void findsTheContainerIdFromTheHostnameMountEvenWhenHostnameIsWrong() throws Exception { + ContainerEnvironment environment = environment(mountInfo( + "1 2 0:1 / / rw - overlay overlay rw", + "3 1 8:1 /var/lib/docker/containers/" + ID + "/resolv.conf /etc/resolv.conf rw - ext4 /dev/sda1 rw", + "4 1 8:1 /var/lib/docker/containers/" + ID + "/hostname /etc/hostname rw - ext4 /dev/sda1 rw"), "my-host"); + + assertTrue(environment.insideContainer()); + assertEquals(List.of(ID), environment.containerIdCandidates()); + } + + @Test + void findsRootlessDockerContainers() throws Exception { + String line = "4 1 8:1 /home/u/.local/share/docker/containers/" + ID + "/hostname /etc/hostname rw - ext4 /dev/sda1 rw"; + + assertEquals(List.of(ID), environment(mountInfo(line), null).containerIdCandidates()); + } + + @Test + void ignoresContainerPathsMountedSomewhereElse() throws Exception { + ContainerEnvironment environment = environment(mountInfo( + "4 1 8:1 /var/lib/docker/containers/" + ID + "/hostname /srv/other rw - ext4 /dev/sda1 rw"), null); + + assertFalse(environment.insideContainer()); + assertEquals(List.of(), environment.containerIdCandidates()); + } + + @Test + void fallsBackToTheHostnameOnly() throws Exception { + ContainerEnvironment environment = environment(mountInfo("1 2 0:1 / / rw - ext4 /dev/sda1 rw"), " abc123 "); + + assertEquals(List.of("abc123"), environment.containerIdCandidates()); + } + + @Test + void aMarkerFileMeansInsideAContainer() throws Exception { + Path marker = Files.createFile(tempDir.resolve(".dockerenv")); + ContainerEnvironment environment = new ContainerEnvironment(tempDir.resolve("missing"), List.of(marker), () -> null); + + assertTrue(environment.insideContainer()); + assertEquals(List.of(), environment.containerIdCandidates()); + } + + @Test + void notInsideAContainerWithoutMarkersOrMountedHostFiles() throws Exception { + assertFalse(environment(mountInfo("1 2 0:1 / / rw - ext4 /dev/sda1 rw"), "host").insideContainer()); + } + + private Path mountInfo(String... lines) throws Exception { + return Files.write(tempDir.resolve("mountinfo"), List.of(lines)); + } + + private ContainerEnvironment environment(Path mountInfo, String hostname) { + return new ContainerEnvironment(mountInfo, List.of(tempDir.resolve("no-marker")), () -> hostname); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/CoveredSymlinkTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/CoveredSymlinkTest.java new file mode 100644 index 0000000..facaf5b --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/CoveredSymlinkTest.java @@ -0,0 +1,97 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.dir; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.file; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.link; +import static wellatleastitried.mediagarrdServer.service.ServiceBackupRunnerTest.tar; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.compress.archivers.tar.TarConstants; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +@Timeout(120) +class CoveredSymlinkTest { + + private static final ZipCompression COMPRESSION = new ZipCompression(1); + + @TempDir + Path dir; + + private Path owner(String name, ServiceBackupRunner.ArchiveResult[] result, ServiceBackupRunnerTest.Item... items) throws Exception { + Path part = dir.resolve(name + ".part"); + result[0] = ServiceBackupRunner.archive(tar(items), "/srv/a", part, COMPRESSION, Set.of(), Set.of("srv/a/covered")); + return part; + } + + private Path fallback(String hostPath, ServiceBackupRunnerTest.Item... items) throws Exception { + Path part = dir.resolve("fallback.part"); + ServiceBackupRunner.archive(tar(items), hostPath, part, COMPRESSION, Set.of(), Set.of()); + return part; + } + + private void extract(Path archive, Path target) throws Exception { + assumeTrue(ArchiveTestSupport.available("bsdtar")); + Files.createDirectories(target); + ArchiveTestSupport.run(null, "bsdtar", "-xpf", archive.toString(), "-C", target.toString()); + Path streamed = dir.resolve("streamed"); + Files.createDirectories(streamed); + ArchiveTestSupport.run(archive, "bsdtar", "-xpf", "-", "-C", streamed.toString()); + assertEquals(Files.isSymbolicLink(target.resolve("srv/a/other")), Files.isSymbolicLink(streamed.resolve("srv/a/other"))); + } + + @Test + void aSymlinkToAFileAtACoveredPathIsLeftOutAndTheRealFileTakesItsName() throws Exception { + var result = new ServiceBackupRunner.ArchiveResult[1]; + Path ownerPart = owner("owner", result, dir("a/"), file("a/keep", "k"), link("a/covered", TarConstants.LF_SYMLINK, "/mnt/x"), + link("a/other", TarConstants.LF_SYMLINK, "keep")); + Path fallbackPart = fallback("/srv/a/covered", file("covered", "real")); + + assertTrue(result[0].confirmed().isEmpty()); + Path archive = ArchiveTestSupport.merge(dir, ownerPart, fallbackPart); + Map contents = ArchiveTestSupport.contents(archive); + assertEquals("real", contents.get("srv/a/covered")); + assertEquals("keep", contents.get("srv/a/other")); + Path target = dir.resolve("restored"); + extract(archive, target); + assertEquals("real", Files.readString(target.resolve("srv/a/covered"))); + assertFalse(Files.isSymbolicLink(target.resolve("srv/a/covered"))); + assertTrue(Files.isSymbolicLink(target.resolve("srv/a/other"))); + assertEquals("keep", Files.readSymbolicLink(target.resolve("srv/a/other")).toString()); + } + + @Test + void aSymlinkToADirectoryAtACoveredPathIsLeftOutAndTheRealDirectoryIsRestored() throws Exception { + var result = new ServiceBackupRunner.ArchiveResult[1]; + Path ownerPart = owner("owner", result, dir("a/"), file("a/keep", "k"), link("a/covered", TarConstants.LF_SYMLINK, "/mnt/dir")); + Path fallbackPart = fallback("/srv/a/covered", dir("covered/"), file("covered/data", "real")); + + assertTrue(result[0].confirmed().isEmpty()); + Path archive = ArchiveTestSupport.merge(dir, ownerPart, fallbackPart); + Map contents = ArchiveTestSupport.contents(archive); + assertFalse(contents.containsKey("srv/a/covered")); + assertTrue(contents.containsKey("srv/a/covered/")); + assertEquals("real", contents.get("srv/a/covered/data")); + Path target = dir.resolve("restored"); + extract(archive, target); + assertTrue(Files.isDirectory(target.resolve("srv/a/covered"), java.nio.file.LinkOption.NOFOLLOW_LINKS)); + assertEquals("real", Files.readString(target.resolve("srv/a/covered/data"))); + } + + @Test + void aSymlinkAtANameThatIsNotCoveredIsStillStoredAsASymlink() throws Exception { + var result = new ServiceBackupRunner.ArchiveResult[1]; + Path ownerPart = owner("owner", result, dir("a/"), link("a/other", TarConstants.LF_SYMLINK, "/mnt/x")); + + assertEquals("/mnt/x", ArchiveTestSupport.partContents(dir, ownerPart).get("srv/a/other")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java new file mode 100644 index 0000000..c8a74b2 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java @@ -0,0 +1,146 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.Volume; + +class DatabaseHostPathResolverTest { + + @TempDir + Path tempDir; + + private final DockerService docker = mock(DockerService.class); + private final ContainerEnvironment environment = mock(ContainerEnvironment.class); + private final DatabaseHostPathResolver resolver = new DatabaseHostPathResolver(docker, environment); + + private Path database; + private Path databaseDirectory; + + @BeforeEach + void setUp() throws Exception { + databaseDirectory = Files.createDirectories(tempDir.toRealPath().resolve("db")); + database = Files.createFile(databaseDirectory.resolve("mediagarrd.db")); + when(environment.insideContainer()).thenReturn(true); + when(environment.containerIdCandidates()).thenReturn(List.of("abc")); + } + + @Test + void usesThePathAsIsOutsideAContainer() throws Exception { + when(environment.insideContainer()).thenReturn(false); + + assertEquals(database, resolver.resolve(database)); + + verify(docker, never()).mountsOf(anyString()); + } + + @Test + void mapsThroughABindMount() throws Exception { + when(docker.mountsOf("abc")).thenReturn(List.of(mount(databaseDirectory.toString(), "/home/u/data/server/db"))); + + assertEquals(Path.of("/home/u/data/server/db/mediagarrd.db"), resolver.resolve(database)); + } + + @Test + void picksTheLongestMatchingMount() throws Exception { + when(docker.mountsOf("abc")).thenReturn(List.of( + mount(tempDir.toRealPath().toString(), "/outer"), + mount(databaseDirectory.toString(), "/inner"), + mount("/", "/rootfs"))); + + assertEquals(Path.of("/inner/mediagarrd.db"), resolver.resolve(database)); + } + + @Test + void doesNotMatchASiblingWithTheSamePrefix() throws Exception { + Path sibling = Files.createDirectories(tempDir.toRealPath().resolve("dbx")); + when(docker.mountsOf("abc")).thenReturn(List.of(mount(sibling.toString(), "/elsewhere"))); + + IOException e = assertThrows(IOException.class, () -> resolver.resolve(database)); + + assertTrue(e.getMessage().contains("no mount covers")); + } + + @Test + void mapsAMountOfTheDatabaseFileItself() throws Exception { + when(docker.mountsOf("abc")).thenReturn(List.of(mount(database.toString(), "/home/u/mediagarrd.db"))); + + assertEquals(Path.of("/home/u/mediagarrd.db"), resolver.resolve(database)); + } + + @Test + void failsForAMountWithoutAHostSource() { + when(docker.mountsOf("abc")).thenReturn(List.of(mount(databaseDirectory.toString(), ""))); + + IOException e = assertThrows(IOException.class, () -> resolver.resolve(database)); + + assertTrue(e.getMessage().contains("no host source")); + } + + @Test + void failsWhenTheDatabaseIsInTheWritableLayer() { + when(docker.mountsOf("abc")).thenReturn(List.of(mount("/tmp/else", "/home/u/else"))); + + assertThrows(IOException.class, () -> resolver.resolve(database)); + } + + @Test + void failsWhenInspectThrows() { + when(docker.mountsOf("abc")).thenThrow(new NotFoundException("gone")); + + IOException e = assertThrows(IOException.class, () -> resolver.resolve(database)); + + assertTrue(e.getMessage().contains("gone")); + } + + @Test + void failsWhenTheContainerIdIsUnknown() { + when(environment.containerIdCandidates()).thenReturn(List.of()); + + assertThrows(IOException.class, () -> resolver.resolve(database)); + } + + @Test + void failsWhenTheSourceIsNotAbsolute() { + when(docker.mountsOf("abc")).thenReturn(List.of(mount(databaseDirectory.toString(), "relative/db"))); + + assertThrows(IOException.class, () -> resolver.resolve(database)); + } + + @Test + void fallsBackToTheNextCandidateWhenTheFirstDoesNotCoverTheDatabase() throws Exception { + when(environment.containerIdCandidates()).thenReturn(List.of("host-name", "abc")); + when(docker.mountsOf("host-name")).thenThrow(new NotFoundException("no such container")); + when(docker.mountsOf("abc")).thenReturn(List.of(mount(databaseDirectory.toString(), "/home/u/db"))); + + assertEquals(Path.of("/home/u/db/mediagarrd.db"), resolver.resolve(database)); + } + + @Test + void failsWhenTheDatabaseFileDoesNotExist() throws Exception { + Files.delete(database); + + assertThrows(IOException.class, () -> resolver.resolve(database)); + } + + private static InspectContainerResponse.Mount mount(String destination, String source) { + return new InspectContainerResponse.Mount().withDestination(new Volume(destination)).withSource(source); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseRebuildHandlerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseRebuildHandlerTest.java new file mode 100644 index 0000000..232be0d --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseRebuildHandlerTest.java @@ -0,0 +1,184 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.concurrent.CompletableFuture; +import java.util.function.BooleanSupplier; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.dto.PairResponse; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; + +class DatabaseRebuildHandlerTest { + + @TempDir + Path tempDir; + + private final MutableClock clock = new MutableClock(); + private Path databaseFile; + private TestDatabase db; + private SetupService setup; + private RunStatusBroadcaster broadcaster; + private PairingService pairing; + private BackupArchiveService archives; + private BackupScheduleService schedule; + private Path defaultRoot; + + @BeforeEach + void setUp() { + MediaGarrdProperties properties = new MediaGarrdProperties(); + databaseFile = tempDir.resolve("mediagarrd.db"); + properties.setDatabasePath(databaseFile.toString()); + defaultRoot = tempDir.resolve("default-backups"); + properties.setBackupRoot(defaultRoot.toString()); + db = new TestDatabase(properties); + broadcaster = new RunStatusBroadcaster(); + setup = new SetupService(db.settings, db.pairedClients, false, clock); + pairing = new PairingService(setup, db.pairedClients, broadcaster, clock); + archives = new BackupArchiveService(properties, db.settings, db.backups); + schedule = new BackupScheduleService(properties, db.settings, db.backups, setup, clock); + new DatabaseRebuildHandler(db.database, pairing, broadcaster, archives, schedule); + } + + @AfterEach + void drainRebuildNotifier() { + db.database.shutdownRebuildNotifier(); + } + + private void corruptWhileRunning() throws Exception { + Files.writeString(databaseFile, "x".repeat(4096)); + db.settings.fetchSetting("anything"); + } + + private static void await(BooleanSupplier condition) throws Exception { + long deadline = System.nanoTime() + Duration.ofSeconds(10).toNanos(); + while (!condition.getAsBoolean()) { + if (System.nanoTime() > deadline) { + throw new AssertionError("Condition not met in time"); + } + Thread.sleep(10); + } + } + + private PairResponse pairConfirmed(String name) { + PairResponse response = pairing.pair(setup.currentPin(), name); + assertTrue(pairing.authenticate(response.token()).isPresent()); + return response; + } + + @Test + void aRuntimeRebuildReopensSetupLikeARestartOnAFreshDatabase() throws Exception { + setup.complete(); + PairResponse client = pairConfirmed("Laptop"); + pairing.createCode(); + assertEquals(1, db.pairedClients.countPairedClients()); + + corruptWhileRunning(); + await(() -> !setup.isCompleted()); + + assertEquals(0, db.pairedClients.countPairedClients()); + assertFalse(setup.isPairingOpen()); + String pin = setup.currentPin(); + assertNotNull(pin); + assertTrue(pairing.authenticate(client.token()).isEmpty()); + String session = setup.startSession(pin).orElseThrow(); + assertTrue(setup.canConfigure(session)); + } + + @Test + void theBackupLocationRetentionAndScheduleAreReloadedFromTheNewDatabase() throws Exception { + setup.complete(); + archives.updateSettings(tempDir.resolve("custom-backups").toString(), 7); + schedule.updateInterval(Duration.ofHours(3)); + assertEquals(7, archives.retentionCount()); + assertEquals(Duration.ofHours(3), schedule.getInterval()); + + corruptWhileRunning(); + await(() -> !setup.isCompleted()); + await(() -> archives.rootDirectory().equals(defaultRoot.toAbsolutePath().normalize())); + await(() -> !Duration.ofHours(3).equals(schedule.getInterval())); + + assertEquals(new MediaGarrdProperties().getRetentionCount(), archives.retentionCount()); + assertEquals(new MediaGarrdProperties().getBackupInterval(), schedule.getInterval()); + } + + @Test + void aPendingPairingFromBeforeTheRebuildCannotConfirmAfterwards() throws Exception { + setup.complete(); + PairResponse pending = pairing.pair(setup.currentPin(), "Phone"); + + corruptWhileRunning(); + await(() -> !setup.isCompleted()); + setup.complete(); + + assertTrue(pairing.authenticate(pending.token()).isEmpty()); + assertEquals(0, db.pairedClients.countPairedClients()); + } + + @Test + void aLockoutFromBeforeTheRebuildIsCleared() throws Exception { + setup.complete(); + for (int i = 0; i < SetupService.MAX_FAILED_ATTEMPTS; i++) { + assertThrows(PairingException.class, () -> pairing.pair("000000", null)); + } + assertThrows(LockedOutException.class, () -> pairing.pair("000000", null)); + + corruptWhileRunning(); + await(() -> !setup.isCompleted()); + + assertTrue(setup.startSession(setup.currentPin()).isPresent()); + } + + @Test + void openEventStreamsAreClosedButNewOnesStillWork() throws Exception { + broadcaster.subscribe(new SseEmitter(60_000L)); + assertEquals(1, broadcaster.subscriberCount()); + + corruptWhileRunning(); + await(() -> broadcaster.subscriberCount() == 0); + + broadcaster.subscribe(new SseEmitter(60_000L)); + assertEquals(1, broadcaster.subscriberCount()); + broadcaster.shutdown(); + } + + @Test + void theRebuildDoesNotWaitForTheSetupServiceMonitorOrAQueuedSnapshot() throws Exception { + setup.complete(); + Path snapshot = tempDir.resolve("snapshot.db"); + Files.writeString(databaseFile, "x".repeat(4096)); + + CompletableFuture rebuild; + CompletableFuture snapshotting; + synchronized (setup) { + rebuild = CompletableFuture.runAsync(() -> db.settings.fetchSetting("anything")); + assertTimeoutPreemptively(Duration.ofSeconds(10), () -> rebuild.get()); + snapshotting = CompletableFuture.runAsync(() -> { + try { + db.database.snapshotTo(snapshot); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }); + assertTimeoutPreemptively(Duration.ofSeconds(10), () -> snapshotting.get()); + assertTrue(setup.isCompleted()); + } + + await(() -> !setup.isCompleted()); + assertTrue(Files.isRegularFile(snapshot)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java new file mode 100644 index 0000000..02a00bb --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java @@ -0,0 +1,134 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.COMPLETED; +import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseUtils.Status.FAILED; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.sql.DriverManager; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.compress.archivers.zip.X7875_NewUnix; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipFile; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; + +class DatabaseSnapshotServiceTest { + + private static final Path HOST_DATABASE = Path.of("/srv/mediagarrd/db/mediagarrd.db"); + + @TempDir + Path tempDir; + + private TestDatabase db; + private DatabaseHostPathResolver hostPaths; + private DatabaseSnapshotService snapshots; + private Path run; + + @BeforeEach + void setUp() throws Exception { + MediaGarrdProperties properties = new MediaGarrdProperties(); + properties.setDatabasePath(tempDir.resolve("db/mediagarrd.db").toString()); + db = new TestDatabase(properties); + hostPaths = mock(DatabaseHostPathResolver.class); + when(hostPaths.resolve(db.database.databaseFile())).thenReturn(HOST_DATABASE); + snapshots = new DatabaseSnapshotService(db.database, hostPaths, new ZipCompression(1)); + run = Files.createDirectories(tempDir.resolve("run")); + } + + @Test + void writesTheSnapshotAtTheHostPathWithTheLiveFileMetadata() throws Exception { + db.services.addService(new ServiceDefinition("radarr", List.of("/srv/radarr"))); + Files.setPosixFilePermissions(db.database.databaseFile(), PosixFilePermissions.fromString("rw-r-----")); + Integer uid = (Integer) Files.getAttribute(db.database.databaseFile(), "unix:uid"); + Integer gid = (Integer) Files.getAttribute(db.database.databaseFile(), "unix:gid"); + + BackupServiceResult result = snapshots.snapshot(run); + + assertEquals(COMPLETED, result.status()); + assertEquals(DatabaseSnapshotService.SERVICE_NAME, result.serviceName()); + Path part = run.resolve(DatabaseSnapshotService.PART_DIRECTORY).resolve(DatabaseSnapshotService.PART_NAME); + try (ZipFile zip = ZipFile.builder().setPath(ArchiveTestSupport.merge(tempDir, part)).get()) { + assertEquals(List.of("srv/mediagarrd/db/mediagarrd.db"), Collections.list(zip.getEntries()).stream().map(ZipArchiveEntry::getName).toList()); + ZipArchiveEntry entry = zip.getEntry("srv/mediagarrd/db/mediagarrd.db"); + assertEquals(0640, entry.getUnixMode() & 07777); + X7875_NewUnix owner = (X7875_NewUnix) entry.getExtraField(new X7875_NewUnix().getHeaderId()); + assertEquals(uid.longValue(), owner.getUID()); + assertEquals(gid.longValue(), owner.getGID()); + + Path extracted = tempDir.resolve("extracted.db"); + Files.copy(zip.getInputStream(entry), extracted); + try (var connection = DriverManager.getConnection("jdbc:sqlite:" + extracted); var statement = connection.createStatement()) { + assertEquals("ok", statement.executeQuery("PRAGMA quick_check").getString(1)); + assertEquals(2, statement.executeQuery("PRAGMA user_version").getInt(1)); + assertEquals("radarr", statement.executeQuery("SELECT name FROM services").getString(1)); + } + } + assertFalse(Files.exists(run.resolve(DatabaseSnapshotService.PART_DIRECTORY).resolve("snapshot.db"))); + } + + @Test + void failsWithoutAPartWhenTheHostPathCannotBeResolved() throws Exception { + when(hostPaths.resolve(db.database.databaseFile())).thenThrow(new IOException("no mount covers the database")); + + BackupServiceResult result = snapshots.snapshot(run); + + assertEquals(FAILED, result.status()); + assertEquals("no mount covers the database", result.errorMessage()); + assertNoPart(); + } + + @Test + void failsWithoutAPartWhenTheDatabaseIsMissing() throws Exception { + Files.delete(db.database.databaseFile()); + + BackupServiceResult result = snapshots.snapshot(run); + + assertEquals(FAILED, result.status()); + assertEquals("Database file " + db.database.databaseFile() + " does not exist", result.errorMessage()); + assertFalse(Files.exists(db.database.databaseFile())); + assertNoPart(); + } + + @Test + void failsWithoutAPartWhenTheDatabaseIsCorrupt() throws Exception { + Files.writeString(db.database.databaseFile(), "x".repeat(4096)); + + BackupServiceResult result = snapshots.snapshot(run); + + assertEquals(FAILED, result.status()); + assertEquals("x".repeat(4096), Files.readString(db.database.databaseFile())); + assertNoPart(); + } + + @Test + void resolverFailuresOfAnyKindBecomeAFailedResult() throws Exception { + when(hostPaths.resolve(db.database.databaseFile())).thenThrow(new IllegalStateException("docker down")); + + assertEquals("docker down", snapshots.snapshot(run).errorMessage()); + } + + private void assertNoPart() throws IOException { + Path directory = run.resolve(DatabaseSnapshotService.PART_DIRECTORY); + if (Files.exists(directory)) { + try (var files = Files.list(directory)) { + assertTrue(files.toList().isEmpty()); + } + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java new file mode 100644 index 0000000..2205276 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java @@ -0,0 +1,201 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.RETURNS_SELF; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CopyArchiveFromContainerCmd; +import com.github.dockerjava.api.command.CreateContainerCmd; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.InspectImageCmd; +import com.github.dockerjava.api.command.ListContainersCmd; +import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.api.command.PullImageResultCallback; +import com.github.dockerjava.api.command.RemoveContainerCmd; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.HostConfig; +import com.github.dockerjava.api.model.Mount; +import com.github.dockerjava.api.model.MountType; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.model.ServiceDefinition; + +class DockerServiceTest { + + private static final String IMAGE = "busybox:stable"; + private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr/config", "/srv/radarr/data")); + + private final DockerClient client = mock(DockerClient.class); + private final ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF); + private final CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF); + private final RemoveContainerCmd removeCmd = mock(RemoveContainerCmd.class, RETURNS_SELF); + private final InspectImageCmd inspectCmd = mock(InspectImageCmd.class); + private DockerService docker; + + @BeforeEach + void setUp() { + MediaGarrdProperties properties = new MediaGarrdProperties(); + properties.setHelperImage(IMAGE); + docker = new DockerService(client, properties); + + when(client.listContainersCmd()).thenReturn(listCmd); + when(client.createContainerCmd(IMAGE)).thenReturn(createCmd); + when(client.removeContainerCmd(anyString())).thenReturn(removeCmd); + when(client.inspectImageCmd(IMAGE)).thenReturn(inspectCmd); + CreateContainerResponse created = new CreateContainerResponse(); + created.setId("new-id"); + when(createCmd.exec()).thenReturn(created); + } + + @Test + void createsReadOnlyNetworklessHelperContainer() { + when(listCmd.exec()).thenReturn(List.of()); + + assertEquals("new-id", docker.containerFor(RADARR)); + + verify(listCmd).withLabelFilter(Map.of(DockerService.SERVICE_LABEL, "radarr")); + verify(createCmd).withName("mediagarrd-backup-radarr"); + verify(createCmd).withLabels(Map.of( + DockerService.SERVICE_LABEL, "radarr", + DockerService.CONFIG_HASH_LABEL, docker.configHash(RADARR))); + ArgumentCaptor hostConfig = ArgumentCaptor.forClass(HostConfig.class); + verify(createCmd).withHostConfig(hostConfig.capture()); + assertEquals("none", hostConfig.getValue().getNetworkMode()); + assertEquals( + List.of(bind("/srv/radarr/config"), bind("/srv/radarr/data")), + hostConfig.getValue().getMounts().stream().map(DockerServiceTest::describe).toList()); + verify(client, never()).startContainerCmd(anyString()); + } + + @Test + void reusesContainerWithMatchingConfigHash() { + Container existing = container("existing", docker.configHash(RADARR)); + when(listCmd.exec()).thenReturn(List.of(existing)); + + assertEquals("existing", docker.containerFor(RADARR)); + + verify(client, never()).createContainerCmd(anyString()); + verify(client, never()).removeContainerCmd(anyString()); + } + + @Test + void replacesContainerWhenConfigChanged() { + Container stale = container("stale", "old-hash"); + when(listCmd.exec()).thenReturn(List.of(stale)); + + assertEquals("new-id", docker.containerFor(RADARR)); + + verify(client).removeContainerCmd("stale"); + verify(removeCmd).withForce(true); + } + + @Test + void pullsHelperImageOnlyWhenMissing() throws Exception { + when(listCmd.exec()).thenReturn(List.of()); + when(inspectCmd.exec()).thenThrow(new NotFoundException("missing")); + PullImageCmd pullCmd = mock(PullImageCmd.class); + PullImageResultCallback callback = mock(PullImageResultCallback.class); + when(client.pullImageCmd(IMAGE)).thenReturn(pullCmd); + when(pullCmd.start()).thenReturn(callback); + when(callback.awaitCompletion(anyLong(), any(TimeUnit.class))).thenReturn(true); + + docker.containerFor(RADARR); + + verify(client).pullImageCmd(IMAGE); + } + + @Test + void failsWhenHelperImagePullTimesOut() throws Exception { + when(listCmd.exec()).thenReturn(List.of()); + when(inspectCmd.exec()).thenThrow(new NotFoundException("missing")); + PullImageCmd pullCmd = mock(PullImageCmd.class); + PullImageResultCallback callback = mock(PullImageResultCallback.class); + when(client.pullImageCmd(IMAGE)).thenReturn(pullCmd); + when(pullCmd.start()).thenReturn(callback); + when(callback.awaitCompletion(anyLong(), any(TimeUnit.class))).thenReturn(false); + + assertThrows(IllegalStateException.class, () -> docker.containerFor(RADARR)); + verify(client, never()).createContainerCmd(anyString()); + } + + @Test + void removeContainersNeverThrows() { + List containers = List.of(container("a", "x"), container("b", "y")); + when(listCmd.exec()).thenReturn(containers); + when(removeCmd.exec()).thenThrow(new NotFoundException("gone")).thenThrow(new RuntimeException("daemon down")); + + docker.removeContainers("radarr"); + + verify(client).removeContainerCmd("a"); + verify(client).removeContainerCmd("b"); + } + + @Test + void configHashDependsOnPathsNotTheirOrder() { + ServiceDefinition reordered = new ServiceDefinition("other", List.of("/srv/radarr/data", "/srv/radarr/config")); + ServiceDefinition changed = new ServiceDefinition("radarr", List.of("/srv/radarr/config")); + + assertEquals(docker.configHash(RADARR), docker.configHash(reordered)); + assertNotEquals(docker.configHash(RADARR), docker.configHash(changed)); + } + + @Test + void copyFromStreamsTheTarFromTheHelperContainerUnderTheMountRoot() { + CopyArchiveFromContainerCmd copyCmd = mock(CopyArchiveFromContainerCmd.class); + java.io.InputStream tar = new java.io.ByteArrayInputStream(new byte[] {1, 2, 3}); + when(client.copyArchiveFromContainerCmd("cid", "/mnt/srv/radarr/config")).thenReturn(copyCmd); + when(copyCmd.exec()).thenReturn(tar); + + assertSame(tar, docker.copyFrom("cid", "/srv/radarr/config")); + } + + private static Container container(String id, String hash) { + Container container = mock(Container.class); + when(container.getId()).thenReturn(id); + when(container.getLabels()).thenReturn(Map.of(DockerService.SERVICE_LABEL, "radarr", DockerService.CONFIG_HASH_LABEL, hash)); + return container; + } + + private static String bind(String hostPath) { + return MountType.BIND + " " + hostPath + " -> /mnt" + hostPath + " ro=true"; + } + + private static String describe(Mount mount) { + return mount.getType() + " " + mount.getSource() + " -> " + mount.getTarget() + " ro=" + mount.getReadOnly(); + } + + @Test + void removesEveryStaleContainerEvenWhenAMatchingOneComesFirst() { + Container match = container("match", docker.configHash(RADARR)); + Container staleAfter = container("stale-after", "old-hash"); + Container staleBefore = container("stale-before", "older-hash"); + when(listCmd.exec()).thenReturn(List.of(staleBefore, match, staleAfter)); + + assertEquals("match", docker.containerFor(RADARR)); + + verify(client).removeContainerCmd("stale-before"); + verify(client).removeContainerCmd("stale-after"); + verify(client, never()).removeContainerCmd("match"); + verify(client, never()).createContainerCmd(anyString()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/GeneratedTar.java b/src/test/java/wellatleastitried/mediagarrdServer/service/GeneratedTar.java new file mode 100644 index 0000000..a1330cd --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/GeneratedTar.java @@ -0,0 +1,107 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Date; +import java.util.Iterator; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; + +final class GeneratedTar extends InputStream { + + record Spec(String name, long size, byte[] pattern) { + + static Spec directory(String name) { + return new Spec(name, -1, null); + } + + static Spec file(String name, long size, byte[] pattern) { + return new Spec(name, size, pattern); + } + } + + private static final int BLOCK = 512; + + private final Iterator specs; + private final byte[] header = new byte[BLOCK]; + private int headerPosition = BLOCK; + private long contentRemaining; + private long contentOffset; + private byte[] pattern; + private int padding; + private int trailer = 2 * BLOCK; + + GeneratedTar(Iterator specs) { + this.specs = specs; + } + + @Override + public int read() throws IOException { + byte[] one = new byte[1]; + int read = read(one, 0, 1); + return read < 0 ? -1 : one[0] & 0xFF; + } + + @Override + public int read(byte[] target, int offset, int length) throws IOException { + if (length == 0) { + return 0; + } + while (true) { + if (headerPosition < BLOCK) { + int count = Math.min(length, BLOCK - headerPosition); + System.arraycopy(header, headerPosition, target, offset, count); + headerPosition += count; + return count; + } + if (contentRemaining > 0) { + int count = (int) Math.min(length, contentRemaining); + for (int i = 0; i < count; i++) { + target[offset + i] = pattern[(int) ((contentOffset + i) % pattern.length)]; + } + contentOffset += count; + contentRemaining -= count; + if (contentRemaining == 0) { + padding = (int) ((BLOCK - contentOffset % BLOCK) % BLOCK); + } + return count; + } + if (padding > 0) { + int count = Math.min(length, padding); + java.util.Arrays.fill(target, offset, offset + count, (byte) 0); + padding -= count; + return count; + } + if (specs.hasNext()) { + begin(specs.next()); + continue; + } + if (trailer > 0) { + int count = Math.min(length, trailer); + java.util.Arrays.fill(target, offset, offset + count, (byte) 0); + trailer -= count; + return count; + } + return -1; + } + } + + private void begin(Spec spec) { + TarArchiveEntry entry = new TarArchiveEntry(spec.name()); + entry.setModTime(new Date(1_700_000_000_000L)); + entry.setUserId(1000); + entry.setGroupId(1000); + if (spec.size() < 0) { + entry.setMode(040755); + } else { + entry.setMode(0100644); + entry.setSize(spec.size()); + } + java.util.Arrays.fill(header, (byte) 0); + entry.writeEntryHeader(header); + headerPosition = 0; + contentRemaining = Math.max(spec.size(), 0); + contentOffset = 0; + pattern = spec.pattern(); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/MutableClock.java b/src/test/java/wellatleastitried/mediagarrdServer/service/MutableClock.java new file mode 100644 index 0000000..8e7eab5 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/MutableClock.java @@ -0,0 +1,31 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; + +final class MutableClock extends Clock { + + private Instant now = Instant.parse("2026-11-19T10:00:00Z"); + + void advance(Duration duration) { + now = now.plus(duration); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now; + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/PairingServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/PairingServiceTest.java new file mode 100644 index 0000000..f96de2a --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/PairingServiceTest.java @@ -0,0 +1,663 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.dto.PairResponse; +import wellatleastitried.mediagarrdServer.dto.PairingCodeDto; +import wellatleastitried.mediagarrdServer.model.PairedClient; +import wellatleastitried.mediagarrdServer.repository.PairedClientRepository; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; + +class PairingServiceTest { + + private static final Pattern TOKEN = Pattern.compile("[A-Za-z0-9_-]{43}"); + + @TempDir + Path tempDir; + + private final MutableClock clock = new MutableClock(); + private MediaGarrdProperties properties; + private TestDatabase db; + private SetupService setup; + private RunStatusBroadcaster broadcaster; + private PairingService pairing; + + @BeforeEach + void setUp() { + properties = new MediaGarrdProperties(); + properties.setDatabasePath(tempDir.resolve("mediagarrd.db").toString()); + db = new TestDatabase(properties); + broadcaster = mock(RunStatusBroadcaster.class); + setup = new SetupService(db.settings, db.pairedClients, false, clock); + pairing = new PairingService(setup, db.pairedClients, broadcaster, clock); + } + + @Test + void pairingIsRefusedBeforeSetupCompletes() { + PairingException e = assertThrows(PairingException.class, () -> pairing.pair(setup.currentPin(), null)); + + assertEquals(PairingException.Reason.SETUP_INCOMPLETE, e.reason()); + assertEquals("This server has not finished setup yet. Finish it on the server's /config page, then pair.", e.getMessage()); + assertEquals(0, db.pairedClients.countPairedClients()); + } + + @Test + void theCorrectPinReturnsATokenAndStoresOnlyItsHash() { + setup.complete(); + + PairResponse response = pairing.pair(" " + setup.currentPin() + " ", "Laptop"); + + assertTrue(TOKEN.matcher(response.token()).matches(), response.token()); + assertEquals("Laptop", response.name()); + assertEquals(0, db.pairedClients.countPairedClients()); + + confirm(response); + + assertTrue(db.pairedClients.fetchPairedClientByTokenHash(PairingService.hashToken(response.token())).isPresent()); + assertTrue(db.pairedClients.fetchPairedClientByTokenHash(response.token()).isEmpty()); + assertEquals(1, db.pairedClients.countPairedClients()); + assertFalse(db.pairedClients.fetchPairedClients().toString().contains(response.token())); + } + + @Test + void tokensAreDistinctPerPairing() { + setup.complete(); + PairResponse first = pairing.pair(setup.currentPin(), "A"); + confirm(first); + String code = pairing.createCode().code(); + PairResponse second = pairing.pair(code, "B"); + confirm(second); + + assertNotEquals(first.token(), second.token()); + assertNotEquals(first.id(), second.id()); + assertEquals(2, db.pairedClients.countPairedClients()); + } + + @Test + void aConfirmedPairingClosesPairing() { + setup.complete(); + String pin = setup.currentPin(); + PairResponse response = pairing.pair(pin, null); + assertTrue(setup.isPairingOpen()); + assertEquals(pin, setup.currentPin()); + + confirm(response); + + assertFalse(setup.isPairingOpen()); + assertNull(setup.currentPin()); + PairingException e = assertThrows(PairingException.class, () -> pairing.pair(pin, null)); + + assertEquals(PairingException.Reason.CLOSED, e.reason()); + assertEquals(1, db.pairedClients.countPairedClients()); + } + + @Test + void aWrongPinIsInvalidAndCreatesNothing() { + setup.complete(); + + PairingException e = assertThrows(PairingException.class, () -> pairing.pair("not-it", null)); + + assertEquals(PairingException.Reason.INVALID, e.reason()); + assertEquals(0, db.pairedClients.countPairedClients()); + assertTrue(setup.isPairingOpen()); + } + + @Test + void wrongPinsLockPairingEvenForTheCorrectPin() { + setup.complete(); + for (int i = 0; i < SetupService.MAX_FAILED_ATTEMPTS; i++) { + assertThrows(PairingException.class, () -> pairing.pair("000000", null)); + } + + assertThrows(LockedOutException.class, () -> pairing.pair(setup.currentPin(), null)); + + clock.advance(SetupService.LOCK_DURATION.plusSeconds(1)); + confirm(pairing.pair(setup.currentPin(), null)); + assertEquals(1, db.pairedClients.countPairedClients()); + } + + @Test + void anExistingInstallWithoutClientsGetsAPinOnStart() { + setup.complete(); + SetupService restarted = new SetupService(db.settings, db.pairedClients, false, clock); + PairingService restartedPairing = new PairingService(restarted, db.pairedClients, broadcaster, clock); + + PairResponse response = restartedPairing.pair(restarted.currentPin(), null); + + assertTrue(TOKEN.matcher(response.token()).matches()); + assertTrue(restartedPairing.authenticate(response.token()).isPresent()); + } + + @Test + void openPairingFlagLetsAnotherClientPairWithANewPin() { + setup.complete(); + confirm(pairing.pair(setup.currentPin(), "First")); + SetupService restarted = new SetupService(db.settings, db.pairedClients, true, clock); + PairingService restartedPairing = new PairingService(restarted, db.pairedClients, broadcaster, clock); + + PairResponse second = restartedPairing.pair(restarted.currentPin(), "Second"); + assertTrue(restartedPairing.authenticate(second.token()).isPresent()); + + assertEquals(2, db.pairedClients.countPairedClients()); + } + + @Test + void namesAreValidatedAndGeneratedWhenMissing() { + setup.complete(); + + assertThrows(IllegalArgumentException.class, () -> pairing.pair(setup.currentPin(), "x".repeat(65))); + assertThrows(IllegalArgumentException.class, () -> pairing.pair(setup.currentPin(), "