diff --git a/.dockerignore b/.dockerignore index 7b657fc..6826209 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,9 @@ .git .github +.claude +.jj +ref +vendor .vscode build **/build @@ -17,7 +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/CHANGELOG b/CHANGELOG index 5fb07d1..479b93e 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,64 @@ # CHANGELOG +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 diff --git a/Dockerfile b/Dockerfile index 53332a9..85ec6f6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,6 +10,9 @@ 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", \ "-XX:+UseG1GC", \ "-Xms16m", \ diff --git a/README.md b/README.md index 15ecfeb..9d816f7 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ Full documentation, including configuration, archives and restoring, is on the [ - [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 @@ -26,13 +27,21 @@ 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, and its API is unauthenticated after setup. Do not expose its port to untrusted networks. +> **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 [MIT](./LICENSE) diff --git a/build.gradle.kts b/build.gradle.kts index c641e5f..afffa02 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,25 +1,22 @@ 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" -extra["httpclient5.version"] = "5.4.4" -extra["httpcore5.version"] = "5.3.4" - repositories { mavenCentral() } dependencies { testImplementation("org.springframework.boot:spring-boot-starter-test") - testImplementation("org.xerial:sqlite-jdbc:3.44.0.0") + 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.44.0.0") + 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") diff --git a/docs/API.md b/docs/API.md index f6743eb..f23cef3 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1,41 +1,107 @@ # Server API -All endpoints are under `/api/v1`. Errors are returned as `{"error": "..."}` with a matching status code. +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`. -## Status -| Endpoint | Returns | +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 | |---|---| -| `GET /health` | The server's health, whether a backup is running, the number of backups to keep, and the time between backups. | -| `GET /version` | The running version and the result of the daily check for a newer GitHub release. | -| `GET /events` | A Server-Sent Events stream that reports when backup runs start and finish and when archives or configuration change. | +| `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 | Returns | -|---|---| -| `GET /setup` | Whether first-time setup is finished and whether the caller holds a setup session. | -| `POST /setup/session` | An empty `204` and a setup session cookie when the posted PIN is correct. | -| `POST /setup/complete` | An empty `204` once setup is finished, after which the setup page is disabled. | +| 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. | +| `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. | +| `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. | +| `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 index 4e8cabc..acbe951 100644 --- a/docs/database.md +++ b/docs/database.md @@ -2,6 +2,8 @@ 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: ``` @@ -26,14 +28,14 @@ Never restore over the database of a running server. ```bash curl -fLO https://github.com/MediaGarrd/Recovery/releases/latest/download/mgrecover.sh chmod +x mgrecover.sh - ./mgrecover.sh -C restore .zip + 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 (they belong to you); step 3 copies the database back as root into the server's existing directory, which keeps its owner and mode. + `-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 - bsdtar -xpf .zip -C 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 @@ -48,4 +50,4 @@ Never restore over the database of a running server. 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 starts again with no settings or services. Restore a copy from the newest archive as above to get them back, or restart the server and use its new setup PIN to configure it again. +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 index 30dfbad..01605a2 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -5,16 +5,66 @@ Set these in `environment` in `docker-compose.yml`. Durations use ISO-8601, for | 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. Only the initial value: once it is saved through setup, the API, or the client, the stored value is used. | +| `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. diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java index 41ea9c5..b9a7254 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -21,4 +21,5 @@ public class MediaGarrdProperties { 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 index 2d12820..7d9e83c 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/WebMvcConfig.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/WebMvcConfig.java @@ -5,15 +5,18 @@ 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) { + public WebMvcConfig(SetupInterceptor setupInterceptor, ApiAuthInterceptor apiAuthInterceptor) { this.setupInterceptor = setupInterceptor; + this.apiAuthInterceptor = apiAuthInterceptor; } @Override @@ -23,6 +26,7 @@ public void addViewControllers(ViewControllerRegistry registry) { @Override public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(setupInterceptor); + 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 index fb33dbc..33c4dc6 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandler.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ApiExceptionHandler.java @@ -1,37 +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 wellatleastitried.mediagarrdServer.service.BackupOrchestratorService.BackupInProgressException; -import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService.RunRejectedException; +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 (status.is5xxServerError()) { + if (e instanceof BackupFailedException) { LOGGER.error("Request failed: {}", e.getMessage()); - } else { - LOGGER.warn("Rejected request: {}", 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).body(Map.of("error", Objects.requireNonNullElse(message, status.getReasonPhrase()))); + return ResponseEntity.status(status).contentType(MediaType.APPLICATION_JSON).body(Map.of("error", Objects.requireNonNullElse(message, status.getReasonPhrase()))); } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java index 0158ca2..1008f52 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java @@ -11,7 +11,7 @@ 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; @@ -19,20 +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 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") @@ -50,12 +53,17 @@ public BackupController(BackupArchiveService archiveService, BackupOrchestratorS this.broadcaster = broadcaster; } + @PublicEndpoint(tokenOptional = true) @GetMapping("/health") - public ServerStatusDto health() { + 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()); @@ -75,46 +83,44 @@ public List listBackups() { @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(); } @@ -139,20 +145,19 @@ 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); } } @@ -163,13 +168,4 @@ private ServerStatusDto status(Duration interval) { private BackupDto toDto(BackupArchive archive) { return new BackupDto(archive.id(), archive.fileName(), archive.sizeBytes(), archive.createdAt()); } - - 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); - } } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java index 420e896..f152815 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java @@ -1,9 +1,6 @@ package wellatleastitried.mediagarrdServer.api; -import static wellatleastitried.mediagarrdServer.api.ApiExceptionHandler.error; - import java.util.List; -import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,9 +20,10 @@ import wellatleastitried.mediagarrdServer.model.ServiceDefinition; import wellatleastitried.mediagarrdServer.service.BackupArchiveService; import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; -import wellatleastitried.mediagarrdServer.service.DatabaseService; -import wellatleastitried.mediagarrdServer.service.DockerService; +import wellatleastitried.mediagarrdServer.service.BackupRunLifecycle; import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.ServiceConfigService; +import wellatleastitried.mediagarrdServer.utilities.LogSanitizer; @RestController @RequestMapping("/api/v1") @@ -35,34 +33,36 @@ public class ConfigController { private final BackupArchiveService archiveService; private final BackupOrchestratorService orchestrator; - private final DatabaseService db; - private final DockerService docker; + private final BackupRunLifecycle lifecycle; + private final ServiceConfigService serviceConfig; private final RunStatusBroadcaster broadcaster; public ConfigController( BackupArchiveService archiveService, BackupOrchestratorService orchestrator, - DatabaseService db, - DockerService docker, + BackupRunLifecycle lifecycle, + ServiceConfigService serviceConfig, RunStatusBroadcaster broadcaster ) { this.archiveService = archiveService; this.orchestrator = orchestrator; - this.db = db; - this.docker = docker; + this.lifecycle = lifecycle; + this.serviceConfig = serviceConfig; this.broadcaster = broadcaster; } + @SetupSessionAllowed @GetMapping("/config") public ServerConfigDto config() { - LOGGER.info("GET /api/v1/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={}", request.backupLocation(), request.retentionCount()); - return orchestrator.whileIdle(() -> { + 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(); @@ -72,63 +72,35 @@ public ServerConfigDto updateConfig(@RequestBody ConfigUpdateRequest request) { }); } + @SetupSessionAllowed @GetMapping("/services") public List services() { - LOGGER.info("GET /api/v1/services"); - return db.fetchServices(); + LOGGER.debug("GET /api/v1/services"); + return serviceConfig.list(); } + @SetupSessionAllowed @PostMapping("/services") - public ResponseEntity addService(@RequestBody ServiceDefinition request) { + public ResponseEntity addService(@RequestBody ServiceDefinition request) { ServiceDefinition service = request.validate(); - LOGGER.info("POST /api/v1/services, name={}, paths={}", service.name(), service.paths()); - return orchestrator.whileIdle(() -> { - if (db.fetchService(service.name()).isPresent()) { - return error(HttpStatus.CONFLICT, "Service already exists: " + service.name()); - } - db.addService(service); - orchestrator.servicesChanged(); - broadcaster.publishConfigChanged(); - return ResponseEntity.status(HttpStatus.CREATED).body(service); - }); + 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) { + public ResponseEntity updateService(@PathVariable String name, @RequestBody ServiceDefinition request) { ServiceDefinition service = request.validate(); - LOGGER.info("PUT /api/v1/services/{}, name={}, paths={}", name, service.name(), service.paths()); - return orchestrator.whileIdle(() -> { - Optional existing = db.fetchService(name); - if (existing.isEmpty()) { - return error(HttpStatus.NOT_FOUND, "Service not found: " + name); - } - String currentName = existing.get().name(); - if (!service.name().equalsIgnoreCase(currentName) && db.fetchService(service.name()).isPresent()) { - return error(HttpStatus.CONFLICT, "Service already exists: " + service.name()); - } - db.updateService(currentName, service); - if (!service.name().equals(currentName)) { - docker.removeContainers(currentName); - } - orchestrator.servicesChanged(); - broadcaster.publishConfigChanged(); - return ResponseEntity.ok(service); - }); + 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/{}", name); - return orchestrator.whileIdle(() -> { - Optional existing = db.fetchService(name); - if (existing.isEmpty()) { - return error(HttpStatus.NOT_FOUND, "Service not found: " + name); - } - db.removeService(existing.get().name()); - docker.removeContainers(existing.get().name()); - broadcaster.publishConfigChanged(); - return ResponseEntity.noContent().build(); - }); + 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() { 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 index c4f2f86..e82f3c0 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java @@ -2,12 +2,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.http.CacheControl; 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; @@ -15,6 +15,7 @@ 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; @@ -25,18 +26,24 @@ public class RunEventsController { private static final Logger LOGGER = LoggerFactory.getLogger(RunEventsController.class); private final RunStatusBroadcaster broadcaster; + private final PairingService pairing; - public RunEventsController(RunStatusBroadcaster broadcaster) { + public RunEventsController(RunStatusBroadcaster broadcaster, PairingService pairing) { this.broadcaster = broadcaster; + this.pairing = pairing; } @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) - public ResponseEntity events() { + 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() - .cacheControl(CacheControl.noCache()) .header("X-Accel-Buffering", "no") - .body(broadcaster.subscribe()); + .body(emitter); } catch (SubscriberLimitException e) { return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).build(); } 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 index e02d508..9f95f09 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/SetupController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupController.java @@ -18,9 +18,11 @@ 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.service.DatabaseService; +import wellatleastitried.mediagarrdServer.repository.ServiceRepository; +import wellatleastitried.mediagarrdServer.service.SetupAlreadyCompleteException; import wellatleastitried.mediagarrdServer.service.SetupService; @RestController @@ -30,20 +32,22 @@ public class SetupController { private static final Logger LOGGER = LoggerFactory.getLogger(SetupController.class); private final SetupService setup; - private final DatabaseService db; + private final ServiceRepository services; - public SetupController(SetupService setup, DatabaseService db) { + public SetupController(SetupService setup, ServiceRepository services) { this.setup = setup; - this.db = db; + 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) { + 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"); @@ -52,25 +56,40 @@ public ResponseEntity startSession(@RequestBody SetupSessionRequest request) 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).toString()).build(); + return ResponseEntity.noContent().header(HttpHeaders.SET_COOKIE, cookie(session.get(), -1, http).toString()).build(); } + @SetupSessionAllowed @PostMapping("/complete") - public ResponseEntity 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 (db.fetchServices().isEmpty()) { + if (services.fetchServices().isEmpty()) { return error(HttpStatus.CONFLICT, "Add at least one service before finishing setup"); } - setup.complete(); - return ResponseEntity.noContent().header(HttpHeaders.SET_COOKIE, cookie("", 0).toString()).build(); + 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) { + 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) diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java index 354fbbb..5265b88 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/SetupInterceptor.java @@ -2,10 +2,8 @@ import java.io.IOException; import java.util.Arrays; -import java.util.List; import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; @@ -18,8 +16,7 @@ public class SetupInterceptor implements HandlerInterceptor { static final String SESSION_COOKIE = "mediagarrd-setup"; - private static final List SETUP_PAGE_PATHS = List.of("/config", "/config.html", "/css/", "/js/"); - private static final List CONFIG_API_PATHS = List.of("/api/v1/config", "/api/v1/services", "/api/v1/setup/complete"); + public static final String[] SETUP_PAGE_PATTERNS = {"/config", "/config.html", "/css/**", "/js/**"}; private final SetupService setup; @@ -29,17 +26,10 @@ public SetupInterceptor(SetupService setup) { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { - String path = request.getRequestURI(); - if (matches(path, SETUP_PAGE_PATHS) && setup.isCompleted()) { + if (setup.isCompleted()) { response.sendError(HttpStatus.NOT_FOUND.value()); return false; } - if (matches(path, CONFIG_API_PATHS) && !setup.canConfigure(sessionToken(request))) { - response.setStatus(HttpStatus.UNAUTHORIZED.value()); - response.setContentType(MediaType.APPLICATION_JSON_VALUE); - response.getWriter().write("{\"error\":\"Setup session required, reload /config and enter the PIN from the server logs\"}"); - return false; - } return true; } @@ -54,10 +44,4 @@ static String sessionToken(HttpServletRequest request) { .findFirst() .orElse(null); } - - private static boolean matches(String path, List prefixes) { - return prefixes.stream().anyMatch(prefix -> prefix.endsWith("/") - ? path.startsWith(prefix) - : path.equals(prefix) || path.startsWith(prefix + "/")); - } } 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 index 99bb197..57f640f 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java @@ -17,6 +17,7 @@ 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/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/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/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 index 3322f4e..aab071d 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/BackupArchive.java @@ -5,10 +5,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.security.DigestInputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.time.Instant; -import java.util.HexFormat; +import wellatleastitried.mediagarrdServer.utilities.Sha256; public record BackupArchive( String id, @@ -27,10 +25,10 @@ public String resolvedChecksum() { } public String generateChecksum() { - try (DigestInputStream in = new DigestInputStream(Files.newInputStream(path), MessageDigest.getInstance("SHA-256"))) { + try (DigestInputStream in = new DigestInputStream(Files.newInputStream(path), Sha256.newDigest())) { in.transferTo(OutputStream.nullOutputStream()); - return HexFormat.of().formatHex(in.getMessageDigest().digest()); - } catch (IOException | NoSuchAlgorithmException e) { + return Sha256.hex(in.getMessageDigest().digest()); + } catch (IOException e) { return ""; } } 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 index 715364c..3245550 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/model/ServiceDefinition.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/model/ServiceDefinition.java @@ -7,6 +7,8 @@ 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 { @@ -28,7 +30,13 @@ public ServiceDefinition validate() { 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); } 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 index 49d1ebf..9b71b06 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupArchiveService.java @@ -4,17 +4,19 @@ 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.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; @@ -24,6 +26,10 @@ 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 { @@ -34,35 +40,54 @@ public class BackupArchiveService { .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 final DatabaseService db; - private final AtomicReference> cachedArchives = new AtomicReference<>(null); - private final AtomicLong cacheLastUpdatedMs = new AtomicLong(0); private volatile Path root; private volatile int retentionCount; - public BackupArchiveService(MediaGarrdProperties properties, DatabaseService db) { - this.db = db; - this.root = Path.of(db.fetchSetting(BACKUP_ROOT_SETTING).orElse(properties.getBackupRoot())) + 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 = db.fetchSetting(RETENTION_COUNT_SETTING) + 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"); + Path runsRoot = root.resolve(RUNS_DIRECTORY); try { - Files.createDirectories(root); + FilePermissions.createPrivateDirectories(root); try (var stream = Files.list(root)) { stream .filter(Files::isRegularFile) - .filter(path -> path.getFileName().toString().endsWith(".zip.tmp")) + .filter(path -> path.getFileName().toString().endsWith(TEMP_SUFFIX)) .forEach(path -> { try { Files.deleteIfExists(path); @@ -116,7 +141,7 @@ public synchronized void updateSettings(String location, Integer retention) { updateRootDirectory(location); } if (retention != null) { - db.saveSetting(RETENTION_COUNT_SETTING, retention.toString()); + settings.saveSetting(RETENTION_COUNT_SETTING, retention.toString()); retentionCount = retention; LOGGER.info("Retention count changed to {}, applied on the next backup run", retention); } @@ -126,13 +151,19 @@ 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 { - Files.createDirectories(normalized); + FilePermissions.createPrivateDirectories(normalized); } catch (IOException | SecurityException e) { throw new IllegalArgumentException("Unable to create backup location " + normalized); } @@ -140,10 +171,10 @@ public Path updateRootDirectory(String location) { throw new IllegalArgumentException("Backup location is not writable: " + normalized); } - db.saveSetting(BACKUP_ROOT_SETTING, normalized.toString()); + settings.saveSetting(BACKUP_ROOT_SETTING, normalized.toString()); root = normalized; invalidateCache(); - LOGGER.info("Backup location changed to {}", normalized); + LOGGER.info("Backup location changed to {}", LogSanitizer.clean(normalized)); return normalized; } @@ -155,7 +186,7 @@ public BackupArchive createArchive(Path runDirectory) { LOGGER.info("Creating backup archive: {} from runDir={}", fileName, runDirectory); try { - Files.createDirectories(root); + FilePermissions.createPrivateDirectories(root); String checksum = mergeParts(runDirectory, archivePath); enforceRetention(); long size = Files.size(archivePath); @@ -172,14 +203,11 @@ public BackupArchive createArchive(Path runDirectory) { public List listArchives() { long now = System.currentTimeMillis(); - long lastUpdate = cacheLastUpdatedMs.get(); + ArchiveSnapshot cached = archiveCache.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; - } + 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 @@ -190,8 +218,7 @@ public List listArchives() { throw new IllegalStateException("Failed to list archives", e); } - cachedArchives.set(archives); - cacheLastUpdatedMs.set(now); + archiveCache.set(new ArchiveSnapshot(archives, now)); LOGGER.debug("Rebuilt archive cache with {} archives", archives.size()); return archives; } @@ -212,7 +239,7 @@ public boolean deleteById(String id) { try { Files.deleteIfExists(archive.get().path()); - db.deleteBackupRecordById(id); + backups.deleteBackupRecordById(id); LOGGER.info("Archive deleted: {}", id); invalidateCache(); return true; @@ -224,9 +251,9 @@ public boolean deleteById(String id) { } public Path createRunDirectory() { - Path runDir = rootDirectory().resolve("runs").resolve(UUID.randomUUID().toString()); + Path runDir = rootDirectory().resolve(RUNS_DIRECTORY).resolve(UUID.randomUUID().toString()); try { - Files.createDirectories(runDir); + FilePermissions.createPrivateDirectories(runDir); return runDir; } catch (IOException e) { throw new IllegalStateException("Failed to create run directory", e); @@ -254,9 +281,13 @@ public void removeRunDirectory(Path runDirectory) { 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()); - db.deleteBackupRecordById(archive.id()); + backups.deleteBackupRecordById(archive.id()); } } @@ -275,8 +306,7 @@ private List scanArchives() throws IOException { } private void invalidateCache() { - cacheLastUpdatedMs.set(0); - cachedArchives.set(null); + archiveCache.set(null); } private String mergeParts(Path runDirectory, Path zipPath) throws IOException { @@ -290,6 +320,8 @@ private String mergeParts(Path runDirectory, Path zipPath) throws IOException { } Path tempZip = zipPath.resolveSibling(zipPath.getFileName() + ".tmp"); + Files.deleteIfExists(tempZip); + FilePermissions.createPrivateFile(tempZip); Path snapshotDirectory = runDirectory.resolve(DatabaseSnapshotService.PART_DIRECTORY); ZipPartMerger.Result result; try { @@ -297,15 +329,31 @@ private String mergeParts(Path runDirectory, Path zipPath) throws IOException { 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; } - Files.move(tempZip, zipPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + 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( @@ -313,10 +361,20 @@ private BackupArchive toArchive(Path path) { fileName, path, fileSize(path), - lastModified(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); @@ -327,7 +385,7 @@ private static Optional parseRetention(String stored) { } private String toId(String fileName) { - return fileName.replace(".zip", ""); + return fileName.endsWith(ZIP_EXTENSION) ? fileName.substring(0, fileName.length() - ZIP_EXTENSION.length()) : fileName; } private long fileSize(Path path) { 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 index f9501b9..8317521 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -23,10 +23,7 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.function.Supplier; import java.util.stream.Collectors; import org.slf4j.Logger; @@ -39,6 +36,8 @@ 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 { @@ -55,11 +54,10 @@ public class BackupOrchestratorService { private final BackupArchiveService archiveService; private final BackupScheduleService scheduleService; private final DatabaseSnapshotService snapshotService; - private final DatabaseService db; - private final RunStatusBroadcaster broadcaster; - private final AtomicBoolean running = new AtomicBoolean(false); - private final Object transitionLock = new Object(); - private final ReentrantReadWriteLock configLock = new ReentrantReadWriteLock(); + private final ServiceRepository services; + private final BackupRecordRepository backups; + private final BackupRunLifecycle lifecycle; + private final WebhookService webhook; private final ExecutorService runnerExecutor = createRunnerExecutor(); public BackupOrchestratorService( @@ -67,15 +65,19 @@ public BackupOrchestratorService( BackupArchiveService archiveService, BackupScheduleService scheduleService, DatabaseSnapshotService snapshotService, - DatabaseService db, - RunStatusBroadcaster broadcaster + ServiceRepository services, + BackupRecordRepository backups, + BackupRunLifecycle lifecycle, + WebhookService webhook ) { this.runner = runner; this.archiveService = archiveService; this.scheduleService = scheduleService; this.snapshotService = snapshotService; - this.db = db; - this.broadcaster = broadcaster; + this.services = services; + this.backups = backups; + this.lifecycle = lifecycle; + this.webhook = webhook; } private static ExecutorService createRunnerExecutor() { @@ -97,7 +99,7 @@ private static ExecutorService createRunnerExecutor() { @Scheduled(fixedDelay = SCHEDULED_CHECK_INTERVAL_MS) public void scheduledRun() { - if (running.get()) { + if (lifecycle.isRunning()) { LOGGER.debug("Scheduled check skipped, backup already in progress"); return; } @@ -120,127 +122,106 @@ public BackupRunResult runBackup() { BackupRunResult runBackup(boolean scheduled) { Instant startedAt = Instant.now(); - String finalStatus = FAILED; + 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; - 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"); - } - } + boolean notified = false; try { - configLock.readLock().lock(); - Path runDirectory = null; - try { - List services = db.fetchServices(); - if (services.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"); - } - started = true; - publishStarted(startedAt); - - scheduleService.markRunStarted(); - runDirectory = archiveService.createRunDirectory(); - final Path runDir = runDirectory; - - LOGGER.info("Backup run started: runDir={}, services={}", - runDir, services.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(services, runDir, excluded); - - List incomplete = serviceRunResults.stream() - .filter(r -> !COMPLETED.equals(r.status())) - .toList(); - int succeeded = services.size() - incomplete.size(); - LOGGER.info("All runners finished: succeeded={}/{}", succeeded, services.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)); - db.addNewBackupRecord(new BackupRunResult( - runId, formatTime(startedAt), recordCurrentTime(), FAILED, serviceRunResults, null, errorMessage)); - LOGGER.error("Every service failed, no archive created (run {}):\n{}", runId, errorMessage); - throw new IllegalStateException("Every service failed, no archive created: " + errorMessage); + 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; - } + 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())); + 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()); + 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 == services.size() ? COMPLETED : succeeded > 0 ? PARTIAL : FAILED; - if (snapshotFailed && COMPLETED.equals(status)) { - status = PARTIAL; - } + 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); - db.addNewBackupRecord(backupRecord); - finalStatus = status; - return backupRecord; - } finally { + 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 { - if (runDirectory != null) { - archiveService.removeRunDirectory(runDirectory); - LOGGER.debug("Run directory cleaned up: {}", runDirectory); - } + archiveService.removeRunDirectory(runDirectory); + LOGGER.debug("Run directory cleaned up: {}", runDirectory); } catch (RuntimeException e) { LOGGER.error("Failed to clean up run directory {}", runDirectory, e); - } finally { - configLock.readLock().unlock(); } } - } finally { - synchronized (transitionLock) { - running.set(false); - if (started) { - publishFinished(finalStatus, startedAt); - } - } - } - } - - 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); } } @@ -342,23 +323,12 @@ private static BackupServiceResult failedResult(String serviceName, Throwable ca ); } - 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 void servicesChanged() { scheduleService.releaseDeferral(); } public boolean isRunning() { - return running.get(); + return lifecycle.isRunning(); } public Duration getInterval() { @@ -373,16 +343,4 @@ public Duration updateInterval(Duration duration) { public void shutdownRunnerExecutor() { runnerExecutor.shutdownNow(); } - - public static class RunRejectedException extends IllegalStateException { - public RunRejectedException(String message) { - super(message); - } - } - - public static class BackupInProgressException extends IllegalStateException { - public BackupInProgressException(String message) { - super(message); - } - } } 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 index 1b21d86..1034c12 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java @@ -2,6 +2,7 @@ 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; @@ -11,30 +12,65 @@ 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 DatabaseService db; + 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()); + } - public BackupScheduleService(MediaGarrdProperties properties, DatabaseService db) { - this.db = db; - Duration interval = db.fetchSetting(BACKUP_INTERVAL_SETTING) - .flatMap(BackupScheduleService::parse) - .orElseGet(() -> safe(properties.getBackupInterval())); + 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<>(Instant.now().plus(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(); } @@ -44,58 +80,106 @@ public Instant getNextRun() { } public Duration updateInterval(Duration interval) { - Duration safe = safe(interval); - db.saveSetting(BACKUP_INTERVAL_SETTING, safe.toString()); - currentInterval.set(safe); - Instant next = Instant.now().plus(safe); + 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={}", safe, next); - return safe; + LOGGER.info("Backup interval updated: newInterval={}, nextRunAt={}", interval, next); + return interval; } public boolean dueNow() { - Instant now = Instant.now(); + 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() { - Instant next = Instant.now().plus(currentInterval.get()); + 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 = Instant.now().plus(currentInterval.get()); + 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(Instant.now()); + 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 { - return Optional.of(Duration.parse(stored)).filter(BackupScheduleService::isValid); + 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: {}", stored); + LOGGER.warn("Ignoring invalid stored backup interval: {}", LogSanitizer.clean(stored)); return Optional.empty(); } } - private static boolean isValid(Duration interval) { - return interval != null && !interval.isNegative() && !interval.isZero(); + 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 Duration safe(Duration interval) { - // Default to 12 hours if the provided interval is invalid - return isValid(interval) ? interval : Duration.ofHours(12); + 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 index ded1f51..bd05951 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironment.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironment.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; @@ -44,16 +43,12 @@ public boolean insideContainer() { } public List containerIdCandidates() { - List candidates = new ArrayList<>(); Optional mounted = mountedContainerId(); if (mounted.isPresent()) { return List.of(mounted.get()); } String name = hostname.get(); - if (name != null && !name.isBlank() && !candidates.contains(name.strip())) { - candidates.add(name.strip()); - } - return candidates; + return name == null || name.isBlank() ? List.of() : List.of(name.strip()); } private Optional mountedContainerId() { 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/DatabaseService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java deleted file mode 100644 index d76ca4a..0000000 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseService.java +++ /dev/null @@ -1,638 +0,0 @@ -package wellatleastitried.mediagarrdServer.service; - -import static wellatleastitried.mediagarrdServer.utilities.MediaGarrdUtils.formatTime; -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.ADD_SERVICE; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.CREATE_TABLES; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.DELETE_BACKUP_RECORD_BY_ID; -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_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 static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SERVICE_BY_NAME; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.FETCH_SETTING; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.MIGRATIONS; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.UPDATE_SERVICE; -import static wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.UPSERT_SETTING; -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.time.Instant; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import org.sqlite.SQLiteErrorCode; -import org.sqlite.SQLiteConfig; -import org.sqlite.SQLiteException; -import org.sqlite.SQLiteOpenMode; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import wellatleastitried.mediagarrdServer.MediaGarrdProperties; -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; -import wellatleastitried.mediagarrdServer.model.ServiceDefinition; -import wellatleastitried.mediagarrdServer.utilities.database.DatabaseQueries.Migration; - -@Service -public class DatabaseService { - - private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseService.class); - private static final ObjectMapper JSON = new ObjectMapper(); - private static final TypeReference> PATH_LIST = new TypeReference<>() {}; - - 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 static final List REQUIRED_TABLES = List.of("backups", "backup_services", "services", "settings"); - - private final ReentrantReadWriteLock databaseLock = new ReentrantReadWriteLock(); - private final Path databaseFile; - private final String databaseUrl; - private volatile SchemaFingerprint verifiedSchema; - - private record SchemaFingerprint(int userVersion, int schemaVersion) {} - - public DatabaseService(MediaGarrdProperties properties) { - databaseFile = Path.of(properties.getDatabasePath()).toAbsolutePath(); - databaseUrl = SQLITE + databaseFile; - verifyDatabaseIntegrity(); - } - - protected Connection getConnection() throws SQLException { - Connection connection = DriverManager.getConnection(databaseUrl); - try (var statement = connection.createStatement()) { - statement.execute("PRAGMA foreign_keys = ON"); - } catch (SQLException sE) { - connection.close(); - throw sE; - } - return connection; - } - - protected synchronized boolean verifyDatabaseIntegrity() { - verifiedSchema = null; - try { - rebuildIfNeeded(); - return true; - } catch (SQLException sE) { - if (!isCorrupt(sE) || !quarantineDatabase()) { - LOGGER.warn("An error occurred while verifying the integrity of the database", sE); - return false; - } - } catch (Exception e) { - LOGGER.warn("An unknown error occurred while verifying the integrity of the database", e); - return false; - } - - try { - rebuildIfNeeded(); - return true; - } catch (Exception e) { - LOGGER.warn("Unable to create a new database after moving the corrupt one aside", e); - return false; - } - } - - private void rebuildIfNeeded() throws SQLException { - try { - Files.createDirectories(databaseFile.getParent()); - } catch (IOException iE) { - LOGGER.warn("Unable to create database directory " + databaseFile.getParent(), iE); - } - try (var connection = getConnection()) { - checkNotCorrupt(connection); - connection.setAutoCommit(false); - ensureTablesExist(connection); - runNeededMigrations(connection); - verifiedSchema = fingerprint(connection); - } - } - - private Connection openVerifiedConnection() throws SQLException { - SchemaFingerprint expected = verifiedSchema; - if (expected != null) { - Connection connection = null; - try { - connection = getConnection(); - if (fingerprint(connection).equals(expected)) { - return connection; - } - } catch (SQLException sE) { - LOGGER.debug("Unable to read the database schema fingerprint", sE); - } - 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(); - } - - private static SchemaFingerprint 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 SchemaFingerprint(rs.getInt(1), rs.getInt(2)); - } - } - - private 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); - } - } - } - - private boolean invalidateIfDamaged(SQLException e) { - String message = String.valueOf(e.getMessage()); - boolean damaged = isCorrupt(e) || message.contains("no such table") || message.contains("no such column"); - if (damaged) { - verifiedSchema = null; - } - return damaged; - } - - private 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; - } - - private boolean quarantineDatabase() { - 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 iE) { - LOGGER.error("Database {} is corrupt and could not be moved aside", databaseFile, iE); - 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); - } - } - - private void ensureTablesExist(Connection connection) throws SQLException { - try (var statement = connection.createStatement()) { - for (String sql : CREATE_TABLES.split(";")) { - String CREATE_STATEMENT = sql.trim(); - if (!CREATE_STATEMENT.isEmpty()) { - statement.execute(CREATE_STATEMENT); - } - } - - connection.commit(); - } catch (SQLException sE) { - LOGGER.warn("Failed to verify if tables exist in database.", sE); - handleSqlException(connection); - throw sE; - } - } - - private void runNeededMigrations(Connection connection) throws SQLException { - int currentVersion = getDatabaseVersion(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 sE) { - LOGGER.warn( - "Migration failed for v" + migration.version() + ". Aborting the rest of the migrations...", - sE - ); - handleSqlException(connection); - throw sE; - } - - currentVersion = migration.version(); - setDatabaseVersion(connection, currentVersion); - } - - connection.commit(); - } - - protected int getDatabaseVersion(Connection connection) { - try (var statement = connection.createStatement(); - var result = statement.executeQuery("PRAGMA user_version")) { - - return result.getInt(1); - } catch (SQLException sE) { - LOGGER.warn("Failed to fetch database version", sE); - return -1; - } - } - - protected void setDatabaseVersion(Connection connection, int version) { - try (var statement = connection.createStatement()) { - statement.execute("PRAGMA user_version = " + version); - } catch (SQLException sE) { - LOGGER.warn("Failed to set new database version", sE); - } - } - - public void addNewBackupRecord(BackupRunResult backupRecord) { - databaseLock.readLock().lock(); - try (var connection = openVerifiedConnection()) { - connection.setAutoCommit(false); - Integer backupId = addMasterBackup(connection, backupRecord); - if (backupId != null) { - addServiceBackups(connection, backupId, backupRecord.serviceResults()); - } - } catch (SQLException sE) { - LOGGER.warn("Could not log record of backup: " + backupRecord.runId(), sE); - } catch (Exception e) { - LOGGER.warn("An unknown error occurred while attempting to open a connection to the database", e); - } finally { - databaseLock.readLock().unlock(); - } - } - - private Integer addMasterBackup(Connection connection, BackupRunResult backupRecord) { - 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(); - int backupId; - try (var idQuery = connection.createStatement(); - var keys = idQuery.executeQuery("SELECT last_insert_rowid()")) { - backupId = keys.getInt(1); - } - connection.commit(); - return backupId; - } catch (SQLException sE) { - invalidateIfDamaged(sE); - LOGGER.warn("An error occurred while logging a new backup record", sE); - handleSqlException(connection); - } catch (Exception e) { - LOGGER.warn("An unknown error occurred while logging a new backup record", e); - } - return null; - } - - private void addServiceBackups(Connection connection, int backupId, List serviceResults) { - for (BackupServiceResult service : serviceResults) { - 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(); - connection.commit(); - } catch (SQLException sE) { - invalidateIfDamaged(sE); - LOGGER.warn("An error occurred while adding a new backup service record for " + service.serviceName(), sE); - handleSqlException(connection); - } - } - } - - 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); - } - - public Optional fetchBackupById(String archiveId) { - FetchedBackupRecord backupRecord = null; - databaseLock.readLock().lock(); - try (var connection = openVerifiedConnection()) { - backupRecord = fetchMasterRecordById(connection, archiveId); - if (backupRecord != null) { - backupRecord = populateFetchedRecordWithServices(connection, backupRecord); - } - } catch (SQLException sE) { - LOGGER.warn("An error occurred while fetching a backup record by archive_id (" + archiveId + ")", sE); - } catch (Exception e) { - LOGGER.warn("An unknown error occurred while fetching a backup record by archive_id (" + archiveId + ")", e); - } finally { - databaseLock.readLock().unlock(); - } - - return Optional.ofNullable(backupRecord); - } - - 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 sE) { - invalidateIfDamaged(sE); - LOGGER.warn("Error fetching backup record by archive_id " + archiveId + ")", sE); - return null; - } - } - - public Optional fetchLatestBackupRecord() { - FetchedBackupRecord backupRecord = null; - databaseLock.readLock().lock(); - try (var connection = openVerifiedConnection()) { - backupRecord = fetchLatestMasterRecord(connection); - if (backupRecord != null) { - backupRecord = populateFetchedRecordWithServices(connection, backupRecord); - } - } catch (SQLException sE) { - LOGGER.warn("An error occurred while fetching the latest backup record", sE); - } catch (Exception e) { - LOGGER.warn("An unknown error occurred while fetching the latest backup record", e); - } finally { - databaseLock.readLock().unlock(); - } - - return Optional.ofNullable(backupRecord); - } - - private FetchedBackupRecord fetchLatestMasterRecord(Connection connection) { - try (var statement = connection.createStatement()) { - var rs = statement.executeQuery(FETCH_LATEST_RECORD); - return buildFetchedBackupRecordFromQueryResult(rs); - } catch (SQLException sE) { - invalidateIfDamaged(sE); - LOGGER.warn("Error fetching latest backup record", sE); - return null; - } - } - - 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 sE) { - invalidateIfDamaged(sE); - LOGGER.warn("Error populating backup record with related services", sE); - return null; - } - } - - private void handleSqlException(Connection connection) { - try { - connection.rollback(); - } catch (SQLException rollbackException) { - LOGGER.warn("Failed to rollback update after previous SQL failure, there is an issue with the database!"); - } - } - - public void deleteBackupRecordById(String archiveId) { - databaseLock.readLock().lock(); - try (var connection = openVerifiedConnection(); - var statement = connection.prepareStatement(DELETE_BACKUP_RECORD_BY_ID)) { - statement.setString(1, archiveId); - statement.executeUpdate(); - } catch (SQLException sE) { - invalidateIfDamaged(sE); - LOGGER.warn("Error deleting a backup record with archive_id (" + archiveId + ")", sE); - } finally { - databaseLock.readLock().unlock(); - } - } - - public List fetchServices() { - return query("fetch configured services", FETCH_ALL_SERVICES, DatabaseService::toServiceDefinition); - } - - public Optional fetchService(String name) { - return query("fetch service " + name, FETCH_SERVICE_BY_NAME, DatabaseService::toServiceDefinition, name) - .stream().findFirst(); - } - - public void addService(ServiceDefinition service) { - update("add service " + service.name(), ADD_SERVICE, service.name(), toJson(service.paths())); - } - - public boolean updateService(String name, ServiceDefinition service) { - return update("update service " + name, UPDATE_SERVICE, service.name(), toJson(service.paths()), name) > 0; - } - - public boolean removeService(String name) { - return update("remove service " + name, DELETE_SERVICE, name) > 0; - } - - public Optional fetchSetting(String key) { - return query("fetch setting " + key, FETCH_SETTING, rs -> rs.getString("value"), key).stream().findFirst(); - } - - public void saveSetting(String key, String value) { - update("save setting " + key, UPSERT_SETTING, key, value); - } - - @FunctionalInterface - private interface RowMapper { - T map(ResultSet rs) throws SQLException; - } - - @FunctionalInterface - private interface StatementWork { - T run(PreparedStatement statement) throws SQLException; - } - - private 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; - } - }); - } - - private 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 sE) { - if (attempt > 1 || !invalidateIfDamaged(sE)) { - throw new IllegalStateException("Failed to " + action, sE); - } - LOGGER.warn("Database is damaged or out of date, rebuilding and retrying: {}", sE.getMessage()); - } - } - } finally { - databaseLock.readLock().unlock(); - } - } - - public Path databaseFile() { - return databaseFile; - } - - 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)) { - 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)) { - checkNotCorrupt(connection); - if (getDatabaseVersion(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); - } - } - } - - private static void bind(PreparedStatement statement, String... params) throws SQLException { - for (int i = 0; i < params.length; i++) { - statement.setString(i + 1, params[i]); - } - } - - private static ServiceDefinition toServiceDefinition(ResultSet rs) throws SQLException { - try { - return new ServiceDefinition(rs.getString("name"), JSON.readValue(rs.getString("paths"), PATH_LIST)); - } catch (JsonProcessingException jE) { - throw new SQLException("Corrupt paths for service " + rs.getString("name"), jE); - } - } - - private static String toJson(List paths) { - try { - return JSON.writeValueAsString(paths); - } catch (JsonProcessingException jE) { - throw new IllegalStateException("Failed to serialize service paths", jE); - } - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java index 506cbbe..9f9d541 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotService.java @@ -22,6 +22,7 @@ import org.springframework.stereotype.Service; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; +import wellatleastitried.mediagarrdServer.repository.SqliteDatabase; @Service public class DatabaseSnapshotService { @@ -34,11 +35,11 @@ public class DatabaseSnapshotService { private static final List DATABASE_SIDECAR_SUFFIXES = List.of("", "-journal", "-wal", "-shm"); private static final String SNAPSHOT_FILE = "snapshot.db"; - private final DatabaseService db; + private final SqliteDatabase db; private final DatabaseHostPathResolver hostPaths; private final ZipCompression compression; - public DatabaseSnapshotService(DatabaseService db, DatabaseHostPathResolver hostPaths, ZipCompression compression) { + public DatabaseSnapshotService(SqliteDatabase db, DatabaseHostPathResolver hostPaths, ZipCompression compression) { this.db = db; this.hostPaths = hostPaths; this.compression = compression; diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java index eb36c32..a937f2d 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/DockerService.java @@ -1,10 +1,6 @@ package wellatleastitried.mediagarrdServer.service; import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -23,6 +19,7 @@ import wellatleastitried.mediagarrdServer.MediaGarrdProperties; import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.utilities.Sha256; @Service public class DockerService { @@ -44,15 +41,17 @@ public DockerService(DockerClient client, MediaGarrdProperties properties) { public String containerFor(ServiceDefinition service) { String hash = configHash(service); + String reusable = null; for (Container container : managedContainers(service.name())) { - if (hash.equals(container.getLabels().get(CONFIG_HASH_LABEL))) { - LOGGER.debug("[{}] Reusing helper container {}", service.name(), container.getId()); - return container.getId(); + 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("[{}] Service config changed, removing stale helper container {}", service.name(), container.getId()); + LOGGER.info("[{}] Removing stale helper container {}", service.name(), container.getId()); removeContainer(container.getId()); } - return createContainer(service, hash); + return reusable != null ? reusable : createContainer(service, hash); } public InputStream copyFrom(String containerId, String hostPath) { @@ -78,12 +77,7 @@ static String containerPath(String hostPath) { String configHash(ServiceDefinition service) { String fingerprint = helperImage + "\n" + String.join("\n", service.paths().stream().sorted().toList()); - try { - byte[] digest = MessageDigest.getInstance("SHA-256").digest(fingerprint.getBytes(StandardCharsets.UTF_8)); - return HexFormat.of().formatHex(digest); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException(e); - } + return Sha256.hex(fingerprint); } private List managedContainers(String serviceName) { @@ -121,9 +115,9 @@ private synchronized void ensureHelperImage() { if (!client.pullImageCmd(helperImage).start().awaitCompletion(IMAGE_PULL_TIMEOUT_MINUTES, TimeUnit.MINUTES)) { throw new IllegalStateException("Timed out pulling helper image " + helperImage); } - } catch (InterruptedException iE) { + } catch (InterruptedException ex) { Thread.currentThread().interrupt(); - throw new IllegalStateException("Interrupted while pulling helper image " + helperImage, iE); + throw new IllegalStateException("Interrupted while pulling helper image " + helperImage, ex); } } } 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/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 index 0a19f73..b9edf53 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java @@ -62,11 +62,19 @@ private static Thread newWriterThread(Runnable runnable) { } public SseEmitter subscribe() { - return subscribe(new SseEmitter(emitterTimeoutMs)); + return subscribe(new SseEmitter(emitterTimeoutMs), null); + } + + public SseEmitter subscribe(String clientId) { + return subscribe(new SseEmitter(emitterTimeoutMs), clientId); } SseEmitter subscribe(SseEmitter emitter) { - Subscriber subscriber = new Subscriber(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"); @@ -119,6 +127,24 @@ private void publish(String name, Boolean nowRunning, String json) { } } + 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(); @@ -152,12 +178,14 @@ public SubscriberLimitException(String 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) { + Subscriber(SseEmitter emitter, String clientId) { this.emitter = emitter; + this.clientId = clientId; } void close() { 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 index 5985220..f2f79cb 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/SetupService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/SetupService.java @@ -6,16 +6,24 @@ 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.Set; +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 { @@ -23,21 +31,64 @@ 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 DatabaseService db; - private final Set sessions = ConcurrentHashMap.newKeySet(); + 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; - private int failedAttempts; - public SetupService(DatabaseService db) { - this.db = db; - this.completed = db.fetchSetting(SETUP_COMPLETED_SETTING).isPresent(); - if (completed) { - LOGGER.info("Setup already completed, the web setup page is disabled"); + @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"); } } @@ -46,46 +97,134 @@ public boolean isCompleted() { } public boolean canConfigure(String sessionToken) { - return completed || (sessionToken != null && sessions.contains(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 || !MessageDigest.isEqual(bytes(pin), bytes(candidate.strip()))) { - failedAttempts++; - LOGGER.warn("Rejected setup PIN attempt ({}/{})", failedAttempts, MAX_FAILED_ATTEMPTS); - if (failedAttempts >= MAX_FAILED_ATTEMPTS) { - rotatePin(); - } + 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); - sessions.add(session); + 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 void complete() { - db.saveSetting(SETUP_COMPLETED_SETTING, recordCurrentTime()); + public synchronized String complete() { + if (completed) { + throw new SetupAlreadyCompleteException(); + } + settings.saveSetting(SETUP_COMPLETED_SETTING, recordCurrentTime()); completed = true; sessions.clear(); - pin = null; + 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)); - failedAttempts = 0; - LOGGER.warn("Setup PIN: {} (single use, enter it at http://:/config)", pin); + 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) { 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/ZipPartMerger.java b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java index 76ee8f0..fac0d9e 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/ZipPartMerger.java @@ -6,7 +6,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -14,7 +13,6 @@ import java.sql.Statement; import java.util.ArrayList; import java.util.HashSet; -import java.util.HexFormat; import java.util.List; import java.util.Set; @@ -22,6 +20,7 @@ import org.slf4j.LoggerFactory; import wellatleastitried.mediagarrdServer.service.ZipFormat.Entry; +import wellatleastitried.mediagarrdServer.utilities.Sha256; final class ZipPartMerger { @@ -37,7 +36,7 @@ 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(); + 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); @@ -58,7 +57,7 @@ static Result merge(List snapshotParts, List parts, Path output, Pat sink.write(ZipFormat.endOfArchive(entries, centralSize, centralStart)); sink.flush(); LOGGER.debug("Merged {} part(s) into {} entries", ordered.size(), entries); - return new Result(HexFormat.of().formatHex(digest.digest()), entries, sink.written()); + return new Result(Sha256.hex(digest.digest()), entries, sink.written()); } finally { Files.deleteIfExists(names); } @@ -104,14 +103,6 @@ private static long writeCentral(Path part, long base, boolean snapshot, 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 index 19043a9..9d7b135 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/MediaGarrdUtils.java @@ -20,13 +20,17 @@ public static String formatTime(Instant 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 pE) {} + } catch (ParseException e) {} return -1; } } 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 index 2a23d30..bbabaf1 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseQueries.java @@ -42,6 +42,14 @@ CREATE TABLE IF NOT EXISTS settings ( 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); """; @@ -77,6 +85,13 @@ INSERT INTO backup_services ( 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 = ?; @@ -126,6 +141,34 @@ 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; diff --git a/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java index 25e529c..c6a2f0f 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/database/DatabaseUtils.java @@ -7,6 +7,7 @@ public class DatabaseUtils { 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 { diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 00b03a2..0dee2d0 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -17,3 +17,4 @@ mediagarrd: 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 index aced9f0..1f021d6 100644 --- a/src/main/resources/static/config.html +++ b/src/main/resources/static/config.html @@ -15,21 +15,42 @@ - -
Setup PIN
+ + + +
Setup PIN
- -

+ +
- +
+ +
Backup Settings
@@ -41,7 +62,7 @@
- +
@@ -51,58 +72,81 @@ +
+
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.

-
+
- -
-
Add Service
-
-
- - -
-
- Host paths to back up -
- -
-
- - -
-
- - - - - -
Configured Services
- - - -
NamePaths
-

No services configured yet.

-
diff --git a/src/main/resources/static/css/mediagarrd.css b/src/main/resources/static/css/mediagarrd.css index 8e2fdc0..fa64743 100644 --- a/src/main/resources/static/css/mediagarrd.css +++ b/src/main/resources/static/css/mediagarrd.css @@ -48,12 +48,14 @@ body { margin: 0 auto; padding: 1.5rem; display: grid; - grid-template-columns: 360px 1fr; + grid-template-columns: 360px minmax(0, 1fr); gap: 1rem; align-items: start; } -@media (max-width: 900px) { .workspace { grid-template-columns: 1fr; } } +.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; } @@ -61,7 +63,7 @@ body { dialog.panel { color: var(--ink); margin: auto; width: min(360px, calc(100% - 2rem)); } dialog::backdrop { background: rgba(0, 0, 0, 0.8); } -.error-text { color: #fca5a5; } +.error-text, .note.error-text { color: #fca5a5; } .panel-header { display: flex; align-items: center; @@ -74,23 +76,26 @@ dialog::backdrop { background: rgba(0, 0, 0, 0.8); } .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; } -.input-row { display: grid; grid-template-columns: 1fr auto; gap: 0.5rem; } -.button-row { display: flex; gap: 0.5rem; } +.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; - outline: none; transition: border-color 150ms; } -input:focus { border-color: var(--subtle); } +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 { @@ -146,3 +151,23 @@ tbody td { padding: 0.55rem 0.75rem; vertical-align: top; } } .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 d75d8b1..de496d1 100644 --- a/src/main/resources/static/index.html +++ b/src/main/resources/static/index.html @@ -8,6 +8,6 @@

MediaGarrd Server

API is available under /api/v1.

-

Configure services and backup location

+

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 index 7b8cd87..36c8fa5 100644 --- a/src/main/resources/static/js/api.js +++ b/src/main/resources/static/js/api.js @@ -6,7 +6,10 @@ async function request(method, url, body) { }); if (!response.ok) { const data = await response.json().catch(() => ({})); - throw new Error(data.error || `${method} ${url} failed (${response.status})`); + 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(); } @@ -17,6 +20,9 @@ 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), diff --git a/src/main/resources/static/js/config.js b/src/main/resources/static/js/config.js index 5824f97..3619ada 100644 --- a/src/main/resources/static/js/config.js +++ b/src/main/resources/static/js/config.js @@ -1,5 +1,6 @@ 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'); @@ -18,13 +19,18 @@ const notify = { function start() { workspace.hidden = false; initSettings(document.getElementById('settingsForm'), notify); + initWebhook(document.getElementById('webhookForm'), notify); initServices(document.getElementById('services'), notify); - initFinish(document.getElementById('finish'), 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 = false; - notify.error(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/settings.js b/src/main/resources/static/js/settings.js index c397d73..070f84d 100644 --- a/src/main/resources/static/js/settings.js +++ b/src/main/resources/static/js/settings.js @@ -7,6 +7,9 @@ function toHours(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) { @@ -22,13 +25,23 @@ export function initSettings(form, notify) { 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) }); - const { backupInterval } = await api.updateSchedule(toDuration(Number(intervalHours.value))); + saved = true; + const { backupInterval } = await api.updateSchedule(toDuration(hours)); show({ ...config, backupInterval }); notify.ok('Backup settings saved'); } catch (error) { - notify.error(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 index 94dedad..521ec31 100644 --- a/src/main/resources/static/js/setup.js +++ b/src/main/resources/static/js/setup.js @@ -1,14 +1,36 @@ 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(); @@ -19,19 +41,48 @@ export async function unlock(dialog) { } catch (e) { error.textContent = e.message; form.reset(); + form.elements.pin.focus(); + if (e.retryAfter) lockFor(e.retryAfter); } }); }); } -export function initFinish(root, notify, onComplete) { - root.querySelector('button').addEventListener('click', async () => { +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 { - await api.completeSetup(); + const result = await api.completeSetup(); onComplete(); - notify.ok('Setup complete. This page is now disabled, further changes go through the API or the MediaGarrd Client.'); + 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/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 index 29f5e25..ba71e2c 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java @@ -1,9 +1,12 @@ package wellatleastitried.mediagarrdServer.api; import static org.hamcrest.Matchers.hasSize; +import static org.mockito.Mockito.verifyNoInteractions; 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 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; @@ -12,17 +15,25 @@ 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.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +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) @@ -30,18 +41,26 @@ class BackupControllerTest { @Autowired MockMvc mockMvc; - @MockBean + @MockitoBean BackupArchiveService archiveService; - @MockBean + @MockitoBean BackupOrchestratorService orchestratorService; - @MockBean + @MockitoBean RunStatusBroadcaster broadcaster; - @MockBean + @MockitoBean SetupService setup; + @MockitoBean + PairingService pairing; + + @BeforeEach + void authorize() { + ApiTestAuth.accept(pairing); + } + @Test void healthReturnsServerStatus() throws Exception { when(orchestratorService.isRunning()).thenReturn(false); @@ -55,12 +74,35 @@ void healthReturnsServerStatus() throws Exception { } @Test - void clientEndpointsNeverRequireSetupSession() throws Exception { - when(archiveService.listArchives()).thenReturn(List.of()); + void healthWithoutATokenIsMinimal() throws Exception { when(orchestratorService.getInterval()).thenReturn(Duration.ofHours(12)); - mockMvc.perform(get("/api/v1/health")).andExpect(status().isOk()); - mockMvc.perform(get("/api/v1/backups")).andExpect(status().isOk()); + 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 @@ -87,16 +129,64 @@ void runAndListBackups() throws Exception { mockMvc.perform(post("/api/v1/backups/run")) .andExpect(status().isOk()) - .andExpect(jsonPath("$.archive.id").isNotEmpty()); + .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("$", 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 BackupOrchestratorService.RunRejectedException("A backup run is already in progress")); + when(orchestratorService.runBackup()).thenThrow(new RunRejectedException("A backup run is already in progress")); mockMvc.perform(post("/api/v1/backups/run")) .andExpect(status().isConflict()) @@ -105,18 +195,27 @@ void rejectedRunReturnsConflictWithReason() throws Exception { @Test void failedRunReturnsServerErrorWithReason() throws Exception { - when(orchestratorService.runBackup()).thenThrow(new IllegalStateException("Every service failed, no archive created: radarr: boom")); + 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(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete("/api/v1/backups/backup-1")) + mockMvc.perform(delete("/api/v1/backups/backup-1")) .andExpect(status().isNoContent()); org.mockito.Mockito.verify(broadcaster).publishBackupsChanged(); @@ -126,7 +225,7 @@ void deletingABackupPublishesBackupsChanged() throws Exception { void deletingAMissingBackupPublishesNothing() throws Exception { when(archiveService.deleteById("nope")).thenReturn(false); - mockMvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete("/api/v1/backups/nope")) + mockMvc.perform(delete("/api/v1/backups/nope")) .andExpect(status().isNotFound()); org.mockito.Mockito.verify(broadcaster, org.mockito.Mockito.never()).publishBackupsChanged(); @@ -136,11 +235,93 @@ void deletingAMissingBackupPublishesNothing() throws Exception { void updatingTheSchedulePublishesConfigChanged() throws Exception { when(orchestratorService.updateInterval(Duration.ofHours(2))).thenReturn(Duration.ofHours(2)); - mockMvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put("/api/v1/schedule") + 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 index 9fee6ce..7c3db04 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java @@ -9,10 +9,11 @@ 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.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 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; @@ -25,21 +26,30 @@ import org.junit.jupiter.api.BeforeEach; 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.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.DatabaseService; +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")); @@ -50,35 +60,41 @@ class ConfigControllerTest { @Autowired MockMvc mockMvc; - @MockBean + @MockitoBean BackupArchiveService archiveService; - @MockBean - DatabaseService db; + @MockitoBean + ServiceRepository services; - @MockBean + @MockitoBean DockerService docker; - @MockBean + @MockitoBean RunStatusBroadcaster broadcaster; - @MockBean + @MockitoBean SetupService setup; - @MockBean + @MockitoBean + PairingService pairing; + + @MockitoBean BackupOrchestratorService orchestrator; + @MockitoBean + BackupRunLifecycle lifecycle; + @BeforeEach void setUp() { - when(setup.canConfigure(any())).thenReturn(true); - when(orchestrator.whileIdle(any())).thenAnswer(invocation -> invocation.>getArgument(0).get()); + 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 BackupOrchestratorService.BackupInProgressException("busy")).when(orchestrator).whileIdle(any()); + doThrow(new BackupInProgressException("busy")).when(lifecycle).whileIdle(any()); mockMvc.perform(json(post("/api/v1/services"), RADARR_JSON)) .andExpect(status().isConflict()) @@ -87,8 +103,8 @@ void rejectsConfigChangesWhileBackupIsRunning() throws Exception { 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(db, never()).addService(any()); - verify(db, never()).removeService(anyString()); + verify(services, never()).addService(any()); + verify(services, never()).removeService(anyString()); verify(archiveService, never()).updateSettings(any(), any()); verify(broadcaster, never()).publishConfigChanged(); verify(broadcaster, never()).publishBackupsChanged(); @@ -96,21 +112,45 @@ void rejectsConfigChangesWhileBackupIsRunning() throws Exception { @Test void requiresSetupSessionUntilSetupIsComplete() throws Exception { - when(setup.canConfigure(any())).thenReturn(false); - - mockMvc.perform(get("/api/v1/services")) + mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/services")) .andExpect(status().isUnauthorized()) .andExpect(jsonPath("$.error").exists()); - mockMvc.perform(json(post("/api/v1/services"), RADARR_JSON)) + mockMvc.perform(json(MockMvcRequestBuilders.post("/api/v1/services"), RADARR_JSON)) .andExpect(status().isUnauthorized()); - mockMvc.perform(json(put("/api/v1/config"), "{\"backupLocation\": \"/new\"}")) + mockMvc.perform(json(MockMvcRequestBuilders.put("/api/v1/config"), "{\"backupLocation\": \"/new\"}")) .andExpect(status().isUnauthorized()); - verify(db, never()).fetchServices(); - verify(db, never()).addService(any()); + 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")); @@ -159,7 +199,7 @@ void rejectsInvalidBackupLocation() throws Exception { @Test void listsServices() throws Exception { - when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(services.fetchServices()).thenReturn(List.of(RADARR)); mockMvc.perform(get("/api/v1/services")) .andExpect(status().isOk()) @@ -170,27 +210,27 @@ void listsServices() throws Exception { @Test void addsNormalizedService() throws Exception { - when(db.fetchService("radarr")).thenReturn(Optional.empty()); + 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(db).addService(RADARR); + verify(services).addService(RADARR); verify(orchestrator).servicesChanged(); verify(broadcaster).publishConfigChanged(); } @Test void rejectsDuplicateService() throws Exception { - when(db.fetchService("radarr")).thenReturn(Optional.of(RADARR)); + 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(db, never()).addService(any()); + verify(services, never()).addService(any()); verify(orchestrator, never()).servicesChanged(); verify(broadcaster, never()).publishConfigChanged(); } @@ -201,18 +241,18 @@ void rejectsInvalidService() throws Exception { .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error").value("Path must be absolute: relative")); - verify(db, never()).addService(any()); + verify(services, never()).addService(any()); } @Test void updatesServiceKeepingContainersWhenNameUnchanged() throws Exception { - when(db.fetchService("radarr")).thenReturn(Optional.of(RADARR)); + 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(db).updateService("radarr", new ServiceDefinition("radarr", List.of("/srv/other"))); + verify(services).updateService("radarr", new ServiceDefinition("radarr", List.of("/srv/other"))); verify(orchestrator).servicesChanged(); verify(docker, never()).removeContainers(anyString()); verify(broadcaster).publishConfigChanged(); @@ -220,32 +260,32 @@ void updatesServiceKeepingContainersWhenNameUnchanged() throws Exception { @Test void renamingServiceRemovesOldContainers() throws Exception { - when(db.fetchService("RADARR")).thenReturn(Optional.of(RADARR)); - when(db.fetchService("movies")).thenReturn(Optional.empty()); + 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(db).updateService("radarr", new ServiceDefinition("movies", List.of("/srv/radarr"))); + verify(services).updateService("radarr", new ServiceDefinition("movies", List.of("/srv/radarr"))); verify(docker).removeContainers("radarr"); } @Test void renamingOntoExistingServiceConflicts() throws Exception { - when(db.fetchService("radarr")).thenReturn(Optional.of(RADARR)); - when(db.fetchService("sonarr")).thenReturn(Optional.of(new ServiceDefinition("sonarr", List.of("/srv/sonarr")))); + 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(db, never()).updateService(anyString(), any()); + verify(services, never()).updateService(anyString(), any()); verify(orchestrator, never()).servicesChanged(); verify(broadcaster, never()).publishConfigChanged(); } @Test void updatingMissingServiceReturnsNotFound() throws Exception { - when(db.fetchService("radarr")).thenReturn(Optional.empty()); + when(services.fetchService("radarr")).thenReturn(Optional.empty()); mockMvc.perform(json(put("/api/v1/services/radarr"), RADARR_JSON)) .andExpect(status().isNotFound()); @@ -255,19 +295,19 @@ void updatingMissingServiceReturnsNotFound() throws Exception { @Test void removesServiceAndItsContainers() throws Exception { - when(db.fetchService("Radarr")).thenReturn(Optional.of(RADARR)); + when(services.fetchService("Radarr")).thenReturn(Optional.of(RADARR)); mockMvc.perform(delete("/api/v1/services/Radarr")) .andExpect(status().isNoContent()); - verify(db).removeService("radarr"); + verify(services).removeService("radarr"); verify(docker).removeContainers("radarr"); verify(broadcaster).publishConfigChanged(); } @Test void removingMissingServiceReturnsNotFound() throws Exception { - when(db.fetchService("radarr")).thenReturn(Optional.empty()); + when(services.fetchService("radarr")).thenReturn(Optional.empty()); mockMvc.perform(delete("/api/v1/services/radarr")) .andExpect(status().isNotFound()); 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 index e4c64e9..9ce661f 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java @@ -1,21 +1,27 @@ 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 org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +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.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +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) @@ -25,35 +31,60 @@ class RunEventsControllerTest { @Autowired MockMvc mockMvc; - @MockBean + @MockitoBean RunStatusBroadcaster broadcaster; - @MockBean + @MockitoBean SetupService setup; + @MockitoBean + PairingService pairing; + + @BeforeEach + void authorize() { + ApiTestAuth.accept(pairing); + } + @Test - void streamsEventsWithoutASetupSession() throws Exception { - when(setup.isCompleted()).thenReturn(false); - when(setup.canConfigure(null)).thenReturn(false); - when(broadcaster.subscribe()).thenReturn(new SseEmitter(60_000L)); + void streamsEventsWithATokenWhetherOrNotSetupIsComplete() throws Exception { + when(broadcaster.subscribe("c1")).thenReturn(new SseEmitter(60_000L)); - mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) - .andExpect(request().asyncStarted()) - .andExpect(status().isOk()); + 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 streamsEventsAfterSetupToo() throws Exception { - when(setup.isCompleted()).thenReturn(true); - when(broadcaster.subscribe()).thenReturn(new SseEmitter(60_000L)); + 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(request().asyncStarted()); + .andExpect(status().isUnauthorized()); + + verify(broadcaster).closeClient("c1"); } @Test void answers503WhenTooManySubscribers() throws Exception { - when(broadcaster.subscribe()).thenThrow(new RunStatusBroadcaster.SubscriberLimitException("full")); + when(broadcaster.subscribe("c1")).thenThrow(new RunStatusBroadcaster.SubscriberLimitException("full")); mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) .andExpect(status().isServiceUnavailable()); @@ -61,7 +92,7 @@ void answers503WhenTooManySubscribers() throws Exception { @Test void aTimedOutStreamEndsQuietlyWithoutAnErrorPage() throws Exception { - when(broadcaster.subscribe()).thenThrow(new org.springframework.web.context.request.async.AsyncRequestTimeoutException()); + 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()) 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 index 049aa09..3ea26bf 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/SetupControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/SetupControllerTest.java @@ -5,27 +5,34 @@ 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.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +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.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +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.service.DatabaseService; +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) @@ -34,11 +41,19 @@ class SetupControllerTest { @Autowired MockMvc mockMvc; - @MockBean + @MockitoBean SetupService setup; - @MockBean - DatabaseService db; + @MockitoBean + PairingService pairing; + + @MockitoBean + ServiceRepository services; + + @BeforeEach + void authorize() { + ApiTestAuth.accept(pairing); + } @Test void reportsStatusForTheCallersSession() throws Exception { @@ -83,9 +98,19 @@ void pinIsGoneAfterSetupCompletes() throws Exception { 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(post("/api/v1/setup/complete")).andExpect(status().isUnauthorized()); + mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/setup/complete")).andExpect(status().isUnauthorized()); verify(setup, never()).complete(); } @@ -93,7 +118,7 @@ void completeRequiresSession() throws Exception { @Test void completeRequiresAtLeastOneService() throws Exception { when(setup.canConfigure(any())).thenReturn(true); - when(db.fetchServices()).thenReturn(List.of()); + when(services.fetchServices()).thenReturn(List.of()); mockMvc.perform(post("/api/v1/setup/complete")) .andExpect(status().isConflict()) @@ -105,15 +130,49 @@ void completeRequiresAtLeastOneService() throws Exception { @Test void completeFinishesSetupAndClearsCookie() throws Exception { when(setup.canConfigure(any())).thenReturn(true); - when(db.fetchServices()).thenReturn(List.of(new ServiceDefinition("radarr", List.of("/srv/radarr")))); + 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().isNoContent()) - .andExpect(header().string(HttpHeaders.SET_COOKIE, containsString("Max-Age=0"))); + .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); @@ -135,7 +194,19 @@ void setupPageIsServedOnlyUntilSetupCompletes() throws Exception { mockMvc.perform(get("/js/config.js")).andExpect(status().isNotFound()); } - private static RequestBuilder pin(String pin) { + 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 index 6027d77..2e2d718 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java @@ -9,12 +9,13 @@ 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.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; @@ -24,16 +25,18 @@ class VersionControllerTest { @Autowired MockMvc mockMvc; - @MockBean + @MockitoBean UpdateCheckService updateCheckService; - @MockBean + @MockitoBean SetupService setup; + @MockitoBean + PairingService pairing; + @Test - void reportsTheVersionStatusWithoutASetupSession() throws Exception { + void reportsTheVersionStatusWithoutATokenOrSetupSession() throws Exception { when(setup.isCompleted()).thenReturn(false); - when(setup.canConfigure(null)).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)); @@ -48,16 +51,4 @@ void reportsTheVersionStatusWithoutASetupSession() throws Exception { .andExpect(jsonPath("$.checkedAt").value("2026-11-11T18:00:00Z")) .andExpect(jsonPath("$.message").doesNotExist()); } - - @Test - void reportsAFailedCheckAsAState() throws Exception { - when(updateCheckService.status()).thenReturn(new VersionStatusDto( - "0.1.0", null, null, false, CheckState.ERROR, Instant.parse("2026-11-11T18:00:00Z"), "GitHub is unreachable")); - - mockMvc.perform(get("/api/v1/version")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.checkState").value("ERROR")) - .andExpect(jsonPath("$.updateAvailable").value(false)) - .andExpect(jsonPath("$.message").value("GitHub is unreachable")); - } } 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/ServiceDefinitionTest.java b/src/test/java/wellatleastitried/mediagarrdServer/model/ServiceDefinitionTest.java index 80fa721..ca67ba3 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/model/ServiceDefinitionTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/model/ServiceDefinitionTest.java @@ -54,4 +54,14 @@ void rejectsInvalidPaths(String path) { 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 index c4fac32..c88ed6f 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ArchiveInteropTest.java @@ -49,8 +49,10 @@ private Path archive() throws Exception { 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), "/srv/data", part, new ZipCompression(1)); + ServiceBackupRunner.archive(tar(folder, secret, text, empty, symlink, hardLink, movie), "/srv/data", part, new ZipCompression(1)); return ArchiveTestSupport.merge(dir, part); } @@ -97,6 +99,6 @@ void listingsShowNumericOwnersFromTheLocalHeaders() throws Exception { @Test void everyReaderAcceptsTheArchive() throws Exception { - ZipPartWriterTest.verifyWithTools(archive(), 6); + ZipPartWriterTest.verifyWithTools(archive(), 7); } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java index 1fc30cc..0fc098b 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupArchiveServiceTest.java @@ -17,6 +17,7 @@ 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; @@ -34,6 +35,7 @@ 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 { @@ -42,7 +44,7 @@ class BackupArchiveServiceTest { Path tempDir; private MediaGarrdProperties properties; - private DatabaseService db; + private TestDatabase db; private BackupArchiveService service; @BeforeEach @@ -51,8 +53,8 @@ void setUp() { properties.setBackupRoot(tempDir.resolve("backups").toString()); properties.setDatabasePath(tempDir.resolve("mediagarrd.db").toString()); properties.setRetentionCount(2); - db = new DatabaseService(properties); - service = new BackupArchiveService(properties, db); + db = new TestDatabase(properties); + service = new BackupArchiveService(properties, db.settings, db.backups); } @Test @@ -111,23 +113,23 @@ void aDuplicateNameAcrossPartsFailsTheMergeAndLeavesNoArchive() throws Exception assertThrows(IllegalStateException.class, () -> service.createArchive(run)); try (var files = Files.list(service.rootDirectory())) { - assertEquals(List.of("runs"), files.map(path -> path.getFileName().toString()).toList()); + 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.saveSetting("backup_root", "/marker"); + db.settings.saveSetting("backup_root", "/marker"); DatabaseHostPathResolver hostPaths = mock(DatabaseHostPathResolver.class); - when(hostPaths.resolve(db.databaseFile())).thenReturn(Path.of("/srv/zzz/mediagarrd.db")); + 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, hostPaths, new ZipCompression(1)).snapshot(run).status()); + assertEquals(COMPLETED, new DatabaseSnapshotService(db.database, hostPaths, new ZipCompression(1)).snapshot(run).status()); BackupArchive archive = service.createArchive(run); @@ -155,7 +157,7 @@ void failedMergeLeavesNoArchiveBehind() throws Exception { assertThrows(IllegalStateException.class, () -> service.createArchive(run)); try (var files = Files.list(service.rootDirectory())) { - assertEquals(List.of("runs"), files.map(path -> path.getFileName().toString()).toList()); + assertEquals(List.of(BackupArchiveService.RUNS_DIRECTORY), files.map(path -> path.getFileName().toString()).toList()); } } @@ -164,10 +166,8 @@ void retentionKeepsNewestArchivesAndIgnoresUnrelatedZips() throws Exception { Path unrelated = Files.createDirectories(service.rootDirectory()).resolve("keep-me.zip"); Files.writeString(unrelated, "not a backup"); - for (int i = 0; i < 3; i++) { - createArchive(); - Thread.sleep(10); - } + seedArchives(2); + createArchive(); assertEquals(2, service.listArchives().size()); assertTrue(Files.exists(unrelated)); @@ -181,19 +181,16 @@ void deletesArchiveAndItsRecordById() throws Exception { assertFalse(service.deleteById(archive.id())); assertTrue(service.listArchives().isEmpty()); - assertTrue(db.fetchBackupById(archive.id()).isEmpty()); + assertTrue(db.backups.fetchBackupById(archive.id()).isEmpty()); } @Test void retentionDeletesRecordsOfRemovedArchives() throws Exception { - BackupArchive oldest = createArchive(); - Thread.sleep(10); - createArchive(); - Thread.sleep(10); + BackupArchive oldest = seedArchives(2).get(0); BackupArchive newest = createArchive(); - assertTrue(db.fetchBackupById(oldest.id()).isEmpty()); - assertTrue(db.fetchBackupById(newest.id()).isPresent()); + assertTrue(db.backups.fetchBackupById(oldest.id()).isEmpty()); + assertTrue(db.backups.fetchBackupById(newest.id()).isPresent()); } @Test @@ -204,7 +201,7 @@ void updatesAndPersistsRootDirectory() { assertEquals(newRoot, service.rootDirectory()); assertTrue(Files.isDirectory(newRoot)); - assertEquals(newRoot, new BackupArchiveService(properties, db).rootDirectory()); + assertEquals(newRoot, new BackupArchiveService(properties, db.settings, db.backups).rootDirectory()); } @Test @@ -231,10 +228,7 @@ void rejectsInvalidRootDirectories() throws Exception { @Test void persistsRetentionCountAndAppliesItOnNextArchive() throws Exception { - for (int i = 0; i < 2; i++) { - createArchive(); - Thread.sleep(10); - } + seedArchives(2); service.updateSettings(null, 1); @@ -242,7 +236,7 @@ void persistsRetentionCountAndAppliesItOnNextArchive() throws Exception { assertEquals(2, service.listArchives().size()); createArchive(); assertEquals(1, service.listArchives().size()); - assertEquals(1, new BackupArchiveService(properties, db).retentionCount()); + assertEquals(1, new BackupArchiveService(properties, db.settings, db.backups).retentionCount()); } @Test @@ -250,16 +244,16 @@ void usesPropertyRetentionUntilOneIsSaved() { assertEquals(2, service.retentionCount()); properties.setRetentionCount(0); - assertEquals(1, new BackupArchiveService(properties, db).retentionCount()); + assertEquals(1, new BackupArchiveService(properties, db.settings, db.backups).retentionCount()); } @Test void ignoresCorruptStoredRetention() { - db.saveSetting(RETENTION_COUNT_SETTING, "lots"); - assertEquals(2, new BackupArchiveService(properties, db).retentionCount()); + db.settings.saveSetting(RETENTION_COUNT_SETTING, "lots"); + assertEquals(2, new BackupArchiveService(properties, db.settings, db.backups).retentionCount()); - db.saveSetting(RETENTION_COUNT_SETTING, "0"); - assertEquals(2, new BackupArchiveService(properties, db).retentionCount()); + db.settings.saveSetting(RETENTION_COUNT_SETTING, "0"); + assertEquals(2, new BackupArchiveService(properties, db.settings, db.backups).retentionCount()); } @Test @@ -268,7 +262,7 @@ void updatesLocationAndRetentionTogether() { service.updateSettings(newRoot.toString(), 5); - BackupArchiveService restarted = new BackupArchiveService(properties, db); + BackupArchiveService restarted = new BackupArchiveService(properties, db.settings, db.backups); assertEquals(newRoot, restarted.rootDirectory()); assertEquals(5, restarted.retentionCount()); } @@ -282,14 +276,14 @@ void rejectsInvalidSettingsWithoutPartialWrites() { assertFalse(Files.exists(tempDir.resolve("never"))); assertEquals(tempDir.resolve("backups"), service.rootDirectory()); assertEquals(2, service.retentionCount()); - assertTrue(db.fetchSetting(RETENTION_COUNT_SETTING).isEmpty()); + 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.ARCHIVE_SUFFIX + ".tmp"), "x"); + Path tempZip = Files.writeString(service.rootDirectory().resolve("old" + BackupArchiveService.TEMP_SUFFIX), "x"); service.cleanupStaleArtifactsOnStartup(); @@ -297,12 +291,45 @@ void startupCleanupRemovesStaleArtifacts() throws Exception { 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.saveSetting("backup_root", "/marker"); + db.settings.saveSetting("backup_root", "/marker"); DatabaseHostPathResolver hostPaths = mock(DatabaseHostPathResolver.class); String entry = "srv/mediagarrd/db/mediagarrd.db"; - when(hostPaths.resolve(db.databaseFile())).thenReturn(Path.of("/" + entry)); + 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")); @@ -314,7 +341,7 @@ void theDatabaseSnapshotWinsOverServiceCopiesThatAreExcludedWhileCopying() throw 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, hostPaths, new ZipCompression(1)).snapshot(run); + var snapshot = new DatabaseSnapshotService(db.database, hostPaths, new ZipCompression(1)).snapshot(run); BackupArchive archive = service.createArchive(run); assertEquals(COMPLETED, snapshot.status()); @@ -336,15 +363,15 @@ void theDatabaseSnapshotWinsOverServiceCopiesThatAreExcludedWhileCopying() throw @Test void aLiveDatabaseCopyThatSlippedPastTheExclusionFailsTheMerge() throws Exception { DatabaseHostPathResolver hostPaths = mock(DatabaseHostPathResolver.class); - when(hostPaths.resolve(db.databaseFile())).thenReturn(Path.of("/srv/mediagarrd/db/mediagarrd.db")); + 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, hostPaths, new ZipCompression(1)).snapshot(run); + 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("runs"), files.map(path -> path.getFileName().toString()).toList()); + assertEquals(List.of(BackupArchiveService.RUNS_DIRECTORY), files.map(path -> path.getFileName().toString()).toList()); } } @@ -411,16 +438,6 @@ void mergesPartsWithMixedStoredAndDeflatedEntries() throws Exception { assertEquals(contents(archive.path()), streamed); } - @Test - void archivesWithoutASnapshotPartStillMerge() throws Exception { - Path run = service.createRunDirectory(); - part(run, "radarr", 0, "/srv/radarr", tar(file("radarr", "x"))); - - BackupArchive archive = service.createArchive(run); - - assertEquals(List.of("srv/radarr"), List.copyOf(contents(archive.path()).keySet())); - } - 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)); @@ -431,12 +448,126 @@ private static void part(Path run, String service, int index, String hostPath, j 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.addNewBackupRecord(new BackupRunResult(archive.id(), "start", "end", COMPLETED, List.of(), archive, null)); + 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 index 41fa227..b92dd93 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupCopyRoundsTest.java @@ -42,6 +42,8 @@ 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) @@ -56,10 +58,10 @@ class BackupCopyRoundsTest { private final DockerService docker = mock(DockerService.class); private final BackupArchiveService archives = mock(BackupArchiveService.class); private final DatabaseSnapshotService snapshots = mock(DatabaseSnapshotService.class); - private final DatabaseService db = mock(DatabaseService.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, db, mock(RunStatusBroadcaster.class)); + 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 { @@ -100,7 +102,7 @@ private void serve(String path, Item... items) { } private BackupRunResult runBackup(ServiceDefinition... services) { - when(db.fetchServices()).thenReturn(List.of(services)); + when(serviceRepository.fetchServices()).thenReturn(List.of(services)); return orchestrator.runBackup(); } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java index 145ad75..3d3b7fb 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java @@ -38,6 +38,9 @@ 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 { @@ -51,10 +54,13 @@ class BackupOrchestratorServiceTest { private final ServiceBackupRunner runner = mock(ServiceBackupRunner.class); private final BackupArchiveService archives = mock(BackupArchiveService.class); private final BackupScheduleService schedule = mock(BackupScheduleService.class); - private final DatabaseService db = mock(DatabaseService.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 BackupOrchestratorService orchestrator = new BackupOrchestratorService(runner, archives, schedule, snapshots, db, broadcaster); + 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() { @@ -70,26 +76,28 @@ void tearDown() { @Test void refusesToRunWithoutServices() { - when(db.fetchServices()).thenReturn(List.of()); + when(services.fetchServices()).thenReturn(List.of()); - assertThrows(BackupOrchestratorService.RunRejectedException.class, orchestrator::runBackup); + 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, db); - BackupOrchestratorService manual = new BackupOrchestratorService(runner, archives, realSchedule, snapshots, db, broadcaster); - when(db.fetchServices()).thenReturn(List.of()); + 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(BackupOrchestratorService.RunRejectedException.class, manual::runBackup); + assertThrows(RunRejectedException.class, manual::runBackup); assertEquals(before, realSchedule.getNextRun()); manual.shutdownRunnerExecutor(); @@ -98,7 +106,7 @@ void aRejectedManualRunLeavesTheRealScheduleUntouched() { @Test void aScheduledRunWithoutServicesDefersTheNextCheck() { when(schedule.dueNow()).thenReturn(true); - when(db.fetchServices()).thenReturn(List.of()); + when(services.fetchServices()).thenReturn(List.of()); orchestrator.scheduledRun(); @@ -110,7 +118,7 @@ void aScheduledRunWithoutServicesDefersTheNextCheck() { void aScheduledRunRejectedBecauseOneIsInProgressDoesNotDefer() throws Exception { CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); - when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(services.fetchServices()).thenReturn(List.of(RADARR)); when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); @@ -120,13 +128,179 @@ void aScheduledRunRejectedBecauseOneIsInProgressDoesNotDefer() throws Exception CompletableFuture manual = CompletableFuture.supplyAsync(orchestrator::runBackup); assertTrue(started.await(5, TimeUnit.SECONDS)); - assertThrows(BackupOrchestratorService.RunRejectedException.class, () -> orchestrator.runBackup(true)); + 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(); @@ -145,7 +319,7 @@ void completedWhenEveryServiceSucceeds() { assertEquals(List.of("radarr", "sonarr", SNAPSHOT), result.serviceNames()); result.serviceResults().forEach(r -> assertEquals("archive-1", r.runId())); verify(schedule).markRunStarted(); - verify(db).addNewBackupRecord(result); + verify(backups).addNewBackupRecord(result); verify(archives).removeRunDirectory(RUN_DIR); } @@ -157,6 +331,7 @@ void partialWhenSomeServicesFail() { assertEquals(PARTIAL, result.status()); assertEquals("sonarr: boom", result.errorMessage()); + verify(broadcaster).publishFinished(eq(PARTIAL), any(), any()); } @Test @@ -170,7 +345,7 @@ void partialWhenOnlyTheDatabaseSnapshotFails() { assertEquals(SNAPSHOT + ": boom", result.errorMessage()); assertEquals(ARCHIVE, result.archive()); result.serviceResults().forEach(r -> assertEquals("archive-1", r.runId())); - verify(db).addNewBackupRecord(result); + verify(backups).addNewBackupRecord(result); } @Test @@ -194,7 +369,7 @@ void aThrowingSnapshotStillProducesAPartialArchive() { assertEquals(PARTIAL, result.status()); assertEquals(SNAPSHOT + ": docker down", result.errorMessage()); assertEquals(ARCHIVE, result.archive()); - verify(db).addNewBackupRecord(result); + verify(backups).addNewBackupRecord(result); } @Test @@ -228,17 +403,18 @@ void skipsArchiveWhenEveryServiceFails() { assertFalse(orchestrator.isRunning()); ArgumentCaptor recorded = ArgumentCaptor.forClass(BackupRunResult.class); - verify(db).addNewBackupRecord(recorded.capture()); + 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(db.fetchServices()).thenReturn(List.of(RADARR, SONARR)); + 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)); @@ -256,15 +432,16 @@ void cleansUpWhenArchivingFails() { assertThrows(IllegalStateException.class, orchestrator::runBackup); verify(archives).removeRunDirectory(RUN_DIR); - verify(db, never()).addNewBackupRecord(any()); + 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(db.fetchServices()).thenReturn(List.of(RADARR)); + when(services.fetchServices()).thenReturn(List.of(RADARR)); when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); @@ -275,23 +452,18 @@ void rejectsConcurrentRuns() throws Exception { assertTrue(started.await(5, TimeUnit.SECONDS)); assertTrue(orchestrator.isRunning()); - assertThrows(BackupOrchestratorService.RunRejectedException.class, orchestrator::runBackup); + assertThrows(RunRejectedException.class, orchestrator::runBackup); release.countDown(); assertEquals(COMPLETED, first.get(5, TimeUnit.SECONDS).status()); assertFalse(orchestrator.isRunning()); } - @Test - void configChangesRunWhileIdle() { - assertEquals("changed", orchestrator.whileIdle(() -> "changed")); - } - @Test void configChangesAreRejectedDuringABackupRun() throws Exception { CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); - when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(services.fetchServices()).thenReturn(List.of(RADARR)); when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); @@ -301,11 +473,11 @@ void configChangesAreRejectedDuringABackupRun() throws Exception { CompletableFuture run = CompletableFuture.supplyAsync(orchestrator::runBackup); assertTrue(started.await(5, TimeUnit.SECONDS)); - assertThrows(BackupOrchestratorService.BackupInProgressException.class, () -> orchestrator.whileIdle(() -> "changed")); + assertThrows(BackupInProgressException.class, () -> lifecycle.whileIdle(() -> "changed")); release.countDown(); run.get(5, TimeUnit.SECONDS); - assertEquals("changed", orchestrator.whileIdle(() -> "changed")); + assertEquals("changed", lifecycle.whileIdle(() -> "changed")); } @Test @@ -314,7 +486,7 @@ void backupWaitsForInFlightConfigChange() throws Exception { CountDownLatch finishChange = new CountDownLatch(1); givenResults(COMPLETED, COMPLETED); - CompletableFuture change = CompletableFuture.supplyAsync(() -> orchestrator.whileIdle(() -> { + CompletableFuture change = CompletableFuture.supplyAsync(() -> lifecycle.whileIdle(() -> { changing.countDown(); try { finishChange.await(); @@ -328,7 +500,7 @@ void backupWaitsForInFlightConfigChange() throws Exception { CompletableFuture run = CompletableFuture.supplyAsync(orchestrator::runBackup); Thread.sleep(100); assertFalse(run.isDone()); - verify(db, never()).fetchServices(); + verify(services, never()).fetchServices(); finishChange.countDown(); assertEquals("changed", change.get(5, TimeUnit.SECONDS)); @@ -341,8 +513,8 @@ void publishesStartedBeforeWorkAndFinishedWithTheRunStatus() { orchestrator.runBackup(); - var order = inOrder(broadcaster, runner, db); - order.verify(db).fetchServices(); + 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()); @@ -350,37 +522,9 @@ void publishesStartedBeforeWorkAndFinishedWithTheRunStatus() { verify(broadcaster, org.mockito.Mockito.times(1)).publishFinished(any(), any(), any()); } - @Test - void publishesPartialWhenSomeServicesFail() { - givenResults(COMPLETED, FAILED); - - orchestrator.runBackup(); - - verify(broadcaster).publishFinished(eq(PARTIAL), any(), any()); - } - - @Test - void publishesFailedWhenEveryServiceFails() { - givenResults(FAILED, FAILED); - - assertThrows(IllegalStateException.class, orchestrator::runBackup); - - verify(broadcaster).publishFinished(eq(FAILED), any(), any()); - } - - @Test - void publishesFailedWhenArchivingThrows() { - givenResults(COMPLETED, COMPLETED); - when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); - - assertThrows(IllegalStateException.class, orchestrator::runBackup); - - verify(broadcaster).publishFinished(eq(FAILED), any(), any()); - } - @Test void publishesFailedWhenTheRunDirectoryCannotBeCreated() { - when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(services.fetchServices()).thenReturn(List.of(RADARR)); when(archives.createRunDirectory()).thenThrow(new IllegalStateException("no space")); assertThrows(IllegalStateException.class, orchestrator::runBackup); @@ -393,7 +537,7 @@ void publishesFailedWhenTheRunDirectoryCannotBeCreated() { @Test void publishesFailedWhenRecordingTheRunThrows() { givenResults(COMPLETED, COMPLETED); - doThrow(new IllegalStateException("db locked")).when(db).addNewBackupRecord(any()); + doThrow(new IllegalStateException("db locked")).when(backups).addNewBackupRecord(any()); assertThrows(IllegalStateException.class, orchestrator::runBackup); @@ -425,7 +569,7 @@ void aFailingCleanupDoesNotStickTheRunningFlag() { assertEquals(COMPLETED, result.status()); assertFalse(orchestrator.isRunning()); verify(broadcaster).publishFinished(eq(COMPLETED), any(), any()); - assertEquals("changed", orchestrator.whileIdle(() -> "changed")); + assertEquals("changed", lifecycle.whileIdle(() -> "changed")); assertEquals(COMPLETED, orchestrator.runBackup().status()); } @@ -455,7 +599,7 @@ void aFailingPublishNeverBreaksTheRun() { void aRejectedConcurrentRunPublishesNothingExtra() throws Exception { CountDownLatch started = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); - when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(services.fetchServices()).thenReturn(List.of(RADARR)); when(runner.copyPaths(eq(RADARR), any(), any(), any(), any())).thenAnswer(invocation -> { started.countDown(); release.await(); @@ -464,7 +608,7 @@ void aRejectedConcurrentRunPublishesNothingExtra() throws Exception { CompletableFuture first = CompletableFuture.supplyAsync(orchestrator::runBackup); assertTrue(started.await(5, TimeUnit.SECONDS)); - assertThrows(BackupOrchestratorService.RunRejectedException.class, orchestrator::runBackup); + assertThrows(RunRejectedException.class, orchestrator::runBackup); verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); verify(broadcaster, never()).publishFinished(any(), any(), any()); @@ -503,7 +647,7 @@ void aFinishIsNeverOvertakenByTheNextRunsStart() throws Exception { } private void givenResults(String radarrStatus, String sonarrStatus) { - when(db.fetchServices()).thenReturn(List.of(RADARR, SONARR)); + 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)); } 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 index ba05b43..b364699 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java @@ -2,11 +2,20 @@ 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; @@ -14,6 +23,11 @@ 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 { @@ -21,87 +35,358 @@ class BackupScheduleServiceTest { Path tempDir; private MediaGarrdProperties properties; - private DatabaseService db; + private TestDatabase db; + private MutableClock clock; + private SetupService setup; @BeforeEach void setUp() { properties = new MediaGarrdProperties(); properties.setDatabasePath(tempDir.resolve("mediagarrd.db").toString()); - db = new DatabaseService(properties); + 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() throws Exception { - BackupScheduleService service = new BackupScheduleService(properties, db); - service.updateInterval(Duration.ofMillis(1)); + void updatesAndEvaluatesDueState() { + BackupScheduleService service = service(); + service.updateInterval(Duration.ofMinutes(15)); - assertEquals(Duration.ofMillis(1), service.getInterval()); + assertEquals(Duration.ofMinutes(15), service.getInterval()); + assertFalse(service.dueNow()); - Thread.sleep(5); + clock.advance(Duration.ofMinutes(15)); assertTrue(service.dueNow()); } @Test void notDueUntilIntervalElapses() { - BackupScheduleService service = new BackupScheduleService(properties, db); + 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 usesPropertyIntervalUntilOneIsSaved() { + void persistsUpdatedIntervalAcrossRestarts() { properties.setBackupInterval(Duration.ofHours(3)); + BackupScheduleService first = service(); + assertEquals(Duration.ofHours(3), first.getInterval()); + + first.updateInterval(Duration.ofMinutes(45)); - assertEquals(Duration.ofHours(3), new BackupScheduleService(properties, db).getInterval()); + assertEquals(Optional.of("PT45M"), db.settings.fetchSetting(BACKUP_INTERVAL_SETTING)); + assertEquals(Duration.ofMinutes(45), service().getInterval()); } @Test - void persistsUpdatedIntervalAcrossRestarts() { - properties.setBackupInterval(Duration.ofHours(3)); - new BackupScheduleService(properties, db).updateInterval(Duration.ofMinutes(45)); + 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(); - assertEquals(Optional.of("PT45M"), db.fetchSetting(BACKUP_INTERVAL_SETTING)); - assertEquals(Duration.ofMinutes(45), new BackupScheduleService(properties, db).getInterval()); + assertTrue(restarted.dueNow()); + assertEquals(clock.instant(), restarted.getNextRun()); } @Test - void invalidIntervalsFallBackToTwelveHours() { - BackupScheduleService service = new BackupScheduleService(properties, db); + void changingTheIntervalRecomputesFromTheLastBackup() { + completeSetup(); + properties.setBackupInterval(Duration.ofHours(12)); + Instant last = clock.instant().minus(Duration.ofHours(5)); + recordBackup("run-1", COMPLETED, last); + BackupScheduleService service = service(); - assertEquals(Duration.ofHours(12), service.updateInterval(null)); - assertEquals(Duration.ofHours(12), service.updateInterval(Duration.ZERO)); - assertEquals(Duration.ofHours(12), service.updateInterval(Duration.ofMinutes(-5))); + 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.saveSetting(BACKUP_INTERVAL_SETTING, "every tuesday"); - assertEquals(Duration.ofHours(2), new BackupScheduleService(properties, db).getInterval()); + db.settings.saveSetting(BACKUP_INTERVAL_SETTING, "every tuesday"); + assertEquals(Duration.ofHours(2), service().getInterval()); - db.saveSetting(BACKUP_INTERVAL_SETTING, "PT0S"); - assertEquals(Duration.ofHours(2), new BackupScheduleService(properties, db).getInterval()); + db.settings.saveSetting(BACKUP_INTERVAL_SETTING, "PT0S"); + assertEquals(Duration.ofHours(2), service().getInterval()); } @Test - void deferringTheNextRunStopsItBeingDueUntilTheIntervalElapses() throws Exception { - BackupScheduleService service = new BackupScheduleService(properties, db); - service.updateInterval(Duration.ofMillis(1)); - Thread.sleep(5); + void deferringTheNextRunStopsItBeingDueUntilTheIntervalElapses() { + BackupScheduleService service = service(); + service.updateInterval(Duration.ofMinutes(15)); + clock.advance(Duration.ofMinutes(15)); assertTrue(service.dueNow()); service.updateInterval(Duration.ofHours(1)); - Thread.sleep(5); + clock.advance(Duration.ofMinutes(10)); service.deferNextRun(); assertFalse(service.dueNow()); - assertTrue(service.getNextRun().isAfter(java.time.Instant.now().plus(Duration.ofMinutes(59)))); + 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 = new BackupScheduleService(properties, db); + BackupScheduleService service = service(); service.deferNextRun(); assertFalse(service.dueNow()); @@ -112,8 +397,8 @@ void addingAServiceAfterADeferralMakesTheScheduleDueNow() { @Test void releasingWithoutADeferralChangesNothing() { - BackupScheduleService service = new BackupScheduleService(properties, db); - java.time.Instant before = service.getNextRun(); + BackupScheduleService service = service(); + Instant before = service.getNextRun(); service.releaseDeferral(); diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java index 71c77c3..47a680b 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/ContainerEnvironmentTest.java @@ -29,14 +29,6 @@ void findsTheContainerIdFromTheHostnameMountEvenWhenHostnameIsWrong() throws Exc assertEquals(List.of(ID), environment.containerIdCandidates()); } - @Test - void neverFallsBackToTheHostnameWhenMountinfoGivesAnId() throws Exception { - ContainerEnvironment environment = environment(mountInfo( - "4 1 8:1 /var/lib/docker/containers/" + ID + "/hostname /etc/hostname rw - ext4 /dev/sda1 rw"), "other-container"); - - 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"; diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java index 559a0c5..c8a74b2 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseHostPathResolverTest.java @@ -58,13 +58,6 @@ void mapsThroughABindMount() throws Exception { assertEquals(Path.of("/home/u/data/server/db/mediagarrd.db"), resolver.resolve(database)); } - @Test - void mapsThroughANamedVolume() throws Exception { - when(docker.mountsOf("abc")).thenReturn(List.of(mount(databaseDirectory.toString(), "/var/lib/docker/volumes/db/_data"))); - - assertEquals(Path.of("/var/lib/docker/volumes/db/_data/mediagarrd.db"), resolver.resolve(database)); - } - @Test void picksTheLongestMatchingMount() throws Exception { when(docker.mountsOf("abc")).thenReturn(List.of( 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/DatabaseServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java deleted file mode 100644 index 1f3ee24..0000000 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseServiceTest.java +++ /dev/null @@ -1,488 +0,0 @@ -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.assertTimeoutPreemptively; -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.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.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Set; -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.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.model.BackupServiceResult; -import wellatleastitried.mediagarrdServer.model.FetchedBackupRecord; -import wellatleastitried.mediagarrdServer.model.FetchedBackupServiceRecord; -import wellatleastitried.mediagarrdServer.model.ServiceDefinition; - -class DatabaseServiceTest { - - private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr/config", "/srv/radarr/data")); - - @TempDir - Path tempDir; - - private MediaGarrdProperties properties; - private DatabaseService db; - - @BeforeEach - void setUp() { - properties = new MediaGarrdProperties(); - properties.setDatabasePath(tempDir.resolve("nested/mediagarrd.db").toString()); - db = new DatabaseService(properties); - } - - @Test - void createsDatabaseFileAndParentDirectories() { - assertTrue(Files.isRegularFile(tempDir.resolve("nested/mediagarrd.db"))); - assertTrue(db.verifyDatabaseIntegrity()); - assertTrue(db.verifyDatabaseIntegrity()); - } - - @Test - void storesBackupRecordWithEveryServiceResult() { - db.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.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.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.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.addNewBackupRecord(backupRun("older", "2026-01-01 00:00:00")); - db.addNewBackupRecord(backupRun("newer", "2026-02-01 00:00:00")); - - assertEquals("newer", db.fetchLatestBackupRecord().orElseThrow().archiveId()); - } - - @Test - void returnsEmptyForMissingBackupRecords() { - assertTrue(db.fetchBackupById("missing").isEmpty()); - assertTrue(db.fetchLatestBackupRecord().isEmpty()); - } - - @Test - void deletesBackupRecord() { - db.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00")); - - db.deleteBackupRecordById("run-1"); - - assertTrue(db.fetchBackupById("run-1").isEmpty()); - } - - @Test - void deletingBackupRecordCascadesToServiceRows() throws Exception { - db.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00", serviceResult("radarr", COMPLETED, null))); - assertEquals(1, count("backup_services")); - - db.deleteBackupRecordById("run-1"); - - assertEquals(0, count("backup_services")); - } - - @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 DatabaseService(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 storesAndFetchesServicesWithPathOrderPreserved() { - assertEquals(List.of(), db.fetchServices()); - - db.addService(RADARR); - - assertEquals(Optional.of(RADARR), db.fetchService("radarr")); - assertEquals(Optional.of(RADARR), db.fetchService("RADARR")); - assertEquals(List.of(RADARR), db.fetchServices()); - } - - @Test - void listsServicesSortedByNameIgnoringCase() { - db.addService(new ServiceDefinition("sonarr", List.of("/a"))); - db.addService(new ServiceDefinition("Jellyfin", List.of("/b"))); - db.addService(new ServiceDefinition("radarr", List.of("/c"))); - - assertEquals(List.of("Jellyfin", "radarr", "sonarr"), db.fetchServices().stream().map(ServiceDefinition::name).toList()); - } - - @Test - void rejectsDuplicateServiceNamesIgnoringCase() { - db.addService(RADARR); - - assertThrows(IllegalStateException.class, () -> db.addService(new ServiceDefinition("Radarr", List.of("/other")))); - } - - @Test - void updatesServiceNameAndPaths() { - db.addService(RADARR); - ServiceDefinition renamed = new ServiceDefinition("radarr-4k", List.of("/srv/radarr-4k")); - - assertTrue(db.updateService("radarr", renamed)); - - assertTrue(db.fetchService("radarr").isEmpty()); - assertEquals(Optional.of(renamed), db.fetchService("radarr-4k")); - assertFalse(db.updateService("missing", renamed)); - } - - @Test - void removesService() { - db.addService(RADARR); - - assertTrue(db.removeService("radarr")); - assertFalse(db.removeService("radarr")); - assertEquals(List.of(), db.fetchServices()); - } - - @Test - void savesAndOverwritesSettings() { - assertTrue(db.fetchSetting("backup_root").isEmpty()); - - db.saveSetting("backup_root", "/first"); - db.saveSetting("backup_root", "/second"); - - assertEquals(Optional.of("/second"), db.fetchSetting("backup_root")); - } - - @Test - void persistsDataAcrossInstances() { - db.addService(RADARR); - db.saveSetting("backup_root", "/backups"); - - DatabaseService reopened = new DatabaseService(properties); - - assertEquals(List.of(RADARR), reopened.fetchServices()); - assertEquals(Optional.of("/backups"), reopened.fetchSetting("backup_root")); - } - - @Test - void failsLoudlyWhenDatabaseIsUnusable() { - properties.setDatabasePath(tempDir.toString()); - DatabaseService broken = new DatabaseService(properties); - - assertFalse(broken.verifyDatabaseIntegrity()); - assertThrows(IllegalStateException.class, broken::fetchServices); - assertThrows(IllegalStateException.class, () -> broken.addService(RADARR)); - assertThrows(IllegalStateException.class, () -> broken.fetchSetting("backup_root")); - } - - @Test - void verifiesOnlyOnceWhileTheSchemaIsUnchanged() { - AtomicInteger verifications = new AtomicInteger(); - DatabaseService counted = new DatabaseService(properties) { - @Override - protected synchronized boolean verifyDatabaseIntegrity() { - verifications.incrementAndGet(); - return super.verifyDatabaseIntegrity(); - } - }; - - counted.addService(RADARR); - counted.fetchServices(); - counted.fetchSetting("backup_root"); - - assertEquals(1, verifications.get()); - } - - @Test - void rebuildsWhenTheDatabaseFileIsDeleted() throws Exception { - db.addService(RADARR); - - Files.delete(databaseFile()); - - assertEquals(List.of(), db.fetchServices()); - db.addService(RADARR); - assertEquals(List.of(RADARR), db.fetchServices()); - } - - @Test - void rebuildsWhenTheDatabaseDirectoryIsDeleted() throws Exception { - Files.delete(databaseFile()); - Files.delete(databaseFile().getParent()); - - db.saveSetting("backup_root", "/backups"); - - assertEquals(Optional.of("/backups"), db.fetchSetting("backup_root")); - } - - @Test - void rebuildsWhenATableIsDropped() throws Exception { - try (var connection = rawConnection(); var statement = connection.createStatement()) { - statement.execute("DROP TABLE services"); - } - - db.addService(RADARR); - - assertEquals(List.of(RADARR), db.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.fetchServices(); - - assertEquals(0, count("backup_services")); - } - - @Test - void movesACorruptDatabaseAsideOnStartup() throws Exception { - Files.writeString(databaseFile(), "x".repeat(4096)); - - DatabaseService recovered = new DatabaseService(properties); - - recovered.addService(RADARR); - assertEquals(List.of(RADARR), recovered.fetchServices()); - assertEquals(List.of("x".repeat(4096)), quarantinedContents()); - } - - @Test - void movesACorruptDatabaseAsideWhileRunning() throws Exception { - db.addService(RADARR); - Files.writeString(databaseFile(), "x".repeat(4096)); - - assertEquals(List.of(), db.fetchServices()); - assertEquals(1, quarantinedContents().size()); - } - - @Test - void snapshotIsAValidCopyWithTheSameRowsAndVersion() throws Exception { - db.addService(RADARR); - db.saveSetting("backup_root", "/backups"); - db.addNewBackupRecord(backupRun("run-1", "2026-01-01 00:00:00", serviceResult("radarr", COMPLETED, null))); - Path snapshot = tempDir.resolve("snapshot.db"); - - db.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.fetchServices()); - } - - @Test - void snapshotHandlesQuotesInTheTargetPath() throws Exception { - Path snapshot = Files.createDirectories(tempDir.resolve("it's here")).resolve("snapshot.db"); - - db.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.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.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.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); - DatabaseService paused = new DatabaseService(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.saveSetting("backup_root", "/before"); - - CompletableFuture snapshot = CompletableFuture.runAsync(() -> { - try { - paused.snapshotTo(tempDir.resolve("snapshot.db")); - } catch (Exception e) { - throw new IllegalStateException(e); - } - }); - assertTrue(snapshotting.await(5, TimeUnit.SECONDS)); - - CompletableFuture write = CompletableFuture.runAsync(() -> paused.saveSetting("backup_root", "/during")); - CompletableFuture delete = CompletableFuture.runAsync(() -> paused.deleteBackupRecordById("none")); - CompletableFuture insert = CompletableFuture.runAsync(() -> - paused.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.fetchSetting("backup_root")); - assertTrue(paused.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.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.saveSetting("backup_root", "/" + n); - db.fetchServices(); - db.verifyDatabaseIntegrity(); - } - })); - } - CompletableFuture.allOf(work.toArray(CompletableFuture[]::new)).get(); - }); - } - - private Path databaseFile() { - return Path.of(properties.getDatabasePath()); - } - - private 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(); - } - } - - private Connection rawConnection() throws SQLException { - return DriverManager.getConnection("jdbc:sqlite:" + properties.getDatabasePath()); - } - - private int count(String table) throws SQLException { - try (var connection = rawConnection(); var rs = connection.createStatement().executeQuery("SELECT COUNT(*) FROM " + table)) { - return rs.getInt(1); - } - } - - private 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); - } - - private 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/service/DatabaseSnapshotServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java index fba6743..02a00bb 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DatabaseSnapshotServiceTest.java @@ -26,6 +26,7 @@ import wellatleastitried.mediagarrdServer.MediaGarrdProperties; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +import wellatleastitried.mediagarrdServer.repository.TestDatabase; class DatabaseSnapshotServiceTest { @@ -34,7 +35,7 @@ class DatabaseSnapshotServiceTest { @TempDir Path tempDir; - private DatabaseService db; + private TestDatabase db; private DatabaseHostPathResolver hostPaths; private DatabaseSnapshotService snapshots; private Path run; @@ -43,19 +44,19 @@ class DatabaseSnapshotServiceTest { void setUp() throws Exception { MediaGarrdProperties properties = new MediaGarrdProperties(); properties.setDatabasePath(tempDir.resolve("db/mediagarrd.db").toString()); - db = new DatabaseService(properties); + db = new TestDatabase(properties); hostPaths = mock(DatabaseHostPathResolver.class); - when(hostPaths.resolve(db.databaseFile())).thenReturn(HOST_DATABASE); - snapshots = new DatabaseSnapshotService(db, hostPaths, new ZipCompression(1)); + 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.addService(new ServiceDefinition("radarr", List.of("/srv/radarr"))); - Files.setPosixFilePermissions(db.databaseFile(), PosixFilePermissions.fromString("rw-r-----")); - Integer uid = (Integer) Files.getAttribute(db.databaseFile(), "unix:uid"); - Integer gid = (Integer) Files.getAttribute(db.databaseFile(), "unix:gid"); + 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); @@ -83,7 +84,7 @@ void writesTheSnapshotAtTheHostPathWithTheLiveFileMetadata() throws Exception { @Test void failsWithoutAPartWhenTheHostPathCannotBeResolved() throws Exception { - when(hostPaths.resolve(db.databaseFile())).thenThrow(new IOException("no mount covers the database")); + when(hostPaths.resolve(db.database.databaseFile())).thenThrow(new IOException("no mount covers the database")); BackupServiceResult result = snapshots.snapshot(run); @@ -94,30 +95,30 @@ void failsWithoutAPartWhenTheHostPathCannotBeResolved() throws Exception { @Test void failsWithoutAPartWhenTheDatabaseIsMissing() throws Exception { - Files.delete(db.databaseFile()); + Files.delete(db.database.databaseFile()); BackupServiceResult result = snapshots.snapshot(run); assertEquals(FAILED, result.status()); - assertEquals("Database file " + db.databaseFile() + " does not exist", result.errorMessage()); - assertFalse(Files.exists(db.databaseFile())); + 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.databaseFile(), "x".repeat(4096)); + Files.writeString(db.database.databaseFile(), "x".repeat(4096)); BackupServiceResult result = snapshots.snapshot(run); assertEquals(FAILED, result.status()); - assertEquals("x".repeat(4096), Files.readString(db.databaseFile())); + assertEquals("x".repeat(4096), Files.readString(db.database.databaseFile())); assertNoPart(); } @Test void resolverFailuresOfAnyKindBecomeAFailedResult() throws Exception { - when(hostPaths.resolve(db.databaseFile())).thenThrow(new IllegalStateException("docker down")); + when(hostPaths.resolve(db.database.databaseFile())).thenThrow(new IllegalStateException("docker down")); assertEquals("docker down", snapshots.snapshot(run).errorMessage()); } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java index d9fca86..2205276 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/DockerServiceTest.java @@ -2,6 +2,7 @@ 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; @@ -22,6 +23,7 @@ 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; @@ -158,8 +160,13 @@ void configHashDependsOnPathsNotTheirOrder() { } @Test - void mapsHostPathsUnderMountRoot() { - assertEquals("/mnt/srv/radarr/config", DockerService.containerPath("/srv/radarr/config")); + 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) { @@ -176,4 +183,19 @@ private static String bind(String hostPath) { 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/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(), "