diff --git a/.dockerignore b/.dockerignore index c843ac6..5b09deb 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,12 @@ .git +.jj +.claude +.env +ref +bin +.settings +.classpath +.project .github .vscode build @@ -14,7 +22,6 @@ secrets .gitignore LICENSE README.md -install-util.sh -install.sh CHANGELOG -docker-compose.yml.example +docker-compose.yml +docker-compose.example.yml diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..79f75b9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,59 @@ +name: Bug report +description: Create a report to help us improve +title: "[BUG]: " +labels: ['Type: Bug', 'Status: Needs Triage'] +body: + - type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please search to see if an open or closed issue already exists for the feature you are requesting. If a request exists and is closed note that it may only be fixed in an unstable branch. + options: + - label: I have searched the existing open and closed issues + required: true + - type: textarea + attributes: + label: Describe the bug + description: A clear and concise description of what the bug is. + validations: + required: true + - type: textarea + attributes: + label: To Reproduce + description: | + Steps to reproduce the behavior: + 1. Go to '...' + 2. Click on '....' + 3. Scroll down to '....' + 4. See error + validations: + required: true + - type: textarea + attributes: + label: Expected behavior + description: A clear and concise description of what you expected to happen. + validations: + required: true + - type: textarea + attributes: + label: Screenshots + description: If applicable, add screenshots to help explain your problem. + validations: + required: false + - type: input + attributes: + label: OS + description: e.g. Linux + validations: + required: false + - type: input + attributes: + label: Version + description: e.g. 22 + validations: + required: false + - type: textarea + attributes: + label: Additional context + description: Add any other context about the problem here. + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..3ba13e0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..7e6c25b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,39 @@ +name: Feature Request +description: Suggest an idea for this project +title: "[FEAT]: " +labels: ['Type: Feature', 'Status: Needs Triage'] +body: +- type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please search to see if an open or closed issue already exists for the feature you are requesting. If a request exists and is closed note that it may only be fixed in an unstable branch. + options: + - label: I have searched the existing open and closed issues + required: true +- type: textarea + attributes: + label: Is your feature request related to a problem? Please describe + description: A clear and concise description of what the problem is. + validations: + required: true +- type: textarea + attributes: + label: Describe the solution you'd like + description: A clear and concise description of what you want to happen. + validations: + required: true +- type: textarea + attributes: + label: Describe alternatives you've considered + description: A clear and concise description of any alternative solutions or features you've considered. + validations: + required: true +- type: textarea + attributes: + label: Anything else? + description: | + Links? References? Mockups? Anything that will give us more context about the feature you are encountering! + + Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. + validations: + required: true diff --git a/.github/workflows/integration-dev.yml b/.github/workflows/integration-dev.yml new file mode 100644 index 0000000..80c6dd4 --- /dev/null +++ b/.github/workflows/integration-dev.yml @@ -0,0 +1,17 @@ +name: Integration Test Dev Branch with Server + +on: + push: + branches: + - dev + pull_request: + +jobs: + integration-test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: MediaGarrd/MediaGarrd-Stack-Testing@main + with: + server-branch: dev + client-branch: ${{ github.head_ref || github.ref_name }} diff --git a/.github/workflows/integration-main.yml b/.github/workflows/integration-main.yml new file mode 100644 index 0000000..bd5d151 --- /dev/null +++ b/.github/workflows/integration-main.yml @@ -0,0 +1,16 @@ +name: Integration Test Main Branch with Server + +on: + push: + branches: + - main + +jobs: + integration-test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: MediaGarrd/MediaGarrd-Stack-Testing@main + with: + server-branch: main + client-branch: main diff --git a/.github/workflows/issue_handling.yml b/.github/workflows/issue_handling.yml new file mode 100644 index 0000000..a9f75ca --- /dev/null +++ b/.github/workflows/issue_handling.yml @@ -0,0 +1,55 @@ +name: Handle duplicate status label + +on: + issues: + types: [labeled, unlabeled] + +jobs: + correct-status-labels: + runs-on: ubuntu-latest + steps: + - name: Ensure one Status label per issue + uses: actions/github-script@v7 + with: + github-token: ${{ secrets.MEDIAGARRD_CLIENT_ACTIONS_TOKEN }} + script: | + const issueNumber = context.payload.issue.number; + const statusLabelsToCheck = [ + "Status: Needs Triage", + "Status: Approved", + "Status: Waiting on Child Issues", + "Status: Waiting on Server Update" + ]; + + const existingLabels = context.payload.issue.labels.map(label => label.name); + const existingStatusLabels = existingLabels.filter(label => statusLabelsToCheck.includes(label)); + const addedLabel = context.payload.action === "labeled" ? context.payload.label.name : null; + + let keep = null; + if (statusLabelsToCheck.includes(addedLabel)) { + keep = addedLabel; + } else if (existingStatusLabels.length == 1) { + keep = existingStatusLabels[0]; + } + + for (const label of existingStatusLabels.filter(label => label !== keep)) { + await github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + name: label + }); + console.log(`Removed label "${label}" from issue #${issueNumber}`); + } + + if (keep) { + console.log(`Status label: "${keep}" is set correctly`); + } else { + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + labels: ["Status: Needs Triage"] + }); + } + diff --git a/.github/workflows/pr_handling.yml b/.github/workflows/pr_handling.yml new file mode 100644 index 0000000..fe9016a --- /dev/null +++ b/.github/workflows/pr_handling.yml @@ -0,0 +1,46 @@ +name: Require approved issue + +on: + pull_request: + types: [opened, edited, reopened, synchronize] + +jobs: + require-approved-issue: + if: github.head_ref != 'dev' + runs-on: ubuntu-latest + permissions: + issues: read + pull-requests: read + steps: + - name: Ensure every linked issue is approved + uses: actions/github-script@v7 + with: + script: | + const { repository } = await github.graphql(` + query($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + closingIssuesReferences(first: 25) { + nodes { number labels(first: 25) { nodes { name } } } + } + } + } + }`, { + owner: context.repo.owner, + repo: context.repo.repo, + number: context.payload.pull_request.number + }); + + const issues = repository.pullRequest.closingIssuesReferences.nodes; + if (issues.length === 0) { + core.setFailed("Link the approved issue this pull request resolves, e.g. \"Closes #12\" in the description"); + return; + } + + const unapproved = issues.filter(issue => !issue.labels.nodes.some(label => label.name === "Status: Approved")); + if (unapproved.length > 0) { + core.setFailed(`Linked issues without "Status: Approved": ${unapproved.map(issue => `#${issue.number}`).join(", ")}`); + return; + } + + console.log(`All linked issues are approved: ${issues.map(issue => `#${issue.number}`).join(", ")}`); diff --git a/.gitignore b/.gitignore index 6703b86..6feddf8 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ .gradle .settings/ build -gradle/ **/.settings/ **/.project **/.classpath diff --git a/CHANGELOG b/CHANGELOG index e69de29..ff7948a 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -0,0 +1,107 @@ +# 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 +- Switching the active server between two known servers that are not paired now updates the dashboard (state and event stream) straight away; before, it kept showing the previous server until something else refreshed it +- Events forwarded from the server to the dashboard are re-serialized as compact JSON on one line, so a server cannot add its own event fields to the dashboard stream +- A backup whose file name does not end in `.zip` (or ends in `.part`) is refused before anything is downloaded: a manual pickup answers `400`, an automatic one is skipped and logged as a warning +- After a successful automatic pickup, the client removes the earlier `*-media-backup-AD.zip` copies of the older archives the active server still lists, not only the one before the latest. Newer copies, copies of archives the server no longer lists (for example from another server), your own copies (`*-media-backup.zip`) and other files are never touched + +## 11-22-26 +- A state file the client cannot read (wrong owner or permissions, for example after switching to `user:`) now stops startup with a message naming the file and the UID, instead of being moved aside as `.corrupt-*` and dropping every pairing. Only a file that is really malformed is moved aside +- The pickup interval is limited to 365 days: `PUT /api/client/pickup-interval` answers `400` above that, the dashboard field takes at most 525600 minutes and checks it, and an out-of-range value in the state file or `CLIENT_PICKUP_INTERVAL` is ignored with a warning in favour of the default of 12 hours +- A server that has no backups yet is reported once at INFO, then only at DEBUG on each retry, instead of a WARN every time +- The image has a `HEALTHCHECK` that asks the dashboard's open `/api/auth/status` on `CLIENT_PORT` +- Documented that with `network_mode: host` `CLIENT_PORT` must stay at 1024 or above and that `cap_drop: ALL` needs `CHOWN`, `SETUID` and `SETGID` (or `user:`), and that the `MEDIAGARRD_SERVER_CA` file must be readable by UID 1000 or `PUID` +- The container no longer runs Java as root. It starts as root only to give UID 1000 (or `PUID` and `PGID`) ownership of the state and download folders and of the client's own files in them (the state file with its `.tmp` and `.corrupt-*` copies, `password.json`, and `*-media-backup.zip`, `*-media-backup-AD.zip` and their `.part` files), then runs the client as that user. Other files in your folders are left alone, and the state folder is never changed recursively. Existing installs keep working without a manual `chown`; with `user:` in Compose the entrypoint skips the ownership step, so the folders must already belong to that user. `PUID=0` keeps running as root. The base image is pinned to `eclipse-temurin:21.0.13_9-jre` +- A scan merges the servers it finds into Known Servers instead of replacing the list: servers already known (for example an `https://` one outside the LAN) stay, new ones are added, and the active server stays selected +- Server Configuration checks the backup interval (15 minutes to 365 days, as the server does; the field takes 0.25 to 8760 hours) before sending anything, and `PUT /api/client/server-config` answers `400` for an interval outside that range without changing the location or retention either +- Clearer messages: a server that has not paired this client no longer produces "Connect to a server" hints, Server Configuration says to pair on the Dashboard, a proxy timeout reads as one instead of "POST ... failed (504)", the rejected-token note leads with a pairing code, and disabled buttons are muted +- Pairing confirms itself: after the server issues a token the client makes one authenticated request (`GET /api/v1/health`) to confirm it, retried up to 3 times after a network error or a 502, 503 or 504. The client stores the token first and discards it only when the server refuses the confirmation (a `401` or a reply that is not a confirmation, reported as a `400` or `502`), so the same PIN or pairing code can be entered again; any other failure keeps the token, answers `paired: true` with a new `note` saying the server confirms it on the next connection, and a lost reply can no longer leave the server with a client the Client has forgotten. Pairing while a stored token still works is refused with `409` (unpair first), and pairing and unpairing no longer run at the same time +- The warnings after unpairing no longer point at the server's `/config` page (it is disabled after setup); they say to remove the client with `DELETE /api/v1/clients/{id}` on the server +- Works with the Server's confirm-on-first-use pairing (Server 11-22-26) and with earlier 11-19-26 servers, where the confirmation request simply succeeds + +## 11-21-26 +- Server Configuration has a Failure Notifications panel for the server's optional failure webhook: Save, Clear and Send Test, showing only `Configured: https://host` (the URL is a secret and is never shown or pre-filled). New proxy endpoints `GET` and `PUT /api/client/notifications/webhook` and `POST /api/client/notifications/webhook/test`; a `429` from the server's test cooldown is passed on with its `Retry-After` +- Fixed the missing space between the note and the first field of the set-password form +- Routine reads (`GET /api/client/server-config` and `/services`, and the event stream's "subscribing" and "no event stream" lines, and a preferred server that does not answer) are logged at DEBUG instead of INFO, so polling no longer fills the log; changes, pairing, downloads and errors still log at INFO or WARN +- The pickup schedule survives restarts. The client keeps the time of the last successful pickup of the latest archive (`lastPickupAt` in the state file) and the next pickup is due one interval after it. After a restart an overdue pickup runs on the first check once the client is paired with the active server and the server answers; one that is not overdue waits for its original due time. Changing the pickup interval recomputes the due time from the last pickup +- A pickup that fails or cannot reach the server is retried after 1, 2, 5, 10 and then every 15 minutes, instead of after a full interval. A client that is not paired waits quietly. A scheduled pickup and a manual download of the same archive no longer download it twice +- Switching the active server clears the last pickup time, so the first pickup from the new server is due at once instead of waiting for the old server's schedule. If the pickup time cannot be saved to the state file, the client backs off instead of retrying every minute, and a backward clock jump delays a retry by at most 15 minutes +- A download that finishes after the active server was switched no longer sets the new server's last pickup time. A scheduled pickup records its time before its task reports completed +- Incomplete `.part` files left behind by a crash or restart are deleted on startup and before each pickup, unless they belong to a transfer in progress +- On a phone-width screen the dashboard and Server Configuration no longer scroll sideways: grid columns, form rows and notes shrink to the screen, and the archives and services tables scroll inside their panel +- Server Configuration puts Backup Settings alone in the left column, with Add Service and then Failure Notifications stacked in the right column (in that order under Backup Settings on a narrow screen) + +## 11-19-26 +- The client pairs with the server. Selecting a server that has no stored token shows a pairing form in the Server Status panel: enter the `Pairing PIN` from the server's logs or a pairing code, and the client calls the server's `POST /api/v1/pair` and keeps the token per server address in its state file (readable by its owner only). The token is never logged, shown, or sent to the browser +- Every request to the server (API calls, the event stream, backup downloads, scheduled pickups, and the health check once paired) sends `Authorization: Bearer `. Requests to the server no longer follow redirects, so the token cannot be replayed elsewhere; a redirect is reported with the address it points to +- When the server rejects the token (`401`) the client answers `502` with `"pairing": "required"`, the dashboard says the token was rejected and offers to pair again, and the event stream stops retrying until the client is paired again. The dashboard state has a new `pairing` field and event (`NONE`, `PAIRED`, `REQUIRED`, `REJECTED`) +- New endpoints: `POST /api/client/pairing`, `POST /api/client/pairing/code` (a one-time code that pairs another client) and `DELETE /api/client/pairing` (revokes this client on the server and forgets the token, also when the server cannot be reached) +- The dashboard has a password. The first visitor sets it (at least 8 characters), or `CLIENT_PASSWORD` sets it and disables the form; `CLIENT_RESET_PASSWORD=true` removes a stored one on start. It is stored as a salted PBKDF2-HMAC-SHA256 hash (600,000 iterations) in `password.json` next to the state file. Sessions use an `HttpOnly`, `SameSite=Strict` cookie (`Secure` over HTTPS or with `X-Forwarded-Proto: https`) and end after 12 hours idle or 7 days; failed logins from one address are delayed from 5 seconds up to 5 minutes (`429`) +- Every `/api/client` endpoint, including `GET /events`, now needs the session; only the page, its assets and `/api/auth/status`, `login`, `set-password` and `logout` do not. Changing requests are refused when the browser marks them as cross-site. Scripts log in with `POST /api/auth/login` and keep the cookie +- An address typed with `https://` (in "Connect by IP" or `MEDIAGARRD_SERVER_IP`) keeps its scheme and defaults to port 443; no port scan is done for it. Plain `ip` and `ip:port` behave as before +- `MEDIAGARRD_SERVER_CA` trusts extra certificate authorities, or a self-signed certificate, for connections to the server, next to the system ones. The GitHub update check is unaffected. The client refuses to start if the file cannot be read +- Server addresses are normalized (lowercase scheme and host, default port and trailing slash dropped); stored addresses are migrated when the state is loaded. Tokens are tied to the exact address, so switching from `http://:38471` to `https://` needs pairing again +- The client needs a server from 11-19-26 or later; older servers have no pairing +- Changing requests without `Sec-Fetch-Site` or `Origin` headers must send `X-MediaGarrd-Request: 1`. A login attempt is checked one at a time per address and a few at a time overall, and all addresses together get 30 password checks a minute (a successful login gives its check back); when they are used up, logins get `429` with `Retry-After` until the next check is free +- Every response carries `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'`, so the dashboard cannot be embedded in another page +- An unexpected failure (HTTP 500) answers with `{"error": "Internal error"}`; the details are only in the log +- When the server accepts the token again after rejecting it, the event stream restarts at most once every 5 minutes, and only if the stream itself was rejected +- Added [docs/https.md](./docs/https.md) with nginx and Caddy examples +- Selecting a server by URL now checks that a MediaGarrd server answers at that address before it is stored (`400` with `No MediaGarrd server found at ` otherwise). Servers the client already knows are not checked again +- Request bodies on `/api` are limited to 64 KiB, also when sent chunked (`413` with `{"error": "Request body is too large"}`). A pairing PIN or code is limited to 64 characters and the client name to 64. Service names in the path must be letters, digits, `.`, `_` or `-` (at most 64). A line or event on the server's event stream is limited to 1 MiB +- Every response now also carries `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer` and a `Content-Security-Policy` of `default-src 'self'` (plus `frame-ancestors 'none'`); `/api` responses carry `Cache-Control: no-store` +- Every error answer is `{"error": "..."}`. Unexpected failures and failures reported by the server with a 5xx status carry no detail (`Internal error`, or `MediaGarrd server responded with `); the details are only in the log. The one exception is a failed `POST /api/client/backups/run`, which answers `500` with the run's failure reason from the server (the server does the same for that call), because the dashboard shows it. The messages of failed downloads in the progress of a pickup no longer include file paths +- Downloaded archives are saved with owner-only permissions (`0600`, new directories `0700`). A download that receives no data for 60 seconds fails +- Pairing while this client still holds a working token is refused with `409` (unpair first), and nothing is revoked on the server. `DELETE /pairing` answers `{"serverRevoked", "warning"}`; `warning` says why the server was not told, or is `null` +- A request that the server answers with `401` marks the pairing as rejected at once, without waiting for the next health check +- The live event stream of the browser ends when its session ends (logout, a new password, expiry) +- A `state.json` that cannot be read is moved to `state.json.corrupt-` and logged as an error instead of being overwritten. Changes to the state are written to disk before they take effect, so a failed save no longer leaves the client and its file out of step +- The scheduled pickup no longer runs on the shared scheduler thread. A pickup whose archive name leaves the download directory no longer leaves a stuck task behind, and the scheduled pickup never deletes an archive it did not download itself +- The release link of the update check must point to `https://github.com/`; otherwise it is built from the tag + +## 11-12-26 +- The client now owns the dashboard state (active and known servers, link state, run state, the server's backup interval and retention, both versions) and pushes it to every open page on `GET /api/client/events`: one `snapshot` on subscribe, then `link`, `state`, `run-started`, `run-finished`, `servers`, `config`, `backups-changed`, `versions` and `ping`. `GET /api/client/dashboard` returns the same snapshot +- Link states: `LIVE` (the server's event stream is open), `DEGRADED` (no stream, because of an older server, the subscriber cap or a backoff, but the server answers its health check), `CONNECTING` (a server was just selected or its stream dropped and the first health check has not answered) and `DOWN` (no server, or the health check failed). While not `LIVE`, the client checks the server's health every 8 seconds, once per client instead of once per open page +- Pages no longer poll the server. Status, Backup Archives and Versions are driven by pushes, and the one-minute refresh only re-reads the client's stored state +- The Backup Archives table reloads when a run finishes, when the server announces `backups-changed` (archive deleted or backup location changed), when the connected server changes, and when the link comes back; on tab return or view return only if a server is connected and its link is up. While `DEGRADED` the client lists the server's archives once a minute and pushes `backups-changed` itself +- The client refetches the server's health on its `config-changed` event, so schedule and retention changes made elsewhere show up at once +- Versions: the client pushes its own update check result when it changes. The server's version is fetched when the link comes up (not again within 5 minutes of a good answer, unless the server was down) or the server changes, then at most hourly; it is asked again after 30 seconds if the server has not checked yet, 5 minutes after a server error and 10 minutes when unavailable. The Versions panel needs no recheck timer, and the server row reads "Unable to check" once the first check fails +- The page shows "Client unreachable" instead of "No server connected" when the client itself cannot be reached. Renewing the live connection does not trigger it: the page waits 8 seconds for the reconnect first. The Server Status panel says when live updates are unavailable from the server +- The Known Servers list updates on every open Dashboard the moment the client's list changes, including background discovery, and leaves a selection you are making alone. The Pickup Interval field is filled on the first successful load and never changed by pushes or refreshes +- When the connected server changes, including in the background, the Dashboard reloads at once, including the Server Config form +- Moved the Versions panel below the Backup Archives panel +- The event stream sends a `retry: 5000` hint and answers 503 with an empty body when 32 browsers are already subscribed +- `GET /api/client/status` no longer probes for the preferred server; background discovery does that, retrying every 4 seconds while no server is selected +- Removed the unused `GET /api/client/server-health` and `GET /api/client/versions` +- "Run Backup Now" now gives up waiting after `CLIENT_BACKUP_RUN_TIMEOUT` (default `PT6H`) instead of holding a request open forever; the client answers 504 saying the backup is probably still running on the server, and the dashboard still shows when it finishes +- Added a small `node --test` suite for the page's decision logic; `make test` runs it + +## 11-11-26 +- The client knows its own version (`0.1.0`) and checks GitHub for the latest release of `MediaGarrd/Client` shortly after starting and then once a day. `MEDIAGARRD_UPDATE_REPOSITORY`, `MEDIAGARRD_GITHUB_API_URL` and `MEDIAGARRD_UPDATE_CHECK_INTERVAL` change the repository, API address and interval; the interval must be at least `PT1H` or the client refuses to start +- Added a Versions panel to the Dashboard with a Server row and a Client row: "Up-to-date" when current, a red box with a link to the latest release when an update is available, muted when the check could not be made or no server is connected. The server's version comes from its `GET /api/v1/version` +- The Dashboard refreshes every minute while open and visible (Backup Archives, Known Servers without disturbing a selection, Versions from the stored status without contacting GitHub); the Pickup Interval field is never touched +- The client keeps one connection to the server's `GET /api/v1/events` and relays it on the new `GET /api/client/events` (`state`, `run-started`, `run-finished`, `ping`, and `link` for the stream's status). The Server Status "State" and the backup buttons switch to Running and back to Idle at once, and Backup Archives reloads when a run finishes +- The client resubscribes when the connected server changes, reconnects after a failure with a delay growing from 1 to 30 seconds, and reconnects when the stream is quiet for 45 seconds. A server without `/api/v1/events` is retried every 5 minutes and polled meanwhile +- The browser closes the live connection while the tab is hidden and reopens it on return; at most 32 browsers can subscribe +- A health check started before a live event no longer overwrites it with older information, and a slow Backup Archives reload no longer overwrites a newer one +- Scheduled tasks run on two threads, so a slow GitHub check cannot delay discovery or pickups + +## 10-26-26 +- Finished renaming the codebase to MediaGarrd; removed unused code and dependencies +- Added issue templates, issue label and pull request workflows, integration test workflows, and a `Makefile` with a `test` target. The Gradle wrapper is now committed +- Removed `install.sh`: `docker-compose.example.yml` works as-is, downloads and state stay on the mounted volumes by default, and everything else is set from the web page +- `MEDIAGARRD_SERVER_PORT` defaults to `38471` to match the server; `MEDIAGARRD_SERVER_IP` is optional and accepts `:`. The client connects to it at startup and retries every 30 seconds until a server is selected, so scheduled pickups work without opening the page +- Added a Server Config view, opened from the toggle in the top bar, to change the connected server's backup location, interval and retention count and to add, edit and remove its services +- Split the web page into an HTML page, a stylesheet and JavaScript modules +- Every API endpoint returns errors as `{"error": "..."}`, passing on the server's own message and status code when it rejects a request. Unknown backups and download tasks return 404, invalid pickup intervals and server URLs return 400, and finished download tasks are forgotten after 10 minutes +- Fixed the server schedule being sent as seconds instead of an ISO-8601 duration +- Network discovery finishes in a couple of seconds: it checks for an open port before any HTTP request, probes many hosts at once, skips Docker and VPN interfaces, and counts only servers that answer with a MediaGarrd health response. "Scan Local Network" reports how many it found +- Connecting by IP accepts `host:port`, stops at once when the host is unreachable, and scans every port of a reachable host in about a second +- The badge and status panel show when the selected server is not responding, the backup list says why it could not load, and everything reloads when the server returns. The connection badge is no longer overwritten by the health check during a scan or connection attempt +- The backup list reloads when a run started elsewhere finishes, and the Dashboard shows saved server settings as soon as you switch back to it +- Requests to the server time out instead of hanging, and health checks pause while the page is hidden +- Starting a download of a backup that is already downloading reuses the running download +- Backup file names from the server can no longer write outside the download directory, and the client state file is written atomically diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/Dockerfile b/Dockerfile index b6aca51..9b86100 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,10 +1,20 @@ FROM gradle:9.4.0-jdk21 AS build WORKDIR /workspace COPY . . -RUN gradle :bootJar --no-daemon +RUN --mount=type=cache,target=/home/gradle/.gradle gradle :bootJar --no-daemon --stacktrace --info --warning-mode all -FROM eclipse-temurin:21-jre +FROM eclipse-temurin:21.0.13_9-jre WORKDIR /app +RUN set -eux; \ + if getent passwd 1000 >/dev/null; then userdel "$(getent passwd 1000 | cut -d: -f1)"; fi; \ + if getent group 1000 >/dev/null; then groupdel "$(getent group 1000 | cut -d: -f1)"; fi; \ + groupadd --gid 1000 mediagarrd; \ + useradd --uid 1000 --gid 1000 --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin mediagarrd; \ + mkdir -p /var/lib/mediagarrd/client /var/lib/mediagarrd/downloads; \ + chown -R 1000:1000 /var/lib/mediagarrd COPY --from=build /workspace/build/libs/*.jar app.jar +COPY --chmod=755 docker-entrypoint.sh /usr/local/bin/mediagarrd-entrypoint EXPOSE 8081 -ENTRYPOINT ["java", "-jar", "/app/app.jar"] +HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 CMD ["sh", "-c", "curl -fsS -o /dev/null \"http://127.0.0.1:${CLIENT_PORT:-8081}/api/auth/status\""] +ENTRYPOINT ["/usr/local/bin/mediagarrd-entrypoint"] +CMD ["java", "-jar", "/app/app.jar"] diff --git a/LICENSE b/LICENSE index f288702..ba28e3b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,21 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. +MIT License + +Copyright (c) 2026 Jackson Swindell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..891e440 --- /dev/null +++ b/Makefile @@ -0,0 +1,6 @@ +.PHONY: test + +test: + ./gradlew test --warning-mode all + node --test src/test/js/*.test.mjs + diff --git a/README.md b/README.md index 0101992..1f6d51b 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,39 @@ # Client -This is the official client for [MediaGarrd](https://github.com/MediaGarrd/MediaGarrd). +The official client for [MediaGarrd](https://github.com/MediaGarrd/MediaGarrd). It is a web dashboard that connects to a [MediaGarrd Server](https://github.com/MediaGarrd/Server), shows its status live, runs and downloads backups, and changes the server's configuration. + +Full documentation is on the [MediaGarrd website](https://mediagarrd.github.io/MediaGarrd/). + +## Docs +- [settings.md](./docs/settings.md): every environment variable and its default. +- [https.md](./docs/https.md): HTTPS with nginx or Caddy, and self-signed certificates. +- [network.md](./docs/network.md): how the client finds servers on the network. +- [API.md](./docs/API.md): every HTTP endpoint and what it returns. +- [testing.md](./docs/testing.md): running the Java and browser tests. + +## Requirements +- Docker with Compose v2 +- A MediaGarrd Server from 11-19-26 or later that has finished its first-time setup. Older servers have no pairing, so this client cannot use them + +The dashboard has a password and the client pairs with each server. Whoever opens a new dashboard first can choose its password, so do it right after installing, or set `CLIENT_PASSWORD`. Beyond a trusted network, put both behind HTTPS: see [https.md](./docs/https.md). ## Installation ```bash git clone --depth 1 https://github.com/MediaGarrd/Client.git cd Client -./install.sh # Drops .env, client.env, and docker-compose.yml +cp docker-compose.example.yml docker-compose.yml +docker compose up --build -d +``` + +Then open `http://:8081` and choose a dashboard password (or set `CLIENT_PASSWORD`). Connect to your server by IP or with "Scan Local Network", then pair: enter the `Pairing PIN` that the server's setup page shows after Finish Setup, which it also prints in its logs (`docker logs mediagarrd-server 2>&1 | grep "Pairing PIN"`). To connect automatically, add `MEDIAGARRD_SERVER_IP=` to `environment` in `docker-compose.yml`. + +The container runs the client as UID 1000, not as root. On first start it gives that user ownership of the mounted state and downloads folders (`./data/client/state` and `./data/client/downloads` in the example) and of the client's own files in them, so existing installs keep working. To use another owner, add `PUID` and `PGID` to `environment` in `docker-compose.yml` (see [settings](./docs/settings.md)). + +## Updating +```bash +git pull docker compose up --build -d ``` ## License -[GPLv3](./LICENSE) +[MIT](./LICENSE) diff --git a/build.gradle.kts b/build.gradle.kts index 60673ae..58d8f94 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,18 +1,20 @@ plugins { java - id("org.springframework.boot") version "3.3.5" - id("io.spring.dependency-management") version "1.1.6" + id("org.springframework.boot") version "4.1.3" + id("io.spring.dependency-management") version "1.1.7" } +version = "0.1.0" + repositories { - // Use Maven Central for resolving dependencies. mavenCentral() } dependencies { testImplementation("org.springframework.boot:spring-boot-starter-test") testRuntimeOnly("org.junit.platform:junit-platform-launcher") - implementation("org.springframework.boot:spring-boot-starter-web") + testImplementation("org.springframework.boot:spring-boot-starter-webmvc-test") + implementation("org.springframework.boot:spring-boot-starter-webmvc") implementation("org.springframework.boot:spring-boot-starter") } @@ -22,6 +24,10 @@ java { } } +springBoot { + buildInfo() +} + tasks.test { useJUnitPlatform() } diff --git a/docker-compose.example.yml b/docker-compose.example.yml index 9ad9bfb..4c12fe2 100644 --- a/docker-compose.example.yml +++ b/docker-compose.example.yml @@ -2,18 +2,15 @@ services: mediagarrd-client: build: context: . - dockerfile: ./Dockerfile + dockerfile: Dockerfile container_name: mediagarrd-client environment: - CLIENT_PORT=8081 - - CLIENT_PICKUP_INTERVAL=PT1H - - CLIENT_DOWNLOAD_DIRECTORY=/var/lib/mediagarrd/downloads - - CLIENT_STATE_FILE=/var/lib/mediagarrd/client/state.json + - CLIENT_PICKUP_INTERVAL=PT12H - MEDIAGARRD_SERVER_PORT=38471 - - MEDIAGARRD_SERVER_IP=192.168.50.55 ports: - "8081:8081" volumes: - "./data/client/downloads:/var/lib/mediagarrd/downloads" - - "./data/client:/var/lib/mediagarrd/client" + - "./data/client/state:/var/lib/mediagarrd/client" restart: unless-stopped diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh new file mode 100755 index 0000000..649574c --- /dev/null +++ b/docker-entrypoint.sh @@ -0,0 +1,67 @@ +#!/bin/sh +set -eu + +PUID="${PUID:-1000}" +PGID="${PGID:-1000}" + +for value in "$PUID" "$PGID"; do + case "$value" in + ''|*[!0-9]*) + echo "PUID and PGID must be numbers, got PUID='$PUID' PGID='$PGID'" >&2 + exit 1 + ;; + esac + if [ "${#value}" -gt 10 ] || [ "$value" -gt 4294967294 ]; then + echo "PUID and PGID must be at most 4294967294, got PUID='$PUID' PGID='$PGID'" >&2 + exit 1 + fi +done + +export HOME=/tmp + +warn() { + echo "Warning: $*" >&2 +} + +prepare() { + state_file="${CLIENT_STATE_FILE:-/var/lib/mediagarrd/client/state.json}" + state_dir="$(dirname "$state_file")" + state_base="$(basename "$state_file")" + download_dir="${CLIENT_DOWNLOAD_DIRECTORY:-/var/lib/mediagarrd/downloads}" + + mkdir -p "$state_dir" "$download_dir" || warn "could not create $state_dir or $download_dir" + + for dir in "$state_dir" "$download_dir"; do + if [ "$dir" = "/" ]; then + warn "refusing to change the owner of /" + else + echo "Giving $PUID:$PGID ownership of $dir and the client's own files in it" >&2 + chown -h "$PUID:$PGID" "$dir" || warn "could not change the owner of $dir" + fi + done + + if [ -d "$state_dir" ] && [ "$state_dir" != "/" ]; then + find "$state_dir" -maxdepth 1 -type f -links 1 \ + \( -name "$state_base" -o -name "$state_base.tmp" -o -name "$state_base.corrupt-*" \ + -o -name password.json -o -name password.json.tmp \) \ + -exec chown -h "$PUID:$PGID" {} + || warn "could not change the owner of the client's files in $state_dir" + fi + + if [ -d "$download_dir" ] && [ "$download_dir" != "/" ]; then + find "$download_dir" -maxdepth 1 -type f -links 1 \ + \( -name '*-media-backup.zip' -o -name '*-media-backup-AD.zip' -o -name '*-media-backup*.zip.part' \) \ + -exec chown -h "$PUID:$PGID" {} + || warn "could not change the owner of the client's archives in $download_dir" + fi +} + +uid="$(id -u)" +if [ "$uid" -eq 0 ] && [ "$PUID" -ne 0 ]; then + prepare + if ! command -v setpriv >/dev/null 2>&1; then + echo "setpriv is not available in this image, cannot drop privileges" >&2 + exit 1 + fi + exec setpriv --reuid="$PUID" --regid="$PGID" --clear-groups --no-new-privs -- "$@" +fi + +exec "$@" diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..d44ddb4 --- /dev/null +++ b/docs/API.md @@ -0,0 +1,67 @@ +# Client API + +Endpoints are under `/api/client` and `/api/auth`. Endpoints that act on the connected server need a server to be selected. Errors are returned as `{"error": "..."}` with a matching status code. A `5xx` caused by the client itself, or reported by the server, carries no detail (`{"error": "Internal error"}` or `{"error": "MediaGarrd server responded with "}`), with one exception: a failed `POST /api/client/backups/run` answers `500` with the run's failure reason in `error`, because the dashboard shows it. The documented `502`, `503` and `504` answers below keep their messages. A request body over 64 KiB, declared or chunked, is refused with `413`. + +## Login +Everything under `/api/client`, including `GET /events`, needs the dashboard session cookie (`mg_session`, `HttpOnly`, `SameSite=Strict`, `Secure` over HTTPS or when the proxy sends `X-Forwarded-Proto: https`). Without it the client answers `401` with `{"error": "Login required", "login": "required"}`. Requests that change something (anything but GET) are refused with `403` when a browser marks them as cross-site: `Sec-Fetch-Site` must be `same-origin`, or `Origin` must match the `Host` (or `X-Forwarded-Host`) header. A request with neither header must carry `X-MediaGarrd-Request: 1`; the dashboard sends it on every call, and scripts must add it to every non-GET request. + +| Endpoint | Returns | +|---|---| +| `GET /api/auth/status` | `{"passwordSet", "passwordFromEnvironment", "authenticated"}`. No session needed. | +| `POST /api/auth/login` | `{"authenticated": true}` and the session cookie for body `{"password": "..."}`. `401` for a wrong password, `409` when no password is set, `429` with `Retry-After` while the source address is locked out after repeated failures, while another attempt from it is still being checked, when several passwords are already being checked, or when all addresses together have used up their 30 password checks a minute. | +| `POST /api/auth/set-password` | Sets the first password (body `{"password": "..."}`, 8 to 256 characters) and signs in. `409` when a password already exists or `CLIENT_PASSWORD` is set. | +| `POST /api/auth/logout` | An empty `204` and an expired cookie. | + +A headless script logs in with `curl -c jar -H 'X-MediaGarrd-Request: 1' -H 'Content-Type: application/json' -d '{"password":"..."}' http://:8081/api/auth/login` and sends `-b jar -H 'X-MediaGarrd-Request: 1'` on every later non-GET request. + +## Pairing +The client keeps one token per server address. Tokens never appear in any response. When the server has no token for the selected address, or the server rejects it (`401`), a request that needs the server is answered with `502` and `{"error": "...", "pairing": "required"}`. `GET /dashboard` and the `snapshot` event carry `pairing`: `NONE` (no server), `PAIRED`, `REQUIRED` (no token stored) or `REJECTED` (the server refused the stored token); the `pairing` event carries `{"state": ...}`. + +| Endpoint | Returns | +|---|---| +| `POST /pairing` | `{"paired": true, "name": "...", "note": null}` after pairing with the selected server. Answers `409` while this client holds a stored token that the server still accepts (the client probes it with `GET /api/v1/health`); unpair first. A pair or unpair request waits while another one is running. A stored token the server refuses (`401`) is replaced. Body `{"pin": "", "name": ""}`. The client pairs, stores the token, then confirms it with one authenticated `GET /api/v1/health` on the server (retried up to 3 times after a network error or a 502, 503 or 504). A `401` on the confirmation, or a reply that is not a confirmation, discards the token and is answered with a `400` (or `502`), so the same PIN or code can be tried again. Any other failure keeps the token and answers `{"paired": true, "name": "...", "note": "..."}`, where `note` says the server will confirm it on the next connection; `note` is `null` after a confirmed pairing. A wrong PIN or code is a `400`; the server's `403` (pairing closed), `409` (setup not finished) and `429` (locked) are passed on with its message. | +| `POST /pairing/code` | `{"code": "XXXXX-XXXXX", "expiresAt": "..."}`: a one-time code, valid for 10 minutes, that pairs another client. Shown only in this response. | +| `DELETE /pairing` | `{"serverRevoked": true/false, "warning": null or "..."}`. Revokes this client's token on the server and forgets it locally. It waits while a pair request is running. `{"serverRevoked": false, "warning": "..."}` when the server could not be told (unreachable, token rejected, or no client id stored): the token is forgotten locally anyway and `warning` says the server may still list this client. `warning` is `null` when `serverRevoked` is `true`. | + + +## Dashboard +| Endpoint | Returns | +|---|---| +| `GET /status` | The selected server, the known servers, and the pickup interval. | +| `GET /dashboard` | The dashboard state: selected and known servers, connection state, run state, the server's schedule and retention, and both versions. | +| `GET /events` | A Server-Sent Events stream that starts with the dashboard state and then pushes each change to it, including `pairing`. | + +## Servers +| Endpoint | Returns | +|---|---| +| `POST /discover` | The servers found by scanning the local network. | +| `PUT /server` | The client status after selecting a server by URL, or by IP and optional port. A URL that is not already known is checked first: if no MediaGarrd server answers there the client answers `400`. An address that starts with `https://` keeps its scheme and, without a port, uses 443; no port scan is done for it. | + +## Backups +| Endpoint | Returns | +|---|---| +| `GET /backups` | The connected server's archives. | +| `POST /backups/run` | An empty `200` once the connected server finishes a backup, or `504` if it takes longer than the run timeout. | +| `POST /pickup` | A task id and the archive's details after starting a download of the newest archive. `400` if the server gives the archive a file name that does not end in `.zip` or ends in `.part`. | +| `POST /pickup/{id}` | A task id and the archive's details after starting a download of one archive. `400` for the same file name check. | +| `GET /pickup/progress/{taskId}` | A download's status, bytes written, total size, and saved path. | +| `PUT /pickup-interval` | The client status after changing how often the newest archive is downloaded automatically. | + +## Server configuration +| Endpoint | Returns | +|---|---| +| `GET /server-config` | The connected server's backup location, number of backups to keep, and time between backups. | +| `PUT /server-config` | The connected server's updated configuration. A `backupInterval` shorter than 15 minutes or longer than 365 days is refused with `400` (`Backup interval must be between 15 minutes and 365 days`) before anything is sent to the server, so the location and retention are not changed either. | +| `GET /services` | The connected server's services with their host paths. | +| `POST /services` | The service added to the connected server, with `201`. | +| `PUT /services/{name}` | The updated service on the connected server. | +| `DELETE /services/{name}` | An empty `204` once the service is removed from the connected server. | + +## Failure webhook +Proxies the connected server's failure webhook (see the server's API.md), which the server calls when a backup fails or only partly succeeds. The full URL is a secret, so it is never returned: only whether one is set and its `scheme://host[:port]`. A write needs the same `X-MediaGarrd-Request: 1` header as the other writes. + +| Endpoint | Returns | +|---|---| +| `GET /notifications/webhook` | `{"configured": true, "target": "https://discord.com"}` or `{"configured": false, "target": null}`. | +| `PUT /notifications/webhook` | The same shape after saving. Body `{"url": "https://..."}`; an empty string clears the webhook. An invalid URL is a `400` with the server's message. | +| `POST /notifications/webhook/test` | `{"delivered": false, "status": 404, "error": "Webhook answered 404"}` after the server sends a test message (`status` is the receiver's 2xx code when delivered and `null` only when no reply came, and `error` is `null` when delivered). A test less than 10 seconds after the last one is a `429` with the server's message and its `Retry-After` header. `400` when no webhook is set. | diff --git a/docs/https.md b/docs/https.md new file mode 100644 index 0000000..d07176b --- /dev/null +++ b/docs/https.md @@ -0,0 +1,94 @@ +# HTTPS + +The Client dashboard and the Server both speak plain HTTP. To use HTTPS, put a reverse proxy in front of each. This matters because the dashboard password, the session cookie, the pairing PIN and the pairing tokens travel in plain text over HTTP. On a network you do not control, use HTTPS. The Server has its own page: [Server docs/https.md](https://github.com/MediaGarrd/Server/blob/main/docs/https.md). Read it too: it covers the Server side of this setup. + +## 1. Keep the plain ports private +`docker-compose.example.yml` publishes the Client with `"8081:8081"`. Remove that mapping so the plain port is not reachable from outside, and put the Client and the proxy on a shared Docker network. The proxy reaches it by container name. The Server does the same with its `"38471:38471"` mapping. + +```yaml +services: + mediagarrd-client: + build: + context: . + dockerfile: Dockerfile + container_name: mediagarrd-client + environment: + - CLIENT_PORT=8081 + - CLIENT_PICKUP_INTERVAL=PT12H + - MEDIAGARRD_SERVER_PORT=38471 + - MEDIAGARRD_SERVER_IP=https://mediagarrd.example.com + volumes: + - "./data/client/downloads:/var/lib/mediagarrd/downloads" + - "./data/client/state:/var/lib/mediagarrd/client" + networks: + - proxy + restart: unless-stopped + +networks: + proxy: + name: proxy +``` + +Run the proxy on the same network (`proxy`) and send traffic to `mediagarrd-client:8081`. + +## 2. Serve the dashboard at the root of a domain +The dashboard uses absolute paths (`/js/main.js`, `/api/client/...`). It must be served at the root of a domain or subdomain, for example `https://client.example.com`. It does not work under a subpath such as `https://example.com/mediagarrd/`. + +The proxy must pass the `Host` header on unchanged (or send `X-Forwarded-Host`) and, for the cookie, tell the Client the scheme with `X-Forwarded-Proto: https`. The Client uses the first to accept changing requests from the dashboard and the second to mark the session cookie `Secure`. Caddy does both by default; nginx needs the two `proxy_set_header` lines below. + +### Caddy +``` +client.example.com { + reverse_proxy mediagarrd-client:8081 { + flush_interval -1 + } +} +``` +`flush_interval -1` sends the live event stream (`/api/client/events`) through immediately. + +### nginx +```nginx +server { + listen 443 ssl http2; + server_name client.example.com; + + ssl_certificate /etc/ssl/mediagarrd/fullchain.pem; + ssl_certificate_key /etc/ssl/mediagarrd/privkey.pem; + + location / { + proxy_pass http://mediagarrd-client:8081; + 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. The long timeouts matter for "Run Backup Now", which holds a request open until the backup finishes (up to `CLIENT_BACKUP_RUN_TIMEOUT`, default 6 hours), so raise them if your backups take longer. + +Behind a proxy the Client sees every visitor as coming from the proxy, so the failed-login delay is shared by all of them. + +## 3. Serve the Server +Follow the Server's page for its proxy (`https://mediagarrd.example.com` in the examples). Large backup downloads and backup runs need long timeouts there too: nginx `proxy_read_timeout` and `proxy_send_timeout`, and `proxy_buffering off`. Caddy sets no time limit. + +## 4. Connect the Client to the HTTPS Server +Type the address with its scheme in "Connect by IP", or set `MEDIAGARRD_SERVER_IP=https://mediagarrd.example.com`. The scheme is kept, and without a port the Client uses 443 and checks only that address; it does not scan ports. "Scan Local Network" only looks for plain HTTP servers. + +A token is tied to the exact address it was paired on. Switching from `http://:38471` to `https://mediagarrd.example.com` 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, or the self-signed certificate itself, as a PEM file: + +```yaml + environment: + - MEDIAGARRD_SERVER_CA=/etc/mediagarrd/ca.pem + volumes: + - "./ca.pem:/etc/mediagarrd/ca.pem:ro" +``` +- The file may hold several certificates. They are trusted in addition to the system ones, only for connections to the Server; the GitHub update check is not affected. +- The file must be readable by the user the Client runs as: UID 1000, or your `PUID`. Mode `0644` works; a `0600` file owned by root does not. The Client does not start if the file cannot be read or holds no certificate, and says why. +- The host name is still checked. If you reach the Server by IP address, the certificate needs that IP in its Subject Alternative Names (for example `-addext "subjectAltName=IP:192.168.1.10"` with `openssl req`). diff --git a/docs/network.md b/docs/network.md new file mode 100644 index 0000000..7ef4053 --- /dev/null +++ b/docs/network.md @@ -0,0 +1,28 @@ +# Finding servers on the network + +The client can find MediaGarrd servers in three ways. + +## Scan Local Network +"Scan Local Network" on the Dashboard checks every address of the networks the client is attached to. +- It tries `MEDIAGARRD_SERVER_PORT` first, then `38471`, `8080`, and `80`. +- An address counts as a MediaGarrd server only if it answers `GET /api/v1/health` like one. +- Networks larger than a `/24` are scanned as the `/24` around the client's own address. +- Loopback, Docker, VPN, and other virtual interfaces are skipped. +- A scan gives up after 20 seconds. +- Every server it finds is added to Known Servers. Servers that are already known stay in the list, even when the scan does not find them again. + +## Connect by IP +"Connect by IP" accepts ``, `:`, or an `https://` address such as `https://garrd.example.com`. For an `https://` address the client uses the default port (443) unless you give one, checks only that address, and does not scan ports. The scan of the local network always uses plain HTTP. For a plain address it tries the given port and the common ports above first. If none of them answer, it scans every port from 1024 to 65535 on that host. + +## Connecting automatically +Set `MEDIAGARRD_SERVER_IP=` (or `:`, or `https://`) in the client's `environment`. While no server is selected, the client tries that address every few seconds and connects as soon as it answers. + +## Docker networking +With the default Docker networking the client only sees its container network. A scan then finds servers running on the same host, but not on other machines. To reach those: +- Use "Connect by IP" or `MEDIAGARRD_SERVER_IP`. +- Or add `network_mode: host` to the client's service in `docker-compose.yml`, and remove its `ports` mapping, so the scan covers your LAN. Keep `CLIENT_PORT` at 1024 or above in that case: the client does not run as root and cannot bind a lower port. If you also use `cap_drop: ALL`, keep `CHOWN`, `SETUID` and `SETGID`, or set `user:` instead (see [settings.md](./settings.md)). + +## Pairing +Finding a server does not give access to it. Without a token the server's health check only says whether it is healthy and its backup interval; everything else needs the token you get by pairing. See [settings.md](./settings.md). + +For HTTPS, see [https.md](./https.md). diff --git a/docs/settings.md b/docs/settings.md new file mode 100644 index 0000000..19da442 --- /dev/null +++ b/docs/settings.md @@ -0,0 +1,41 @@ +# Settings + +Set these in `environment` in `docker-compose.yml`. Durations use ISO-8601, for example `PT12H`. + +| Variable | Default | What it does | +|---|---|---| +| `CLIENT_PORT` | `8081` | The port of the web dashboard. Change the `ports` mapping to match. | +| `CLIENT_PICKUP_INTERVAL` | `PT12H` | How often the newest archive is downloaded automatically. Between 1 second and 365 days; a value outside that range is ignored with a warning and the default is used. Only the initial value: once it is saved in the dashboard, the stored value is used. The time of the last successful pickup is kept in the state file, so a restart does not reset the schedule: a pickup that is overdue runs on the first check (every minute) once the client has an active server, a stored pairing, and the server answers; otherwise it runs at the original due time. A pickup that cannot run is retried after 1, 2, 5, 10 and then every 15 minutes. After a successful automatic pickup, the earlier `*-media-backup-AD.zip` copies of the older archives the active server still lists are deleted from the download directory; newer copies, copies of archives the server no longer lists (such as those from another server) and all other files are kept. Downloading the latest archive by hand also counts as a pickup. Switching to a different active server clears the last pickup time, so the first pickup from the new server is due at once; a download that was started from the old server and finishes after the switch does not set the new server's pickup time. Incomplete `.part` files left in the download directory by a crash are deleted on startup and before each pickup, except those of a transfer in progress. If the time of a pickup cannot be saved, the client retries on the same backoff. | +| `CLIENT_BACKUP_RUN_TIMEOUT` | `PT6H` | How long "Run Backup Now" waits for the server to finish. Minimum `PT1M`. If a run takes longer, the dashboard shows an error, but the backup keeps running on the server. | +| `MEDIAGARRD_SERVER_IP` | (none) | A server to connect to automatically, as ``, `:` or `https://[:]`. See [network.md](./network.md). | +| `MEDIAGARRD_SERVER_CA` | (none) | A PEM file with extra certificate authorities (or a self-signed certificate) to trust for connections to the server, in addition to the system ones. The client refuses to start if the file cannot be read. See [https.md](./https.md). | +| `CLIENT_PASSWORD` | (none) | The dashboard password. When set it overrides any stored password and the set-password form is disabled. | +| `CLIENT_RESET_PASSWORD` | `false` | `true` removes the stored dashboard password on start, so the first visitor can set a new one. Remove it again afterwards: while it stays set, every restart reopens that window. | +| `MEDIAGARRD_SERVER_PORT` | `38471` | The server port tried first by "Scan Local Network" and "Connect by IP". | +| `MEDIAGARRD_UPDATE_REPOSITORY` | `MediaGarrd/Client` | 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`. | +| `CLIENT_STATE_FILE` | `/var/lib/mediagarrd/client/state.json` | Where the client keeps its selected server, known servers, pickup interval, the time of the last pickup and the tokens of its paired servers, inside the container. The file is readable by its owner only. The dashboard password hash is stored next to it as `password.json`. | +| `CLIENT_DOWNLOAD_DIRECTORY` | `/var/lib/mediagarrd/downloads` | Where downloaded archives are saved, inside the container. Archives are written with owner-only permissions (`0600`) and directories the client creates are `0700`; an existing directory is left as it is. | + +The container starts as root only to hand the two data folders and the client's own files in them to UID 1000, then runs the client as that user. Set `PUID` and `PGID` in `environment` to use another owner, for example your own user on the host (`id -u`, `id -g`). Only the folders themselves and the client's own files are changed: the state file and its copies, `password.json`, and `*-media-backup.zip`, `*-media-backup-AD.zip` and their `.part` files. Other files in those folders, and the subfolders, are not touched. With `PUID=0` the client keeps running as root. If you set `user:` in Compose, nothing is changed and the folders must already belong to that user. + +Because Java no longer runs as root, two settings need care. With `network_mode: host` keep `CLIENT_PORT` at 1024 or above, since a non-root process cannot bind a lower port. With `cap_drop: ALL` add back `CHOWN`, `SETUID` and `SETGID` (the entrypoint needs them to hand over the folders and drop to UID 1000), or run with `user:` instead. If the state file exists but this user cannot read it, the client refuses to start and names the file and the UID, instead of moving it aside; fix its owner or permissions. + +To change where data is kept on the host, change the left side of the volumes in `docker-compose.yml`: +- `./data/client/downloads`: downloaded archives. +- `./data/client/state`: the client's state. Keep it on persistent storage. + +## Failure webhook +The dashboard's Server Configuration view has a Failure Notifications panel for the connected server's optional failure webhook: a URL the server posts to when a backup fails or only partly succeeds (see the server's settings page for the message formats). Enter a URL and press Save Webhook, press Clear to turn it off, or Send Test to have the server post a test message now (if a URL is typed in the field it is saved first). The panel shows `Configured: https://host` and never the saved URL, because Discord and Slack webhook URLs are secrets; to change it, type the new one. Send Test is limited to one every 10 seconds. The URL is stored on the server, not in the client's state file. + +## Dashboard login +Opening the dashboard asks for a password. If none is set yet, whoever opens it first chooses one (at least 8 characters). Set `CLIENT_PASSWORD` to choose it yourself instead. The password is stored as a salted PBKDF2-HMAC-SHA256 hash in `password.json` next to the state file; keep that directory on persistent storage and private. +- Sessions end after 12 hours without activity or 7 days in total, and when the client restarts. +- Only one login attempt per address is checked at a time and only a few are checked at once overall; extra attempts get 429. +- Password checks from all addresses together share a budget of 30 a minute. A successful login gives its check back. When the budget is used up, logins get 429 with a `Retry-After` of a few seconds and no password is checked, and nobody is locked out for a fixed time. Someone who sends requests from many addresses can still use up the budget and make the owner wait for the next free check; set `CLIENT_PASSWORD` to a long random value and keep the dashboard behind a VPN or reverse proxy that limits access. +- After the 4th failed login from one address, further attempts from it are refused with a delay that grows from 5 seconds to 5 minutes. Behind a reverse proxy every visitor shares the proxy's address, so the delay applies to all of them. +- Forgot the password? Start once with `CLIENT_RESET_PASSWORD=true`, open the dashboard, set a new one, then remove the variable. + +## Pairing +A client must be paired with each server it uses. Choose the server in the dashboard and enter the `Pairing PIN` that the server's setup page shows after Finish Setup (it is also in the server's logs), or a pairing code from a client that is already paired. The client stores the token as soon as the server issues it and then confirms the pairing with one request. It discards the token only when the server refuses the confirmation, so after that error you can enter the same PIN or code again. If the confirmation cannot be completed (the server is unreachable or answers with an error), the client keeps the token and says so: the server confirms it on the client's next connection, which happens within seconds. If the server never received a request with it, the unconfirmed pairing expires after 5 minutes, the client then asks you to pair again, and the same PIN (or a new pairing code) works. A client that is already paired with a working token refuses to pair again (`409`); unpair it first. The token is kept in the state file per server address and is never shown. Tokens are tied to the exact address: `http://:38471` and `https://garrd.example.com` need separate pairings. diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..adefa5e --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,20 @@ +# Testing + +`make test` runs both the Java tests and the browser tests. + +## Browser tests +The browser tests in `src/test/js` cover the pure modules in `src/main/resources/static/js` (dashboard state, view and message logic, formatting, API error handling, the event stream, busy handling, notifications, the webhook form, and login and pairing logic). Some also read the HTML, CSS or Java sources to check what they contain, such as the webhook panel's markup and styles and that the event names match the server's. The files in `src/test/js` are the list of what is covered. + +They need Node 20.19 or newer and have no dependencies. Run them on their own from the repository root: +```bash +node --test src/test/js/*.test.mjs +``` + +## Manual UI check +The page wiring (`auth.js`, `pairing.js`, `main.js`, the HTML and CSS) is not covered by automated tests; only the pure modules are. After changing the page, open the dashboard in a browser and check: setting the first password, logging in and out, pairing with a PIN, creating a pairing code, unpairing, and that a revoked token shows the pairing form again. + +## Java tests +```bash +./gradlew test +``` +The HTTPS tests generate a self-signed certificate with the JDK's `keytool`, so the JDK's `bin` directory must be present. diff --git a/gradle.properties b/gradle.properties index 377538c..1385fa5 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,2 @@ -# This file was generated by the Gradle 'init' task. -# https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties - org.gradle.configuration-cache=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d997cfc Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..dbc3ce4 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew.bat b/gradlew.bat index c4bdd3a..e509b2d 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,93 +1,93 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem -@rem SPDX-License-Identifier: Apache-2.0 -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:execute -@rem Setup the command line - - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/install-util.sh b/install-util.sh deleted file mode 100644 index 6868df0..0000000 --- a/install-util.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env bash - -ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -SECRETS_DIR="$ROOT_DIR/secrets" -COMPOSE_FILE="$ROOT_DIR/docker-compose.yml" -ENV_FILE="$ROOT_DIR/.env" -SERVER_ENV_FILE="$SECRETS_DIR/server.env" -CLIENT_ENV_FILE="$SECRETS_DIR/client.env" - -mkdir -p "$SECRETS_DIR" - -prompt() { - local var_name="$1" - local prompt_text="$2" - local default_value="${3:-}" - local value="" - - read -r -p "$prompt_text" value - if [[ -z "$value" ]]; then - value="$default_value" - fi - - printf -v "$var_name" '%s' "$value" -} - -yes_no() { - local var_name="$1" - local prompt_text="$2" - local default_value="${3:-y}" - local response - - read -r -p "$prompt_text" response - response="${response:-$default_value}" - if [[ "$response" =~ ^[Yy]([Ee][Ss])?$ ]]; then - printf -v "$var_name" 'true' - else - printf -v "$var_name" 'false' - fi -} - diff --git a/install.sh b/install.sh deleted file mode 100644 index 1ac6736..0000000 --- a/install.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail -source ./install-util.sh - -prompt client_port "MediaGarrd-Client host port [8081]: " "8081" -prompt pickup_interval "Client automatic pickup interval in ISO-8601 format [PT12H]: " "PT12H" -prompt server_ip "MediaGarrd-Server IP [192.168.1.10]: " "192.168.1.10" -prompt client_downloads_host "Client download host path [./data/client/downloads]: " "./data/client/downloads" -prompt client_state_host "Client state host path [./data/client]: " "./data/client" - -cat > "$ENV_FILE" < "$CLIENT_ENV_FILE" < "$COMPOSE_FILE" <> serverRejected(RestClientResponseException e) { + int status = e.getStatusCode().value(); + String message = null; + if (!e.getStatusCode().is5xxServerError()) { + try { + ServerError body = e.getResponseBodyAs(ServerError.class); + message = body == null ? null : body.error(); + } catch (RuntimeException ignored) { + } + } + String reason = message == null ? "MediaGarrd server responded with " + status : message; + LOGGER.warn("MediaGarrd server rejected request: {}", reason); + if (status == HttpStatus.TOO_MANY_REQUESTS.value()) { + String retryAfter = e.getResponseHeaders() == null ? null : e.getResponseHeaders().getFirst(HttpHeaders.RETRY_AFTER); + if (retryAfter != null && retryAfter.matches("\\d{1,6}")) { + return ResponseEntity.status(e.getStatusCode()).header(HttpHeaders.RETRY_AFTER, retryAfter).body(Map.of("error", reason)); + } + } + return error(e.getStatusCode(), reason); + } + + @ExceptionHandler(PairingRequiredException.class) + public ResponseEntity> pairingRequired(PairingRequiredException e) { + LOGGER.warn("Pairing required: {}", e.getMessage()); + return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body(Map.of("error", e.getMessage(), "pairing", "required")); + } + + @ExceptionHandler(ServerRedirectException.class) + public ResponseEntity> serverRedirected(ServerRedirectException e) { + LOGGER.warn("MediaGarrd server redirected the request: {}", e.getMessage()); + return error(HttpStatus.BAD_GATEWAY, e.getMessage()); + } + + @ExceptionHandler(UpstreamResponseException.class) + public ResponseEntity> upstreamInvalid(UpstreamResponseException e) { + LOGGER.warn("MediaGarrd server sent an unusable response: {}", e.getMessage()); + return error(HttpStatus.BAD_GATEWAY, e.getMessage()); + } + + @ExceptionHandler(BackupRunFailedException.class) + public ResponseEntity> backupRunFailed(BackupRunFailedException e) { + LOGGER.warn("Backup run failed on the server: {}", e.getMessage()); + return error(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); + } + + @ExceptionHandler(BackupRunTimeoutException.class) + public ResponseEntity> backupRunTimedOut(BackupRunTimeoutException e) { + LOGGER.warn("Backup run timed out: {}", e.getMessage()); + return error(HttpStatus.GATEWAY_TIMEOUT, e.getMessage()); + } + + @ExceptionHandler(ResourceAccessException.class) + public ResponseEntity> serverUnreachable(ResourceAccessException e) { + if (RequestTimeouts.isTimeout(e)) { + LOGGER.warn("MediaGarrd server did not respond in time: {}", e.getMessage()); + return error(HttpStatus.GATEWAY_TIMEOUT, "MediaGarrd server did not respond in time"); + } + LOGGER.warn("MediaGarrd server unreachable: {}", e.getMessage()); + return error(HttpStatus.BAD_GATEWAY, "MediaGarrd server is unreachable"); + } + + @ExceptionHandler(InvalidRequestException.class) + public ResponseEntity> invalid(InvalidRequestException e) { + LOGGER.warn("Rejected request: {}", e.getMessage()); + return error(HttpStatus.BAD_REQUEST, e.getMessage()); + } + + @ExceptionHandler(NotFoundException.class) + public ResponseEntity> notFound(NotFoundException e) { + LOGGER.warn("Rejected request: {}", e.getMessage()); + return error(HttpStatus.NOT_FOUND, e.getMessage()); + } + + @ExceptionHandler(ConflictException.class) + public ResponseEntity> conflict(ConflictException e) { + LOGGER.warn("Rejected request: {}", e.getMessage()); + return error(HttpStatus.CONFLICT, e.getMessage()); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseEntity> unreadable(HttpMessageNotReadableException e) { + if (tooLarge(e)) { + LOGGER.warn("Request body too large"); + return error(HttpStatus.CONTENT_TOO_LARGE, "Request body is too large"); + } + LOGGER.warn("Unreadable request body: {}", e.getMessage()); + return error(HttpStatus.BAD_REQUEST, "Request body is missing or malformed"); + } + + @ExceptionHandler({RuntimeException.class, ServletException.class}) + public ResponseEntity> failed(Exception e) { + if (e instanceof ErrorResponse response && response.getStatusCode().is4xxClientError()) { + LOGGER.warn("Rejected request: {}", e.getMessage()); + return error(response.getStatusCode(), response.getBody().getDetail()); + } + LOGGER.error("Request failed", e); + return error(HttpStatus.INTERNAL_SERVER_ERROR, "Internal error"); + } + + private static boolean tooLarge(Throwable e) { + for (Throwable cause = e; cause != null; cause = cause.getCause()) { + if (cause instanceof RequestTooLargeException) { + return true; + } + } + return false; + } + + private static ResponseEntity> error(HttpStatusCode status, String message) { + String fallback = status instanceof HttpStatus known ? known.getReasonPhrase() : "Request failed"; + return ResponseEntity.status(status).body(Map.of("error", Objects.requireNonNullElse(message, fallback))); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/AuthController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/AuthController.java new file mode 100644 index 0000000..255e3b6 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/AuthController.java @@ -0,0 +1,144 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.Semaphore; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseCookie; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import jakarta.servlet.http.HttpServletRequest; +import wellatleastitried.mediagarrdclient.dto.AuthStatusDto; +import wellatleastitried.mediagarrdclient.dto.PasswordRequest; +import wellatleastitried.mediagarrdclient.service.LoginAttempts; +import wellatleastitried.mediagarrdclient.service.PasswordService; +import wellatleastitried.mediagarrdclient.service.SessionService; + +@RestController +@RequestMapping("/api/auth") +public class AuthController { + + private static final Logger LOGGER = LoggerFactory.getLogger(AuthController.class); + + private static final int HASH_SLOTS = 3; + + private final Semaphore hashSlots = new Semaphore(HASH_SLOTS); + private final PasswordService passwords; + private final SessionService sessions; + private final LoginAttempts attempts; + + public AuthController(PasswordService passwords, SessionService sessions, LoginAttempts attempts) { + this.passwords = passwords; + this.sessions = sessions; + this.attempts = attempts; + } + + @PublicEndpoint + @GetMapping("/status") + public AuthStatusDto status(HttpServletRequest request) { + return new AuthStatusDto(passwords.isConfigured(), passwords.isFromEnvironment(), sessions.validate(SessionGate.sessionToken(request))); + } + + @PublicEndpoint + @PostMapping("/login") + public ResponseEntity login(@RequestBody PasswordRequest body, HttpServletRequest request) { + if (!passwords.isConfigured()) { + return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of("error", "No password is set yet")); + } + String source = request.getRemoteAddr(); + var locked = attempts.tryBegin(source); + if (locked.isPresent()) { + return tooMany(source, locked.get()); + } + if (!hashSlots.tryAcquire()) { + attempts.abandon(source); + return tooMany(source, LoginAttempts.BUSY_RETRY); + } + boolean recorded = false; + try { + boolean matched; + try { + matched = passwords.matches(body.password()); + } finally { + hashSlots.release(); + } + if (!matched) { + attempts.failed(source); + recorded = true; + LOGGER.warn("Failed dashboard login from {}", source); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", "Incorrect password")); + } + attempts.succeeded(source); + recorded = true; + return signedIn(request); + } finally { + if (!recorded) { + attempts.abandon(source); + } + } + } + + private static ResponseEntity tooMany(String source, Duration wait) { + long seconds = Math.max(1, wait.plusMillis(999).toSeconds()); + LOGGER.warn("Login from {} refused, try again in {} second(s)", source, seconds); + return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS) + .header(HttpHeaders.RETRY_AFTER, Long.toString(seconds)) + .body(Map.of("error", "Too many login attempts, try again in " + seconds + " seconds")); + } + + @PublicEndpoint + @PostMapping("/set-password") + public ResponseEntity setPassword(@RequestBody PasswordRequest body, HttpServletRequest request) { + passwords.setInitial(body.password()); + sessions.clear(); + LOGGER.info("Dashboard password set from {}", request.getRemoteAddr()); + return signedIn(request); + } + + @PublicEndpoint + @PostMapping("/logout") + public ResponseEntity logout(HttpServletRequest request) { + sessions.invalidate(SessionGate.sessionToken(request)); + return ResponseEntity.noContent().header(HttpHeaders.SET_COOKIE, cookie("", Duration.ZERO, request).toString()).build(); + } + + private ResponseEntity signedIn(HttpServletRequest request) { + String token = sessions.create(); + return ResponseEntity.ok() + .header(HttpHeaders.SET_COOKIE, cookie(token, null, request).toString()) + .body(Map.of("authenticated", true)); + } + + private static ResponseCookie cookie(String value, Duration maxAge, HttpServletRequest request) { + ResponseCookie.ResponseCookieBuilder builder = ResponseCookie.from(SessionGate.COOKIE, value) + .httpOnly(true) + .secure(isSecure(request)) + .sameSite("Strict") + .path("/"); + if (maxAge != null) { + builder.maxAge(maxAge); + } + return builder.build(); + } + + static boolean isSecure(HttpServletRequest request) { + if (request.isSecure()) { + return true; + } + String forwarded = request.getHeader("X-Forwarded-Proto"); + if (forwarded == null) { + return false; + } + int comma = forwarded.indexOf(','); + return "https".equalsIgnoreCase((comma < 0 ? forwarded : forwarded.substring(0, comma)).trim()); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/BodyLimitFilter.java b/src/main/java/wellatleastitried/mediagarrdclient/api/BodyLimitFilter.java new file mode 100644 index 0000000..8d59635 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/BodyLimitFilter.java @@ -0,0 +1,129 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +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; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE + 1) +public class BodyLimitFilter extends OncePerRequestFilter { + + static final long MAX_BODY_BYTES = 64 * 1024; + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + return !request.getRequestURI().startsWith("/api/"); + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + if (request.getContentLengthLong() > MAX_BODY_BYTES) { + response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding("UTF-8"); + response.getWriter().write("{\"error\":\"Request body is too large\"}"); + return; + } + chain.doFilter(new LimitedRequest(request, MAX_BODY_BYTES), response); + } + + private static final class LimitedRequest extends HttpServletRequestWrapper { + + private final long limit; + private ServletInputStream stream; + + private LimitedRequest(HttpServletRequest request, long limit) { + super(request); + this.limit = limit; + } + + @Override + public ServletInputStream getInputStream() throws IOException { + if (stream == null) { + stream = new LimitedStream(super.getInputStream(), limit); + } + return stream; + } + + @Override + public BufferedReader getReader() throws IOException { + String encoding = getCharacterEncoding(); + Charset charset = encoding == null ? StandardCharsets.UTF_8 : Charset.forName(encoding); + return new BufferedReader(new InputStreamReader(getInputStream(), charset)); + } + } + + private static final class LimitedStream extends ServletInputStream { + + private final ServletInputStream delegate; + private final long limit; + private long count; + + private LimitedStream(ServletInputStream delegate, long limit) { + this.delegate = delegate; + this.limit = limit; + } + + @Override + public int read() throws IOException { + int value = delegate.read(); + if (value >= 0) { + counted(1); + } + return value; + } + + @Override + public int read(byte[] buffer, int offset, int length) throws IOException { + int read = delegate.read(buffer, offset, length); + if (read > 0) { + counted(read); + } + return read; + } + + private void counted(int bytes) throws IOException { + count += bytes; + if (count > limit) { + throw new RequestTooLargeException(limit); + } + } + + @Override + public boolean isFinished() { + return delegate.isFinished(); + } + + @Override + public boolean isReady() { + return delegate.isReady(); + } + + @Override + public void setReadListener(ReadListener listener) { + delegate.setReadListener(listener); + } + + @Override + public void close() throws IOException { + delegate.close(); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java new file mode 100644 index 0000000..f6ca375 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java @@ -0,0 +1,111 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.util.List; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.ClientStatusDto; +import wellatleastitried.mediagarrdclient.dto.DashboardState; +import wellatleastitried.mediagarrdclient.dto.IntervalUpdateRequest; +import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; +import wellatleastitried.mediagarrdclient.dto.PickupStartDto; +import wellatleastitried.mediagarrdclient.dto.ServerSelectionRequest; +import wellatleastitried.mediagarrdclient.service.BackupPickupService; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.DashboardService; +import wellatleastitried.mediagarrdclient.service.ServerApiService; +import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; +import wellatleastitried.mediagarrdclient.service.ServerSelectionService; + +@RestController +@RequestMapping("/api/client") +public class ClientController { + + private final ClientStateService stateService; + private final ServerDiscoveryService discoveryService; + private final ServerApiService serverApiService; + private final BackupPickupService pickupService; + private final DashboardService dashboardService; + private final ServerSelectionService selectionService; + + public ClientController( + ClientStateService stateService, + ServerDiscoveryService discoveryService, + ServerApiService serverApiService, + BackupPickupService pickupService, + DashboardService dashboardService, + ServerSelectionService selectionService + ) { + this.stateService = stateService; + this.discoveryService = discoveryService; + this.serverApiService = serverApiService; + this.pickupService = pickupService; + this.dashboardService = dashboardService; + this.selectionService = selectionService; + } + + @GetMapping("/status") + public ClientStatusDto status() { + return currentStatus(); + } + + @GetMapping("/dashboard") + public DashboardState dashboard() { + return dashboardService.state(); + } + + @PostMapping("/discover") + public List discover() { + List discovered = discoveryService.discover(); + stateService.updateKnownServers(discovered); + return discovered; + } + + @PutMapping("/server") + public ClientStatusDto setServer(@RequestBody ServerSelectionRequest request) { + selectionService.select(request); + return currentStatus(); + } + + @GetMapping("/backups") + public List listBackups() { + return serverApiService.listBackups(stateService.requireActiveServer()); + } + + @PostMapping("/backups/run") + public void runBackup() { + serverApiService.triggerBackup(stateService.requireActiveServer()); + } + + @PostMapping("/pickup") + public PickupStartDto pickupLatest() { + return pickupService.startPickupLatestTask(); + } + + @PostMapping("/pickup/{id}") + public PickupStartDto pickupById(@PathVariable String id) { + return pickupService.startPickupByIdTask(id); + } + + @GetMapping("/pickup/progress/{taskId}") + public PickupProgressDto pickupProgress(@PathVariable String taskId) { + return pickupService.pickupProgress(taskId); + } + + @PutMapping("/pickup-interval") + public ClientStatusDto updatePickupInterval(@RequestBody IntervalUpdateRequest request) { + pickupService.updatePickupInterval(request.interval()); + return currentStatus(); + } + + private ClientStatusDto currentStatus() { + return new ClientStatusDto(stateService.getActiveServer(), stateService.getPickupInterval(), stateService.getKnownServers()); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcaster.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcaster.java new file mode 100644 index 0000000..dcc4ad3 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcaster.java @@ -0,0 +1,236 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.LongFunction; +import java.util.function.Predicate; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdclient.service.ClientEvent; +import wellatleastitried.mediagarrdclient.service.ClientEventPublisher; +import wellatleastitried.mediagarrdclient.service.SessionService; + +@Service +public class ClientEventBroadcaster implements ClientEventPublisher { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClientEventBroadcaster.class); + private static final Duration PING_INTERVAL = Duration.ofSeconds(20); + private static final Duration STREAM_LIFETIME = Duration.ofSeconds(270); + private static final Duration EMITTER_TIMEOUT = Duration.ofMinutes(6); + private static final int MAX_SUBSCRIBERS = 32; + private static final int QUEUE_CAPACITY = 64; + private static final long RETRY_MILLIS = 5000; + private static final String PING_DATA = "{}"; + + private static final ClientEvent PING = new ClientEvent("ping", PING_DATA); + private static final ClientEvent CLOSE = new ClientEvent("close", ""); + + private final class Subscriber { + + private final SseEmitter emitter; + private final String sessionKey; + private final BlockingQueue queue = new LinkedBlockingQueue<>(queueCapacity); + private volatile boolean closed; + + private Subscriber(SseEmitter emitter, String sessionKey) { + this.emitter = emitter; + this.sessionKey = sessionKey; + } + + private boolean offer(ClientEvent message) { + return !closed && queue.offer(message); + } + + private void close() { + closed = true; + queue.offer(CLOSE); + } + + private void run() { + boolean failed = false; + boolean first = true; + long deadline = System.nanoTime() + streamLifetime.toNanos(); + try { + while (!closed) { + long remainingMillis = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()); + if (remainingMillis <= 0) { + break; + } + ClientEvent polled = queue.poll(Math.min(pingInterval.toMillis(), remainingMillis), TimeUnit.MILLISECONDS); + if (closed || polled == CLOSE) { + break; + } + if (polled == null && (System.nanoTime() >= deadline || sessionKey != null && !sessionActive.test(sessionKey))) { + break; + } + ClientEvent message = polled == null ? PING : polled; + SseEmitter.SseEventBuilder event = SseEmitter.event(); + if (first) { + event.reconnectTime(RETRY_MILLIS); + first = false; + } + emitter.send(event.name(message.name()).data(message.data())); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (IOException | RuntimeException e) { + failed = true; + LOGGER.debug("Browser event stream ended: {}", e.getMessage()); + } finally { + detach(this); + if (!failed) { + try { + emitter.complete(); + } catch (RuntimeException e) { + LOGGER.debug("Completing browser event stream failed: {}", e.getMessage()); + } + } + } + } + } + + private final Duration pingInterval; + private final int maxSubscribers; + private final int queueCapacity; + private final Duration streamLifetime; + private final long emitterTimeoutMillis; + private final ThreadFactory threadFactory; + private final LongFunction emitterFactory; + private final Predicate sessionActive; + private final Object lock = new Object(); + private final List subscribers = new ArrayList<>(); + private boolean shutdown; + + @Autowired + public ClientEventBroadcaster(SessionService sessions) { + this(PING_INTERVAL, MAX_SUBSCRIBERS, QUEUE_CAPACITY, STREAM_LIFETIME, EMITTER_TIMEOUT, writerThreads(), SseEmitter::new, sessions::isActive); + sessions.addEndedListener(this::endSession); + } + + ClientEventBroadcaster( + Duration pingInterval, + int maxSubscribers, + int queueCapacity, + Duration streamLifetime, + Duration emitterTimeout, + ThreadFactory threadFactory, + LongFunction emitterFactory + ) { + this(pingInterval, maxSubscribers, queueCapacity, streamLifetime, emitterTimeout, threadFactory, emitterFactory, key -> true); + } + + ClientEventBroadcaster( + Duration pingInterval, + int maxSubscribers, + int queueCapacity, + Duration streamLifetime, + Duration emitterTimeout, + ThreadFactory threadFactory, + LongFunction emitterFactory, + Predicate sessionActive + ) { + this.sessionActive = sessionActive; + this.pingInterval = pingInterval; + this.maxSubscribers = maxSubscribers; + this.queueCapacity = queueCapacity; + this.streamLifetime = streamLifetime; + this.emitterTimeoutMillis = emitterTimeout.toMillis(); + this.threadFactory = threadFactory; + this.emitterFactory = emitterFactory; + } + + private static ThreadFactory writerThreads() { + AtomicInteger counter = new AtomicInteger(); + return runnable -> Thread.ofPlatform().daemon().name("client-events-writer-" + counter.incrementAndGet()).unstarted(runnable); + } + + public Optional subscribe(List initial) { + return subscribe(null, initial); + } + + public Optional subscribe(String sessionKey, List initial) { + SseEmitter emitter = emitterFactory.apply(emitterTimeoutMillis); + Subscriber subscriber = new Subscriber(emitter, sessionKey); + Thread writer = threadFactory.newThread(subscriber::run); + synchronized (lock) { + if (shutdown || subscribers.size() >= maxSubscribers) { + return Optional.empty(); + } + subscribers.add(subscriber); + initial.forEach(subscriber::offer); + } + emitter.onCompletion(() -> detach(subscriber)); + emitter.onTimeout(() -> detach(subscriber)); + emitter.onError(error -> detach(subscriber)); + writer.start(); + return Optional.of(emitter); + } + + @Override + public void publish(String name, String data) { + synchronized (lock) { + broadcast(new ClientEvent(name, data)); + } + } + + void endSession(String sessionKey) { + synchronized (lock) { + subscribers.removeIf(subscriber -> { + boolean ends = sessionKey.equals(subscriber.sessionKey); + if (ends) { + subscriber.close(); + } + return ends; + }); + } + } + + public int subscriberCount() { + synchronized (lock) { + return subscribers.size(); + } + } + + @PreDestroy + void shutdown() { + synchronized (lock) { + shutdown = true; + subscribers.forEach(Subscriber::close); + subscribers.clear(); + } + } + + private void broadcast(ClientEvent message) { + Iterator iterator = subscribers.iterator(); + while (iterator.hasNext()) { + Subscriber subscriber = iterator.next(); + if (!subscriber.offer(message)) { + LOGGER.warn("Dropping a browser event subscriber that is not keeping up"); + subscriber.close(); + iterator.remove(); + } + } + } + + private void detach(Subscriber subscriber) { + synchronized (lock) { + subscribers.remove(subscriber); + } + subscriber.close(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java new file mode 100644 index 0000000..1f2890d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java @@ -0,0 +1,49 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.async.AsyncRequestNotUsableException; +import org.springframework.web.context.request.async.AsyncRequestTimeoutException; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import jakarta.servlet.http.HttpServletRequest; +import wellatleastitried.mediagarrdclient.service.DashboardService; +import wellatleastitried.mediagarrdclient.service.SessionService; + +@RestController +@RequestMapping("/api/client") +public class ClientEventsController { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClientEventsController.class); + + private final DashboardService dashboard; + private final ClientEventBroadcaster broadcaster; + + public ClientEventsController(DashboardService dashboard, ClientEventBroadcaster broadcaster) { + this.dashboard = dashboard; + this.broadcaster = broadcaster; + } + + @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public ResponseEntity events(HttpServletRequest request) { + String sessionKey = SessionService.keyOf(SessionGate.sessionToken(request)); + return dashboard.subscribe(initial -> broadcaster.subscribe(sessionKey, initial)) + .map(emitter -> ResponseEntity.ok() + .header("X-Accel-Buffering", "no") + .body(emitter)) + .orElseGet(() -> ResponseEntity.status(503).build()); + } + + @ExceptionHandler({IOException.class, AsyncRequestNotUsableException.class, AsyncRequestTimeoutException.class}) + public void streamEnded(Exception e) { + LOGGER.debug("Browser event stream ended: {}", e.getMessage()); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/CsrfCheck.java b/src/main/java/wellatleastitried/mediagarrdclient/api/CsrfCheck.java new file mode 100644 index 0000000..8615e66 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/CsrfCheck.java @@ -0,0 +1,53 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.net.URI; +import java.util.Locale; +import java.util.Set; + +import jakarta.servlet.http.HttpServletRequest; + +final class CsrfCheck { + + static final String HEADER = "X-MediaGarrd-Request"; + private static final Set SAFE_METHODS = Set.of("GET", "HEAD", "OPTIONS", "TRACE"); + + private CsrfCheck() { + } + + static boolean allows(HttpServletRequest request) { + if (SAFE_METHODS.contains(request.getMethod().toUpperCase(Locale.ROOT))) { + return true; + } + String fetchSite = request.getHeader("Sec-Fetch-Site"); + if (fetchSite != null) { + return "same-origin".equalsIgnoreCase(fetchSite.trim()); + } + String origin = request.getHeader("Origin"); + if (origin == null) { + return "1".equals(request.getHeader(HEADER)); + } + String authority = originAuthority(origin); + if (authority == null) { + return false; + } + return authority.equalsIgnoreCase(firstValue(request.getHeader("Host"))) + || authority.equalsIgnoreCase(firstValue(request.getHeader("X-Forwarded-Host"))); + } + + private static String originAuthority(String origin) { + try { + URI uri = URI.create(origin.trim()); + return uri.getScheme() == null ? null : uri.getRawAuthority(); + } catch (IllegalArgumentException e) { + return null; + } + } + + private static String firstValue(String header) { + if (header == null) { + return null; + } + int comma = header.indexOf(','); + return (comma < 0 ? header : header.substring(0, comma)).trim(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/PairingController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/PairingController.java new file mode 100644 index 0000000..666b104 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/PairingController.java @@ -0,0 +1,39 @@ +package wellatleastitried.mediagarrdclient.api; + +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdclient.dto.PairRequest; +import wellatleastitried.mediagarrdclient.dto.PairingCodeDto; +import wellatleastitried.mediagarrdclient.dto.PairingResultDto; +import wellatleastitried.mediagarrdclient.dto.UnpairResultDto; +import wellatleastitried.mediagarrdclient.service.ClientPairingService; + +@RestController +@RequestMapping("/api/client/pairing") +public class PairingController { + + private final ClientPairingService pairing; + + public PairingController(ClientPairingService pairing) { + this.pairing = pairing; + } + + @PostMapping + public PairingResultDto pair(@RequestBody PairRequest request) { + return pairing.pair(request.pin(), request.name()); + } + + @PostMapping("/code") + public PairingCodeDto createCode() { + return pairing.createCode(); + } + + @DeleteMapping + public UnpairResultDto unpair() { + return pairing.unpair(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/PublicEndpoint.java b/src/main/java/wellatleastitried/mediagarrdclient/api/PublicEndpoint.java new file mode 100644 index 0000000..f274d2f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/PublicEndpoint.java @@ -0,0 +1,13 @@ +package wellatleastitried.mediagarrdclient.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 { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/RequestTooLargeException.java b/src/main/java/wellatleastitried/mediagarrdclient/api/RequestTooLargeException.java new file mode 100644 index 0000000..909b0ee --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/RequestTooLargeException.java @@ -0,0 +1,10 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.io.IOException; + +public class RequestTooLargeException extends IOException { + + public RequestTooLargeException(long limit) { + super("The request body is larger than " + limit + " bytes"); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/SecurityHeadersFilter.java b/src/main/java/wellatleastitried/mediagarrdclient/api/SecurityHeadersFilter.java new file mode 100644 index 0000000..89017bd --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/SecurityHeadersFilter.java @@ -0,0 +1,33 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.io.IOException; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +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 'self'; form-action 'self'; object-src 'none'"; + + @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 (request.getRequestURI().startsWith("/api/")) { + response.setHeader("Cache-Control", "no-store"); + } + chain.doFilter(request, response); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java new file mode 100644 index 0000000..7fd7361 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java @@ -0,0 +1,102 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.time.Duration; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; +import wellatleastitried.mediagarrdclient.service.ServerApiService; +import wellatleastitried.mediagarrdclient.service.ServiceNames; + +@RestController +@RequestMapping("/api/client") +public class ServerConfigController { + + private static final Logger LOGGER = LoggerFactory.getLogger(ServerConfigController.class); + + private static final Duration MIN_INTERVAL = Duration.ofMinutes(15); + private static final Duration MAX_INTERVAL = Duration.ofDays(365); + static final String INTERVAL_MESSAGE = "Backup interval must be between 15 minutes and 365 days"; + + private final ClientStateService stateService; + private final ServerApiService serverApiService; + + public ServerConfigController(ClientStateService stateService, ServerApiService serverApiService) { + this.stateService = stateService; + this.serverApiService = serverApiService; + } + + @GetMapping("/server-config") + public ServerConfigDto serverConfig() { + String activeServer = stateService.requireActiveServer(); + LOGGER.debug("GET /api/client/server-config, forwarding to {}", activeServer); + return serverApiService.serverConfig(activeServer); + } + + @PutMapping("/server-config") + public ServerConfigDto updateServerConfig(@RequestBody ServerConfigDto request) { + String activeServer = stateService.requireActiveServer(); + requireValidInterval(request.backupInterval()); + LOGGER.info("PUT /api/client/server-config, request={}, target={}", request, activeServer); + ServerConfigDto config = serverApiService.updateServerConfig(activeServer, request.backupLocation(), request.retentionCount()); + if (request.backupInterval() == null) { + return config; + } + ServerStatusDto status = serverApiService.updateServerSchedule(activeServer, request.backupInterval()); + return new ServerConfigDto(config.backupLocation(), config.retentionCount(), status.backupInterval()); + } + + private static void requireValidInterval(Duration interval) { + if (interval != null && (interval.compareTo(MIN_INTERVAL) < 0 || interval.compareTo(MAX_INTERVAL) > 0)) { + throw new InvalidRequestException(INTERVAL_MESSAGE); + } + } + + @GetMapping("/services") + public List services() { + String activeServer = stateService.requireActiveServer(); + LOGGER.debug("GET /api/client/services, forwarding to {}", activeServer); + return serverApiService.listServices(activeServer); + } + + @PostMapping("/services") + @ResponseStatus(HttpStatus.CREATED) + public ServiceDto addService(@RequestBody ServiceDto service) { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("POST /api/client/services, name={}, target={}", service.name(), activeServer); + return serverApiService.addService(activeServer, service); + } + + @PutMapping("/services/{name}") + public ServiceDto updateService(@PathVariable String name, @RequestBody ServiceDto service) { + ServiceNames.require(name); + String activeServer = stateService.requireActiveServer(); + LOGGER.info("PUT /api/client/services/{}, name={}, target={}", name, service.name(), activeServer); + return serverApiService.updateService(activeServer, name, service); + } + + @DeleteMapping("/services/{name}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void removeService(@PathVariable String name) { + ServiceNames.require(name); + String activeServer = stateService.requireActiveServer(); + LOGGER.info("DELETE /api/client/services/{}, target={}", name, activeServer); + serverApiService.removeService(activeServer, name); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/SessionGate.java b/src/main/java/wellatleastitried/mediagarrdclient/api/SessionGate.java new file mode 100644 index 0000000..ad4575b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/SessionGate.java @@ -0,0 +1,71 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.io.IOException; + +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.mvc.ParameterizableViewController; +import org.springframework.web.servlet.resource.ResourceHttpRequestHandler; +import org.springframework.web.util.WebUtils; + +import jakarta.servlet.DispatcherType; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import wellatleastitried.mediagarrdclient.service.SessionService; + +@Component +public class SessionGate implements HandlerInterceptor { + + static final String COOKIE = "mg_session"; + + private final SessionService sessions; + + public SessionGate(SessionService sessions) { + this.sessions = sessions; + } + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { + if (request.getDispatcherType() != DispatcherType.REQUEST) { + return true; + } + if (!CsrfCheck.allows(request)) { + return reject(response, HttpServletResponse.SC_FORBIDDEN, "{\"error\":\"Cross-site request rejected\"}"); + } + if (isStaticContent(handler) || isPublic(handler)) { + return true; + } + if (sessions.validate(sessionToken(request))) { + return true; + } + return reject(response, HttpServletResponse.SC_UNAUTHORIZED, "{\"error\":\"Login required\",\"login\":\"required\"}"); + } + + static String sessionToken(HttpServletRequest request) { + Cookie cookie = WebUtils.getCookie(request, COOKIE); + return cookie == null ? null : cookie.getValue(); + } + + private static boolean isStaticContent(Object handler) { + return handler instanceof ResourceHttpRequestHandler || isWelcomePage(handler); + } + + private static boolean isWelcomePage(Object handler) { + return handler instanceof ParameterizableViewController view && "forward:index.html".equals(view.getViewName()); + } + + private static boolean isPublic(Object handler) { + return handler instanceof HandlerMethod method && method.hasMethodAnnotation(PublicEndpoint.class); + } + + private static boolean reject(HttpServletResponse response, int status, String body) throws IOException { + response.setStatus(status); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding("UTF-8"); + response.getWriter().write(body); + return false; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/WebMvcConfig.java b/src/main/java/wellatleastitried/mediagarrdclient/api/WebMvcConfig.java new file mode 100644 index 0000000..9edd4be --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/WebMvcConfig.java @@ -0,0 +1,20 @@ +package wellatleastitried.mediagarrdclient.api; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + + private final SessionGate sessionGate; + + public WebMvcConfig(SessionGate sessionGate) { + this.sessionGate = sessionGate; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(sessionGate).addPathPatterns("/**"); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/WebhookController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/WebhookController.java new file mode 100644 index 0000000..270976a --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/WebhookController.java @@ -0,0 +1,52 @@ +package wellatleastitried.mediagarrdclient.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.mediagarrdclient.dto.WebhookStatusDto; +import wellatleastitried.mediagarrdclient.dto.WebhookTestDto; +import wellatleastitried.mediagarrdclient.dto.WebhookUpdateRequest; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.ServerApiService; + +@RestController +@RequestMapping("/api/client/notifications/webhook") +public class WebhookController { + + private static final Logger LOGGER = LoggerFactory.getLogger(WebhookController.class); + + private final ClientStateService stateService; + private final ServerApiService serverApiService; + + public WebhookController(ClientStateService stateService, ServerApiService serverApiService) { + this.stateService = stateService; + this.serverApiService = serverApiService; + } + + @GetMapping + public WebhookStatusDto webhook() { + String activeServer = stateService.requireActiveServer(); + LOGGER.debug("GET /api/client/notifications/webhook, forwarding to {}", activeServer); + return serverApiService.webhook(activeServer); + } + + @PutMapping + public WebhookStatusDto updateWebhook(@RequestBody WebhookUpdateRequest request) { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("PUT /api/client/notifications/webhook, target={}", activeServer); + return serverApiService.updateWebhook(activeServer, request.url()); + } + + @PostMapping("/test") + public WebhookTestDto testWebhook() { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("POST /api/client/notifications/webhook/test, target={}", activeServer); + return serverApiService.testWebhook(activeServer); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/AuthStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/AuthStatusDto.java new file mode 100644 index 0000000..784dadb --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/AuthStatusDto.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record AuthStatusDto(boolean passwordSet, boolean passwordFromEnvironment, boolean authenticated) { +} diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/BackupDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/BackupDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/BackupDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/BackupDto.java diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/CheckState.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/CheckState.java new file mode 100644 index 0000000..d6ca709 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/CheckState.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdclient.dto; + +public enum CheckState { + NOT_CHECKED, + OK, + NO_RELEASES, + UNAVAILABLE, + ERROR +} diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/ClientStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ClientStatusDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/ClientStatusDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/ClientStatusDto.java diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/DashboardState.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/DashboardState.java new file mode 100644 index 0000000..7018c9e --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/DashboardState.java @@ -0,0 +1,14 @@ +package wellatleastitried.mediagarrdclient.dto; + +import java.util.List; + +public record DashboardState( + String activeServer, + List knownServers, + LinkState link, + Boolean running, + HealthSummary health, + VersionsDto versions, + PairingState pairing +) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/HealthSummary.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/HealthSummary.java new file mode 100644 index 0000000..65d029a --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/HealthSummary.java @@ -0,0 +1,6 @@ +package wellatleastitried.mediagarrdclient.dto; + +import java.time.Duration; + +public record HealthSummary(Duration backupInterval, int backupRetentionCount) { +} diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/IntervalUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/IntervalUpdateRequest.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/IntervalUpdateRequest.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/IntervalUpdateRequest.java diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/LinkState.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/LinkState.java new file mode 100644 index 0000000..5ad4e28 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/LinkState.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.dto; + +public enum LinkState { + LIVE, + CONNECTING, + DEGRADED, + DOWN +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/PairRequest.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairRequest.java new file mode 100644 index 0000000..c45c6bf --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairRequest.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record PairRequest(String pin, String name) { + + @Override + public String toString() { + return "PairRequest[name=" + name + "]"; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingCodeDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingCodeDto.java new file mode 100644 index 0000000..8633ebf --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingCodeDto.java @@ -0,0 +1,6 @@ +package wellatleastitried.mediagarrdclient.dto; + +import java.time.Instant; + +public record PairingCodeDto(String code, Instant expiresAt) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingResultDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingResultDto.java new file mode 100644 index 0000000..870c922 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingResultDto.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record PairingResultDto(boolean paired, String name, String note) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingState.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingState.java new file mode 100644 index 0000000..3ca4624 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingState.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.dto; + +public enum PairingState { + NONE, + PAIRED, + REQUIRED, + REJECTED +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/PasswordRequest.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PasswordRequest.java new file mode 100644 index 0000000..6791500 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/PasswordRequest.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record PasswordRequest(String password) { + + @Override + public String toString() { + return "PasswordRequest[]"; + } +} diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/PickupProgressDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PickupProgressDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/PickupProgressDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/PickupProgressDto.java diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/PickupStartDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PickupStartDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/PickupStartDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/PickupStartDto.java diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerConfigDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerConfigDto.java new file mode 100644 index 0000000..0d0b8fe --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerConfigDto.java @@ -0,0 +1,6 @@ +package wellatleastitried.mediagarrdclient.dto; + +import java.time.Duration; + +public record ServerConfigDto(String backupLocation, Integer retentionCount, Duration backupInterval) { +} diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/ServerSelectionRequest.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerSelectionRequest.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/ServerSelectionRequest.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/ServerSelectionRequest.java diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/ServerStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerStatusDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/ServerStatusDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/ServerStatusDto.java diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/ServiceDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServiceDto.java new file mode 100644 index 0000000..fdaf639 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServiceDto.java @@ -0,0 +1,6 @@ +package wellatleastitried.mediagarrdclient.dto; + +import java.util.List; + +public record ServiceDto(String name, List paths) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/UnpairResultDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/UnpairResultDto.java new file mode 100644 index 0000000..bc1d2da --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/UnpairResultDto.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record UnpairResultDto(boolean serverRevoked, String warning) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/VersionStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/VersionStatusDto.java new file mode 100644 index 0000000..04a3d30 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/VersionStatusDto.java @@ -0,0 +1,13 @@ +package wellatleastitried.mediagarrdclient.dto; + +import java.time.Instant; + +public record VersionStatusDto( + String currentVersion, + String latestVersion, + String releaseUrl, + boolean updateAvailable, + CheckState checkState, + Instant checkedAt, + String message +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/VersionsDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/VersionsDto.java new file mode 100644 index 0000000..28c69a5 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/VersionsDto.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record VersionsDto(VersionStatusDto client, VersionStatusDto server) {} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookStatusDto.java new file mode 100644 index 0000000..65967bc --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookStatusDto.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record WebhookStatusDto(boolean configured, String target) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookTestDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookTestDto.java new file mode 100644 index 0000000..33c6519 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookTestDto.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record WebhookTestDto(boolean delivered, Integer status, String error) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookUpdateRequest.java new file mode 100644 index 0000000..7bf8855 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookUpdateRequest.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record WebhookUpdateRequest(String url) { + + @Override + public String toString() { + return "WebhookUpdateRequest[url=]"; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/protocol/Endpoints.java b/src/main/java/wellatleastitried/mediagarrdclient/protocol/Endpoints.java new file mode 100644 index 0000000..f59adf9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/protocol/Endpoints.java @@ -0,0 +1,28 @@ +package wellatleastitried.mediagarrdclient.protocol; + +public enum Endpoints { + + SERVER_HEALTH("/api/v1/health"), + SERVER_VERSION("/api/v1/version"), + SERVER_BACKUPS("/api/v1/backups"), + SERVER_BACKUP_RUN("/api/v1/backups/run"), + SERVER_SCHEDULE("/api/v1/schedule"), + SERVER_CONFIG("/api/v1/config"), + SERVER_SERVICES("/api/v1/services"), + SERVER_WEBHOOK("/api/v1/notifications/webhook"), + SERVER_WEBHOOK_TEST("/api/v1/notifications/webhook/test"), + SERVER_EVENTS("/api/v1/events"), + SERVER_PAIR("/api/v1/pair"), + SERVER_PAIRING_CODES("/api/v1/pairing-codes"), + SERVER_CLIENTS("/api/v1/clients"); + + private final String path; + + Endpoints(String path) { + this.path = path; + } + + public String getPath() { + return path; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java new file mode 100644 index 0000000..7b379c1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java @@ -0,0 +1,440 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClientResponseException; + +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; +import wellatleastitried.mediagarrdclient.dto.PickupStartDto; + +@Service +public class BackupPickupService { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupPickupService.class); + private static final String AUTO_DOWNLOAD_SUFFIX = "-AD"; + private static final String ZIP_SUFFIX = ".zip"; + private static final String PART_SUFFIX = ".part"; + static final Duration FINISHED_TASK_RETENTION = Duration.ofMinutes(10); + static final String GENERIC_FAILURE = "The download failed, see the client log for details"; + + private enum PickupStatus { QUEUED, RUNNING, COMPLETED, FAILED } + + private final class PickupTask { + private final String taskId = UUID.randomUUID().toString(); + private final BackupDto backup; + private final boolean latest; + private volatile PickupStatus status = PickupStatus.QUEUED; + private volatile long bytesWritten; + private volatile long totalBytes; + private volatile Path savedPath; + private volatile String error; + private volatile Instant finishedAt; + + private PickupTask(BackupDto backup, boolean latest) { + this.backup = backup; + this.latest = latest; + this.totalBytes = backup.sizeBytes(); + } + + private boolean finished() { + return finishedAt != null; + } + + private void complete(Path path) { + savedPath = path; + bytesWritten = Math.max(bytesWritten, totalBytes); + totalBytes = Math.max(totalBytes, bytesWritten); + status = PickupStatus.COMPLETED; + finishedAt = clock.instant(); + } + + private void fail(String message) { + error = message; + status = PickupStatus.FAILED; + finishedAt = clock.instant(); + } + + private PickupStartDto started() { + return new PickupStartDto(taskId, backup.id(), backup.fileName(), totalBytes); + } + + private PickupProgressDto progress() { + return new PickupProgressDto(taskId, status.name(), backup.id(), backup.fileName(), bytesWritten, totalBytes, + savedPath == null ? null : savedPath.toString(), error); + } + } + + private final MediaGarrdProperties configuration; + private final ClientStateService clientStateService; + private final ServerApiService serverApiService; + private final Clock clock; + private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor(); + private final ExecutorService scheduledExecutor = Executors.newVirtualThreadPerTaskExecutor(); + private final AtomicBoolean scheduledRunning = new AtomicBoolean(); + private final AtomicBoolean noBackupsReported = new AtomicBoolean(); + private final Map tasks = new LinkedHashMap<>(); + private final PickupSchedule schedule; + + @Autowired + public BackupPickupService(MediaGarrdProperties configuration, ClientStateService clientStateService, ServerApiService serverApiService) { + this(configuration, clientStateService, serverApiService, Clock.systemUTC()); + } + + BackupPickupService(MediaGarrdProperties configuration, ClientStateService clientStateService, ServerApiService serverApiService, Clock clock) { + this.configuration = configuration; + this.clientStateService = clientStateService; + this.serverApiService = serverApiService; + this.clock = clock; + this.schedule = new PickupSchedule(clock); + clientStateService.addActiveServerListener(server -> noBackupsReported.set(false)); + } + + @PostConstruct + void removeStalePartFilesAtStartup() { + removeStalePartFiles(downloadsDirectory()); + } + + @Scheduled(fixedDelay = 60_000) + public void scheduledPickup() { + if (!paired() || !schedule.due(clientStateService.getLastPickupAt(), clientStateService.getPickupInterval()) + || !scheduledRunning.compareAndSet(false, true)) { + return; + } + try { + scheduledExecutor.execute(this::runScheduledPickup); + } catch (RejectedExecutionException e) { + scheduledRunning.set(false); + } + } + + void runScheduledPickup() { + try { + Path saved = pickupLatestAuto(); + noBackupsReported.set(false); + if (saved == null) { + LOGGER.debug("Scheduled pickup deferred, the latest backup is being downloaded by a manual pickup"); + } else { + LOGGER.info("Scheduled pickup saved {}, next pickup at {}", saved, nextPickup()); + } + } catch (NoBackupsException e) { + Instant retryAt = schedule.failed(); + if (noBackupsReported.compareAndSet(false, true)) { + LOGGER.info("The server has no backups yet, checking again at {}. Further checks are logged at DEBUG until a backup exists", retryAt); + } else { + LOGGER.debug("The server still has no backups, checking again at {}", retryAt); + } + } catch (RuntimeException e) { + noBackupsReported.set(false); + LOGGER.warn("Scheduled pickup failed, next attempt at {}: {}", schedule.failed(), e.getMessage()); + } finally { + scheduledRunning.set(false); + } + } + + public Duration updatePickupInterval(Duration interval) { + Duration updated = clientStateService.setPickupInterval(interval); + schedule.reset(); + return updated; + } + + public Instant nextPickup() { + return schedule.dueAt(clientStateService.getLastPickupAt(), clientStateService.getPickupInterval()); + } + + boolean scheduledRunning() { + return scheduledRunning.get(); + } + + private boolean paired() { + String server = clientStateService.getActiveServer(); + return server != null && !server.isBlank() && clientStateService.hasPairing(server); + } + + private void pickupSucceeded(String server) { + try { + if (clientStateService.recordPickup(server, clock.instant())) { + schedule.reset(); + } + } catch (RuntimeException e) { + LOGGER.warn("Could not record the pickup time, next attempt at {}: {}", schedule.failed(), e.getMessage()); + } + } + + public PickupStartDto startPickupLatestTask() { + String server = clientStateService.requireActiveServer(); + return startPickupTask(server, latest(serverApiService.listBackups(server)), true); + } + + public PickupStartDto startPickupByIdTask(String backupId) { + String server = clientStateService.requireActiveServer(); + List backups = serverApiService.listBackups(server); + BackupDto backup = backups.stream() + .filter(candidate -> candidate.id().equals(backupId)) + .findFirst() + .orElseThrow(() -> new NotFoundException("Backup not found: " + backupId)); + return startPickupTask(server, backup, backup.equals(backups.getFirst())); + } + + public synchronized PickupProgressDto pickupProgress(String taskId) { + PickupTask task = tasks.get(taskId); + if (task == null) { + throw new NotFoundException("Pickup task not found: " + taskId); + } + return task.progress(); + } + + private synchronized PickupStartDto startPickupTask(String server, BackupDto backup, boolean latest) { + requireArchiveFileName(backup.fileName()); + evictFinishedTasks(); + PickupTask running = tasks.values().stream() + .filter(task -> !task.finished() && task.backup.id().equals(backup.id())) + .findFirst() + .orElse(null); + if (running != null) { + LOGGER.info("Backup {} is already being downloaded by task {}", backup.id(), running.taskId); + return running.started(); + } + + Path downloads = downloadsDirectory(); + removeStalePartFiles(downloads); + Path destination = inside(downloads, backup.fileName()); + Path existing = existingCopy(downloads, backup); + PickupTask task = new PickupTask(backup, latest); + tasks.put(task.taskId, task); + if (existing != null) { + LOGGER.info("Backup {} is already downloaded at {}", backup.id(), existing); + task.complete(existing); + if (latest) { + pickupSucceeded(server); + } + } else { + try { + executor.execute(() -> download(server, destination, task)); + } catch (RejectedExecutionException e) { + task.fail(GENERIC_FAILURE); + } + } + return task.started(); + } + + private void download(String server, Path destination, PickupTask task) { + try { + transfer(server, destination, task, task.latest ? () -> pickupSucceeded(server) : null); + } catch (RuntimeException e) { + LOGGER.warn("Pickup task {} failed for backup {}: {}", task.taskId, task.backup.id(), e.getMessage()); + } + } + + private Path transfer(String server, Path destination, PickupTask task, Runnable afterSaved) { + task.status = PickupStatus.RUNNING; + try { + Path saved = serverApiService.downloadById(server, task.backup.id(), destination, (written, total) -> { + task.bytesWritten = written; + if (total > 0) { + task.totalBytes = total; + } + }); + if (afterSaved != null) { + afterSaved.run(); + } + task.complete(saved); + LOGGER.info("Pickup task {} saved {}", task.taskId, saved); + return saved; + } catch (RuntimeException e) { + task.fail(userMessage(e)); + throw e; + } + } + + private static String userMessage(RuntimeException e) { + if (e instanceof DownloadFailedException || e instanceof PairingRequiredException || e instanceof ServerRedirectException) { + return e.getMessage(); + } + if (e instanceof RestClientResponseException response) { + return "MediaGarrd server responded with " + response.getStatusCode().value(); + } + if (e instanceof ResourceAccessException) { + return "MediaGarrd server is unreachable"; + } + return GENERIC_FAILURE; + } + + private void evictFinishedTasks() { + Instant cutoff = clock.instant().minus(FINISHED_TASK_RETENTION); + tasks.values().removeIf(task -> task.finished() && task.finishedAt.isBefore(cutoff)); + } + + private Path pickupLatestAuto() { + String server = clientStateService.requireActiveServer(); + List backups = serverApiService.listBackups(server); + BackupDto latest = latest(backups); + requireArchiveFileName(latest.fileName()); + Path downloads = downloadsDirectory(); + removeStalePartFiles(downloads); + Path existing = existingCopy(downloads, latest); + if (existing != null) { + LOGGER.info("Scheduled pickup skipped, backup {} is already downloaded at {}", latest.id(), existing); + pickupSucceeded(server); + return existing; + } + + Path destination = inside(downloads, autoFileName(latest)); + ScheduledRegistration registration = registerScheduledTask(downloads, latest); + if (registration.existing() != null) { + pickupSucceeded(server); + return registration.existing(); + } + PickupTask task = registration.task(); + if (task == null) { + return null; + } + return transfer(server, destination, task, () -> { + removeSuperseded(downloads, backups, latest); + pickupSucceeded(server); + }); + } + + private record ScheduledRegistration(PickupTask task, Path existing) { + } + + private synchronized ScheduledRegistration registerScheduledTask(Path downloads, BackupDto latest) { + evictFinishedTasks(); + Path existing = existingCopy(downloads, latest); + if (existing != null) { + return new ScheduledRegistration(null, existing); + } + boolean running = tasks.values().stream().anyMatch(task -> !task.finished() && task.backup.id().equals(latest.id())); + if (running) { + return new ScheduledRegistration(null, null); + } + PickupTask task = new PickupTask(latest, true); + tasks.put(task.taskId, task); + return new ScheduledRegistration(task, null); + } + + private synchronized void removeStalePartFiles(Path downloads) { + if (!Files.isDirectory(downloads)) { + return; + } + Set inProgress = tasks.values().stream() + .filter(task -> !task.finished()) + .flatMap(task -> Stream.of(task.backup.fileName(), autoFileName(task.backup))) + .map(name -> name + PART_SUFFIX) + .collect(Collectors.toSet()); + try (Stream entries = Files.list(downloads)) { + entries + .filter(path -> path.getFileName().toString().endsWith(PART_SUFFIX)) + .filter(path -> !inProgress.contains(path.getFileName().toString())) + .filter(path -> Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) + .forEach(path -> { + if (QuietFiles.delete(path)) { + LOGGER.info("Removed incomplete download {}", path.getFileName()); + } + }); + } catch (IOException e) { + LOGGER.warn("Could not look for incomplete downloads in {}: {}", downloads, e.getMessage()); + } + } + + private Path existingCopy(Path downloads, BackupDto backup) { + return Stream.of(autoFileName(backup), backup.fileName()) + .map(name -> inside(downloads, name)) + .filter(path -> hasSize(path, backup.sizeBytes())) + .findFirst() + .orElse(null); + } + + private static void removeSuperseded(Path downloads, List backups, BackupDto current) { + try { + backups.stream() + .skip(1) + .filter(backup -> !backup.id().equals(current.id())) + .map(backup -> autoFileName(backup)) + .filter(name -> name.endsWith(AUTO_DOWNLOAD_SUFFIX + ZIP_SUFFIX)) + .map(name -> downloads.resolve(name).normalize()) + .filter(path -> downloads.equals(path.getParent())) + .filter(path -> Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) + .forEach(path -> { + if (QuietFiles.delete(path)) { + LOGGER.info("Removed superseded download {}", path.getFileName()); + } + }); + } catch (RuntimeException e) { + LOGGER.warn("Could not remove superseded downloads in {}: {}", downloads, e.getMessage()); + } + } + + private static void requireArchiveFileName(String fileName) { + if (!fileName.endsWith(ZIP_SUFFIX) || fileName.endsWith(PART_SUFFIX)) { + throw new InvalidRequestException("Backup file name must end in " + ZIP_SUFFIX + ": " + fileName); + } + } + + private static boolean hasSize(Path path, long size) { + try { + return Files.isRegularFile(path) && Files.size(path) == size; + } catch (IOException e) { + LOGGER.warn("Could not inspect {}: {}", path, e.getMessage()); + return false; + } + } + + private static BackupDto latest(List backups) { + if (backups.isEmpty()) { + throw new NoBackupsException(); + } + return backups.getFirst(); + } + + private static String autoFileName(BackupDto backup) { + String name = backup.fileName(); + return name.endsWith(ZIP_SUFFIX) + ? name.substring(0, name.length() - ZIP_SUFFIX.length()) + AUTO_DOWNLOAD_SUFFIX + ZIP_SUFFIX + : name + AUTO_DOWNLOAD_SUFFIX; + } + + private static Path inside(Path downloads, String fileName) { + Path path = downloads.resolve(fileName).normalize(); + if (!downloads.equals(path.getParent())) { + throw new InvalidRequestException("Backup file name must not leave the download directory: " + fileName); + } + return path; + } + + private Path downloadsDirectory() { + return Path.of(configuration.getDownloadDirectory()).toAbsolutePath().normalize(); + } + + @PreDestroy + void shutdown() { + executor.shutdownNow(); + scheduledExecutor.shutdownNow(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunFailedException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunFailedException.java new file mode 100644 index 0000000..f79dec9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunFailedException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class BackupRunFailedException extends RuntimeException { + + public BackupRunFailedException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunTimeoutException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunTimeoutException.java new file mode 100644 index 0000000..0325aaf --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunTimeoutException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class BackupRunTimeoutException extends RuntimeException { + + public BackupRunTimeoutException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/BackupWatcher.java b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupWatcher.java new file mode 100644 index 0000000..82db7a3 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupWatcher.java @@ -0,0 +1,109 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executor; +import java.util.function.BooleanSupplier; +import java.util.function.LongSupplier; +import java.util.function.Supplier; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import wellatleastitried.mediagarrdclient.dto.BackupDto; + +final class BackupWatcher { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupWatcher.class); + + private final ServerApiService serverApiService; + private final DashboardEvents events; + private final Clock clock; + private final Object lock; + private final Duration interval; + private final Supplier server; + private final LongSupplier epoch; + private final BooleanSupplier degraded; + private final CoalescedRefresh refresh; + private List seen; + private Instant checkedAt; + + BackupWatcher( + ServerApiService serverApiService, + DashboardEvents events, + Clock clock, + Object lock, + Executor executor, + Duration interval, + Supplier server, + LongSupplier epoch, + BooleanSupplier degraded + ) { + this.serverApiService = serverApiService; + this.events = events; + this.clock = clock; + this.lock = lock; + this.interval = interval; + this.server = server; + this.epoch = epoch; + this.degraded = degraded; + this.refresh = new CoalescedRefresh(lock, executor, this::fetch); + } + + void forget() { + seen = null; + checkedAt = null; + } + + void forgetListing() { + seen = null; + } + + void requestWhenDue() { + if (!refresh.busy() && (checkedAt == null || Duration.between(checkedAt, clock.instant()).compareTo(interval) >= 0)) { + refresh.request(); + } + } + + private void fetch() { + String target; + long expected; + synchronized (lock) { + target = server.get(); + expected = epoch.getAsLong(); + } + if (target == null) { + return; + } + List listed = list(target); + synchronized (lock) { + if (expected != epoch.getAsLong() || !degraded.getAsBoolean()) { + return; + } + record(listed); + } + } + + private List list(String target) { + try { + return serverApiService.listBackups(target); + } catch (RuntimeException e) { + LOGGER.debug("{} did not list its backups: {}", target, e.getMessage()); + return null; + } + } + + private void record(List listed) { + checkedAt = clock.instant(); + if (listed == null) { + return; + } + if (seen != null && !listed.equals(seen)) { + events.publish("backups-changed", Map.of("at", clock.instant().toString())); + } + seen = listed; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEvent.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEvent.java new file mode 100644 index 0000000..f9c0afa --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEvent.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdclient.service; + +public record ClientEvent(String name, String data) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventPublisher.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventPublisher.java new file mode 100644 index 0000000..f9e45d1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventPublisher.java @@ -0,0 +1,6 @@ +package wellatleastitried.mediagarrdclient.service; + +public interface ClientEventPublisher { + + void publish(String name, String data); +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientPairingService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientPairingService.java new file mode 100644 index 0000000..4280849 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientPairingService.java @@ -0,0 +1,133 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.util.Optional; +import java.util.function.LongConsumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.client.ResourceAccessException; + +import wellatleastitried.mediagarrdclient.dto.PairingCodeDto; +import wellatleastitried.mediagarrdclient.dto.PairingResultDto; +import wellatleastitried.mediagarrdclient.dto.UnpairResultDto; + +@Service +public class ClientPairingService { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClientPairingService.class); + static final String DEFAULT_NAME = "MediaGarrd Client"; + static final int MAX_CREDENTIAL_LENGTH = 64; + static final int MAX_NAME_LENGTH = 64; + static final String UNREVOKED_WARNING = "The server could not be told to forget this client, so it may still list it as paired. Remove it with DELETE /api/v1/clients/{id} on the server."; + static final String NOT_PAIRED_WARNING = "This client was not paired with the server."; + static final String NO_ID_WARNING = "This client has no id on the server, so it could not be removed there. Remove it with DELETE /api/v1/clients/{id} on the server."; + static final String ALREADY_PAIRED_MESSAGE = "This client is already paired with this server. Unpair it first."; + static final String DEFERRED_CONFIRMATION_NOTE = "Paired. The server could not be reached to confirm it yet; it is confirmed automatically on the next connection. If it is not, you will be asked to pair again, and the same PIN, or a new pairing code, will work."; + static final long[] CONFIRM_RETRY_DELAYS_MILLIS = {250, 500, 1000}; + + private final ClientStateService stateService; + private final ServerApiService serverApiService; + private final LongConsumer pause; + + @Autowired + public ClientPairingService(ClientStateService stateService, ServerApiService serverApiService) { + this(stateService, serverApiService, ClientPairingService::sleep); + } + + ClientPairingService(ClientStateService stateService, ServerApiService serverApiService, LongConsumer pause) { + this.stateService = stateService; + this.serverApiService = serverApiService; + this.pause = pause; + } + + public synchronized PairingResultDto pair(String credential, String name) { + if (credential == null || credential.isBlank()) { + throw new InvalidRequestException("Enter the PIN or pairing code"); + } + if (credential.trim().length() > MAX_CREDENTIAL_LENGTH) { + throw new InvalidRequestException("The PIN or pairing code must be at most " + MAX_CREDENTIAL_LENGTH + " characters"); + } + if (name != null && name.trim().length() > MAX_NAME_LENGTH) { + throw new InvalidRequestException("The name must be at most " + MAX_NAME_LENGTH + " characters"); + } + String server = stateService.requireActiveServer(); + refuseWhileAlreadyPaired(server); + StoredPairing pairing = serverApiService.pair(server, credential.trim(), name == null || name.isBlank() ? DEFAULT_NAME : name.trim()); + stateService.storePairing(server, pairing); + try { + confirm(server, pairing); + } catch (InvalidRequestException | ConfirmationRefusedException e) { + stateService.forgetPairingIf(server, pairing.token()); + throw e; + } catch (RuntimeException e) { + LOGGER.warn("Could not confirm the pairing with {}, keeping it for the next connection to confirm: {}", server, e.getMessage()); + return new PairingResultDto(true, pairing.name(), DEFERRED_CONFIRMATION_NOTE); + } + return new PairingResultDto(true, pairing.name(), null); + } + + private void refuseWhileAlreadyPaired(String server) { + Optional stored = stateService.pairingFor(server); + if (stored.isEmpty()) { + return; + } + try { + serverApiService.confirmPairing(server, stored.get().token()); + } catch (InvalidRequestException e) { + return; + } + throw new ConflictException(ALREADY_PAIRED_MESSAGE); + } + + public PairingCodeDto createCode() { + return serverApiService.createPairingCode(stateService.requireActiveServer()); + } + + public synchronized UnpairResultDto unpair() { + String server = stateService.requireActiveServer(); + StoredPairing pairing = stateService.pairingFor(server).orElse(null); + String warning = null; + if (pairing != null && hasId(pairing)) { + try { + serverApiService.revokeClient(server, pairing.id()); + } catch (RuntimeException e) { + LOGGER.warn("Could not revoke this client on {}, forgetting the token locally anyway: {}", server, e.getMessage()); + warning = UNREVOKED_WARNING; + } + } else { + warning = pairing == null ? NOT_PAIRED_WARNING : NO_ID_WARNING; + } + stateService.forgetPairing(server); + return new UnpairResultDto(warning == null, warning); + } + + private void confirm(String server, StoredPairing pairing) { + for (int attempt = 0; ; attempt++) { + try { + serverApiService.confirmPairing(server, pairing.token()); + return; + } catch (ResourceAccessException | ConfirmationUnavailableException e) { + if (attempt >= CONFIRM_RETRY_DELAYS_MILLIS.length) { + throw e; + } + LOGGER.warn("Could not confirm the pairing with {}, retrying: {}", server, e.getMessage()); + pause.accept(CONFIRM_RETRY_DELAYS_MILLIS[attempt]); + } + } + } + + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new UpstreamResponseException("Pairing was interrupted before the server confirmed it"); + } + } + + private static boolean hasId(StoredPairing pairing) { + return pairing.id() != null && !pairing.id().isBlank(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java new file mode 100644 index 0000000..3c07c59 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java @@ -0,0 +1,392 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Collection; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import tools.jackson.core.JacksonException; +import tools.jackson.core.exc.JacksonIOException; +import tools.jackson.databind.ObjectMapper; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; + +@Service +public class ClientStateService implements ServerTokens { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClientStateService.class); + private static final Duration DEFAULT_PICKUP_INTERVAL = Duration.ofHours(12); + static final Duration MAX_PICKUP_INTERVAL = Duration.ofDays(365); + private static final DateTimeFormatter ASIDE_STAMP = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssSSS").withZone(ZoneOffset.UTC); + + @JsonIgnoreProperties(ignoreUnknown = true) + record ClientState(String activeServer, long pickupIntervalSeconds, Instant lastPickupAt, List knownServers, Map pairings) { + } + + private final Path statePath; + private final ObjectMapper mapper; + private final Set knownServers = new LinkedHashSet<>(); + private final List> activeServerListeners = new CopyOnWriteArrayList<>(); + private final List knownServersListeners = new CopyOnWriteArrayList<>(); + private final List> pairingListeners = new CopyOnWriteArrayList<>(); + private final Map pairings = new LinkedHashMap<>(); + private String activeServer; + private Duration pickupInterval; + private Instant lastPickupAt; + + public ClientStateService(MediaGarrdProperties configuration, ObjectMapper mapper) { + this.statePath = Path.of(configuration.getStateFile()).toAbsolutePath().normalize(); + this.mapper = mapper; + Duration configured = configuration.getPickupInterval(); + if (valid(configured)) { + this.pickupInterval = configured; + } else { + LOGGER.warn("The configured pickup interval {} is outside 1 second to 365 days, using {}", configured, DEFAULT_PICKUP_INTERVAL); + this.pickupInterval = DEFAULT_PICKUP_INTERVAL; + } + load(); + LOGGER.info("Client state: activeServer={}, pickupInterval={}, knownServers={}, pairedServers={}", activeServer, pickupInterval, knownServers, pairings.size()); + } + + public synchronized String getActiveServer() { + return activeServer; + } + + public synchronized String requireActiveServer() { + if (!StringUtils.hasText(activeServer)) { + throw new InvalidRequestException("No active MediaGarrd server selected"); + } + return activeServer; + } + + public synchronized Duration getPickupInterval() { + return pickupInterval; + } + + public synchronized Instant getLastPickupAt() { + return lastPickupAt; + } + + public synchronized boolean recordPickup(String server, Instant at) { + if (!Objects.equals(server, activeServer)) { + return false; + } + persist(activeServer, pickupInterval, knownServers, pairings, at); + lastPickupAt = at; + return true; + } + + public synchronized List getKnownServers() { + return List.copyOf(knownServers); + } + + public void updateKnownServers(List servers) { + String before = null; + String after = null; + List listBefore = null; + List listAfter = null; + try { + synchronized (this) { + before = activeServer; + listBefore = List.copyOf(knownServers); + List found = servers.stream().map(ServerUrls::normalize).toList(); + Set nextKnown = new LinkedHashSet<>(knownServers); + nextKnown.addAll(found); + String nextActive = activeServer; + if (!StringUtils.hasText(nextActive)) { + nextActive = found.stream().findFirst().orElse(null); + } else { + nextKnown.add(nextActive); + } + persist(nextActive, pickupInterval, nextKnown, pairings, lastPickupAt); + knownServers.clear(); + knownServers.addAll(nextKnown); + activeServer = nextActive; + after = activeServer; + listAfter = List.copyOf(knownServers); + LOGGER.info("Known servers updated: {}, active server: {}", knownServers, activeServer); + } + } finally { + if (!Objects.equals(before, after)) { + notifyActiveServerListeners(after); + } + if (listBefore != null && !listBefore.equals(listAfter)) { + notifyKnownServersListeners(); + } + } + } + + public void setActiveServer(String requested) { + String serverUrl = ServerUrls.normalize(requested); + boolean changed = false; + boolean listChanged = false; + try { + synchronized (this) { + changed = !Objects.equals(activeServer, serverUrl); + Set nextKnown = new LinkedHashSet<>(knownServers); + if (StringUtils.hasText(serverUrl)) { + listChanged = nextKnown.add(serverUrl); + } + Instant nextPickup = changed ? null : lastPickupAt; + persist(serverUrl, pickupInterval, nextKnown, pairings, nextPickup); + LOGGER.info("Active server changed: {} -> {}", activeServer, serverUrl); + activeServer = serverUrl; + lastPickupAt = nextPickup; + knownServers.clear(); + knownServers.addAll(nextKnown); + } + } finally { + if (changed) { + notifyActiveServerListeners(serverUrl); + } + if (listChanged) { + notifyKnownServersListeners(); + } + } + } + + public void setActiveServerIfBlank(String requested) { + String serverUrl = ServerUrls.normalize(requested); + boolean changed = false; + boolean listChanged = false; + try { + synchronized (this) { + if (StringUtils.hasText(activeServer) || !StringUtils.hasText(serverUrl)) { + return; + } + Set nextKnown = new LinkedHashSet<>(knownServers); + listChanged = nextKnown.add(serverUrl); + Instant nextPickup = changed ? null : lastPickupAt; + persist(serverUrl, pickupInterval, nextKnown, pairings, nextPickup); + LOGGER.info("Active server changed: {} -> {}", activeServer, serverUrl); + activeServer = serverUrl; + lastPickupAt = nextPickup; + changed = true; + knownServers.clear(); + knownServers.addAll(nextKnown); + } + } finally { + if (changed) { + notifyActiveServerListeners(serverUrl); + } + if (listChanged) { + notifyKnownServersListeners(); + } + } + } + + public synchronized boolean isKnownServer(String serverUrl) { + return knownServers.contains(ServerUrls.normalize(serverUrl)); + } + + public void addActiveServerListener(Consumer listener) { + activeServerListeners.add(listener); + } + + public void addKnownServersListener(Runnable listener) { + knownServersListeners.add(listener); + } + + public void addPairingListener(Consumer listener) { + pairingListeners.add(listener); + } + + @Override + public synchronized Optional tokenFor(String serverUrl) { + return pairingFor(serverUrl).map(StoredPairing::token); + } + + public synchronized Optional pairingFor(String serverUrl) { + return Optional.ofNullable(pairings.get(ServerUrls.normalize(serverUrl))); + } + + public synchronized boolean hasPairing(String serverUrl) { + return pairings.containsKey(ServerUrls.normalize(serverUrl)); + } + + public void storePairing(String serverUrl, StoredPairing pairing) { + String key = ServerUrls.normalize(serverUrl); + synchronized (this) { + Map next = new LinkedHashMap<>(pairings); + next.put(key, pairing); + persist(activeServer, pickupInterval, knownServers, next, lastPickupAt); + LOGGER.info("Paired with {} as {}", key, pairing.name()); + pairings.put(key, pairing); + } + notifyPairingListeners(key); + } + + public boolean forgetPairing(String serverUrl) { + String key = ServerUrls.normalize(serverUrl); + synchronized (this) { + if (!pairings.containsKey(key)) { + return false; + } + Map next = new LinkedHashMap<>(pairings); + next.remove(key); + persist(activeServer, pickupInterval, knownServers, next, lastPickupAt); + pairings.remove(key); + LOGGER.info("Forgot the pairing with {}", key); + } + notifyPairingListeners(key); + return true; + } + + public boolean forgetPairingIf(String serverUrl, String token) { + String key = ServerUrls.normalize(serverUrl); + synchronized (this) { + StoredPairing current = pairings.get(key); + if (current == null || !current.token().equals(token)) { + return false; + } + Map next = new LinkedHashMap<>(pairings); + next.remove(key); + persist(activeServer, pickupInterval, knownServers, next, lastPickupAt); + pairings.remove(key); + LOGGER.info("Forgot the pairing with {}", key); + } + notifyPairingListeners(key); + return true; + } + + private void notifyPairingListeners(String serverUrl) { + for (Consumer listener : pairingListeners) { + try { + listener.accept(serverUrl); + } catch (RuntimeException e) { + LOGGER.warn("Pairing listener failed: {}", e.getMessage()); + } + } + } + + private void notifyKnownServersListeners() { + for (Runnable listener : knownServersListeners) { + try { + listener.run(); + } catch (RuntimeException e) { + LOGGER.warn("Known servers listener failed: {}", e.getMessage()); + } + } + } + + private void notifyActiveServerListeners(String serverUrl) { + for (Consumer listener : activeServerListeners) { + try { + listener.accept(serverUrl); + } catch (RuntimeException e) { + LOGGER.warn("Active server listener failed: {}", e.getMessage()); + } + } + } + + public synchronized Duration setPickupInterval(Duration interval) { + if (interval == null || !interval.isPositive()) { + throw new InvalidRequestException("Pickup interval must be a positive duration"); + } + if (interval.compareTo(MAX_PICKUP_INTERVAL) > 0) { + throw new InvalidRequestException("Pickup interval must be at most 365 days"); + } + persist(activeServer, interval, knownServers, pairings, lastPickupAt); + pickupInterval = interval; + LOGGER.info("Pickup interval updated to {}", interval); + return interval; + } + + private void load() { + if (!Files.exists(statePath)) { + LOGGER.info("No state file at {}, starting fresh", statePath); + return; + } + if (!Files.isReadable(statePath)) { + throw unreadable(null); + } + try { + ClientState state = mapper.readValue(statePath.toFile(), ClientState.class); + if (state == null) { + throw new IllegalStateException("the file is empty"); + } + if (state.knownServers() != null) { + state.knownServers().stream().map(ServerUrls::normalize).forEach(knownServers::add); + } + if (state.pairings() != null) { + state.pairings().forEach((url, pairing) -> { + if (pairing != null && StringUtils.hasText(pairing.token())) { + pairings.put(ServerUrls.normalize(url), pairing); + } + }); + } + activeServer = !StringUtils.hasText(state.activeServer()) ? knownServers.stream().findFirst().orElse(null) : ServerUrls.normalize(state.activeServer()); + Duration saved = Duration.ofSeconds(state.pickupIntervalSeconds()); + if (valid(saved)) { + pickupInterval = saved; + } else if (state.pickupIntervalSeconds() != 0) { + LOGGER.warn("Ignoring the stored pickup interval of {} seconds, it is outside 1 second to 365 days. Using {}", state.pickupIntervalSeconds(), pickupInterval); + } + lastPickupAt = state.lastPickupAt(); + } catch (JacksonIOException e) { + throw unreadable(e); + } catch (JacksonException | IllegalStateException e) { + moveAside(e); + } + } + + private IllegalStateException unreadable(Exception cause) { + String detail = cause == null ? "it is not readable" : cause.getMessage(); + return new IllegalStateException("Could not read the client state file " + statePath + " as " + runUser() + ": " + detail + + ". Fix its owner or permissions so that this user can read it (or run the container with the matching PUID and PGID); the file is left untouched", cause); + } + + private static String runUser() { + try { + return "UID " + Files.getAttribute(Path.of("/proc/self"), "unix:uid"); + } catch (IOException | RuntimeException e) { + return "user " + System.getProperty("user.name"); + } + } + + private void moveAside(Exception cause) { + Path aside = statePath.resolveSibling(statePath.getFileName() + ".corrupt-" + ASIDE_STAMP.format(Instant.now())); + try { + Files.move(statePath, aside, StandardCopyOption.REPLACE_EXISTING); + LOGGER.error("Could not read the client state from {} ({}). The file was moved to {} and the client starts without pairings, so every server needs to be paired again", + statePath, cause.getMessage(), aside); + } catch (IOException e) { + LOGGER.error("Could not read the client state from {} ({}) and could not move it aside ({}). The client starts without pairings and the next change overwrites the file", + statePath, cause.getMessage(), e.getMessage()); + } + } + + private void persist(String active, Duration interval, Collection known, Map paired, Instant lastPickup) { + try { + ClientState state = new ClientState(active == null ? "" : active, interval.toSeconds(), lastPickup, new ArrayList<>(known), new LinkedHashMap<>(paired)); + OwnerOnlyFiles.write(statePath, mapper.writerWithDefaultPrettyPrinter().writeValueAsBytes(state)); + } catch (IOException | JacksonException e) { + throw new IllegalStateException("Failed to save client state to " + statePath, e); + } + } + + private static boolean valid(Duration duration) { + return duration != null && duration.isPositive() && duration.compareTo(MAX_PICKUP_INTERVAL) <= 0; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/CoalescedRefresh.java b/src/main/java/wellatleastitried/mediagarrdclient/service/CoalescedRefresh.java new file mode 100644 index 0000000..e70bceb --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/CoalescedRefresh.java @@ -0,0 +1,63 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.util.concurrent.Executor; +import java.util.concurrent.RejectedExecutionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +final class CoalescedRefresh { + + private static final Logger LOGGER = LoggerFactory.getLogger(CoalescedRefresh.class); + + private final Object lock; + private final Executor executor; + private final Runnable work; + private boolean inFlight; + private boolean again; + + CoalescedRefresh(Object lock, Executor executor, Runnable work) { + this.lock = lock; + this.executor = executor; + this.work = work; + } + + void request() { + synchronized (lock) { + if (inFlight) { + again = true; + return; + } + inFlight = true; + } + try { + executor.execute(this::loop); + } catch (RejectedExecutionException e) { + synchronized (lock) { + inFlight = false; + } + } + } + + boolean busy() { + return inFlight; + } + + private void loop() { + boolean repeat; + do { + try { + work.run(); + } catch (RuntimeException e) { + LOGGER.warn("Dashboard refresh failed: {}", e.getMessage()); + } + synchronized (lock) { + repeat = again; + again = false; + if (!repeat) { + inFlight = false; + } + } + } while (repeat); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationRefusedException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationRefusedException.java new file mode 100644 index 0000000..0c4c905 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationRefusedException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class ConfirmationRefusedException extends UpstreamResponseException { + + public ConfirmationRefusedException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationUnavailableException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationUnavailableException.java new file mode 100644 index 0000000..4d3261b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationUnavailableException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class ConfirmationUnavailableException extends UpstreamResponseException { + + public ConfirmationUnavailableException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ConflictException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ConflictException.java new file mode 100644 index 0000000..86ee3d2 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ConflictException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class ConflictException extends RuntimeException { + + public ConflictException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardEvents.java b/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardEvents.java new file mode 100644 index 0000000..15068d2 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardEvents.java @@ -0,0 +1,31 @@ +package wellatleastitried.mediagarrdclient.service; + +import tools.jackson.core.JacksonException; +import tools.jackson.databind.ObjectMapper; + +final class DashboardEvents { + + private final ClientEventPublisher publisher; + private final ObjectMapper mapper; + + DashboardEvents(ClientEventPublisher publisher, ObjectMapper mapper) { + this.publisher = publisher; + this.mapper = mapper; + } + + void publish(String name, Object payload) { + publisher.publish(name, json(payload)); + } + + void publishRaw(String name, String data) { + publisher.publish(name, data); + } + + String json(Object payload) { + try { + return mapper.writeValueAsString(payload); + } catch (JacksonException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardService.java new file mode 100644 index 0000000..9984534 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardService.java @@ -0,0 +1,355 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import tools.jackson.databind.ObjectMapper; + +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdclient.dto.DashboardState; +import wellatleastitried.mediagarrdclient.dto.HealthSummary; +import wellatleastitried.mediagarrdclient.dto.LinkState; +import wellatleastitried.mediagarrdclient.dto.PairingState; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; + +@Service +public class DashboardService { + + private static final Logger LOGGER = LoggerFactory.getLogger(DashboardService.class); + private static final Duration POLL_INTERVAL = Duration.ofSeconds(7); + private static final Duration CATCH_ALL_INTERVAL = Duration.ofSeconds(60); + + private final ClientStateService stateService; + private final VersionService versionService; + private final UpdateCheckService updateCheckService; + private final ServerApiService serverApiService; + private final Executor executor; + private final Clock clock; + private final Object lock = new Object(); + private final List> recoveryListeners = new CopyOnWriteArrayList<>(); + private final DashboardEvents events; + private final PairingStatus pairingStatus; + private final LinkStateMachine links; + private final BackupWatcher backups; + private final CoalescedRefresh healthRefresh; + private final CoalescedRefresh versionRefresh; + private String activeServer; + private List knownServers = List.of(); + private HealthSummary health; + private Instant healthFetchedAt; + private long epoch; + + @Autowired + public DashboardService( + ClientStateService stateService, + ClientEventPublisher broadcaster, + ServerApiService serverApiService, + VersionService versionService, + UpdateCheckService updateCheckService, + ObjectMapper mapper + ) { + this(stateService, broadcaster, serverApiService, versionService, updateCheckService, mapper, refreshThreads(), Clock.systemUTC()); + } + + DashboardService( + ClientStateService stateService, + ClientEventPublisher broadcaster, + ServerApiService serverApiService, + VersionService versionService, + UpdateCheckService updateCheckService, + ObjectMapper mapper, + Executor executor, + Clock clock + ) { + this.stateService = stateService; + this.serverApiService = serverApiService; + this.versionService = versionService; + this.updateCheckService = updateCheckService; + this.executor = executor; + this.clock = clock; + this.events = new DashboardEvents(broadcaster, mapper); + this.pairingStatus = new PairingStatus(stateService, events); + this.links = new LinkStateMachine(events, clock); + this.backups = new BackupWatcher(serverApiService, events, clock, lock, executor, CATCH_ALL_INTERVAL, () -> activeServer, () -> epoch, () -> links.link() == LinkState.DEGRADED); + this.healthRefresh = new CoalescedRefresh(lock, executor, this::fetchHealth); + this.versionRefresh = new CoalescedRefresh(lock, executor, this::fetchVersion); + } + + private static ExecutorService refreshThreads() { + AtomicInteger counter = new AtomicInteger(); + return Executors.newFixedThreadPool(2, runnable -> Thread.ofPlatform().daemon().name("dashboard-refresh-" + counter.incrementAndGet()).unstarted(runnable)); + } + + @PostConstruct + void start() { + stateService.addKnownServersListener(this::sync); + stateService.addActiveServerListener(ignored -> sync()); + stateService.addPairingListener(this::pairingChanged); + serverApiService.addTokenRejectedListener(this::pairingRejected); + updateCheckService.addStatusListener(ignored -> publishVersions()); + sync(); + } + + @PreDestroy + void shutdown() { + if (executor instanceof ExecutorService service) { + service.shutdownNow(); + } + } + + public DashboardState state() { + synchronized (lock) { + return snapshot(); + } + } + + public Optional subscribe(Function, Optional> registration) { + synchronized (lock) { + return registration.apply(List.of(new ClientEvent("snapshot", events.json(snapshot())))); + } + } + + void sync() { + synchronized (lock) { + String active = ServerUrls.nullIfBlank(stateService.getActiveServer()); + List known = stateService.getKnownServers(); + if (!Objects.equals(active, activeServer)) { + knownServers = known; + reset(active); + } else if (!known.equals(knownServers)) { + knownServers = known; + publishServers(); + } + } + } + + private void reset(String active) { + activeServer = active; + links.reset(active != null); + health = null; + healthFetchedAt = null; + backups.forget(); + pairingStatus.clear(); + epoch++; + versionService.select(active); + events.publish("snapshot", snapshot()); + if (active != null) { + healthRefresh.request(); + } + } + + void pairingChanged(String server) { + synchronized (lock) { + if (Objects.equals(ServerUrls.nullIfBlank(server), activeServer)) { + reset(activeServer); + } + } + } + + void pairingRejected(String server) { + synchronized (lock) { + if (!Objects.equals(server, activeServer)) { + return; + } + pairingStatus.reject(activeServer); + } + } + + void streamUp(String server) { + synchronized (lock) { + if (!Objects.equals(server, activeServer)) { + return; + } + boolean wasDown = links.link() == LinkState.DOWN; + setLink(LinkState.LIVE); + healthRefresh.request(); + if (versionService.invalidate(wasDown)) { + versionRefresh.request(); + } + } + } + + void streamDown(String server) { + synchronized (lock) { + if (!Objects.equals(server, activeServer)) { + return; + } + setLink(LinkState.CONNECTING); + healthRefresh.request(); + } + } + + void runEvent(String server, String name, String data, boolean runningNow) { + synchronized (lock) { + if (!Objects.equals(server, activeServer)) { + return; + } + links.setRunning(runningNow); + events.publishRaw(name, data); + } + } + + void backupsChanged(String server, String data) { + synchronized (lock) { + if (Objects.equals(server, activeServer)) { + events.publishRaw("backups-changed", data); + } + } + } + + void configChanged(String server) { + synchronized (lock) { + if (Objects.equals(server, activeServer)) { + healthRefresh.request(); + } + } + } + + @Scheduled(initialDelayString = "PT8S", fixedDelayString = "PT8S") + void tick() { + synchronized (lock) { + if (activeServer == null) { + return; + } + Duration limit = links.link() == LinkState.LIVE ? CATCH_ALL_INTERVAL : POLL_INTERVAL; + boolean due = healthFetchedAt == null || Duration.between(healthFetchedAt, clock.instant()).compareTo(limit) >= 0; + if (due && !healthRefresh.busy()) { + healthRefresh.request(); + } + if (links.reachable() && !versionRefresh.busy() && versionService.needsRefresh()) { + versionRefresh.request(); + } + if (links.link() == LinkState.DEGRADED) { + backups.requestWhenDue(); + } + } + } + + public void addRecoveryListener(Consumer listener) { + recoveryListeners.add(listener); + } + + private void fetchHealth() { + String server; + long expected; + synchronized (lock) { + server = activeServer; + expected = epoch; + } + if (server == null) { + return; + } + ServerStatusDto status = null; + boolean tokenRejected = false; + try { + status = serverApiService.health(server); + } catch (PairingRequiredException e) { + tokenRejected = true; + status = new ServerStatusDto(true, false, 0, null); + } catch (RuntimeException e) { + LOGGER.debug("{} did not answer the health check: {}", server, e.getMessage()); + } + applyHealth(expected, status, tokenRejected); + } + + private void applyHealth(long expected, ServerStatusDto status, boolean tokenRejected) { + String cleared; + synchronized (lock) { + cleared = applyHealthLocked(expected, status, tokenRejected); + } + if (cleared != null) { + for (Consumer listener : recoveryListeners) { + listener.accept(cleared); + } + } + } + + private String applyHealthLocked(long expected, ServerStatusDto status, boolean tokenRejected) { + String cleared = null; + if (expected != epoch) { + return null; + } + healthFetchedAt = clock.instant(); + if (status != null && pairingStatus.observe(tokenRejected, activeServer)) { + cleared = activeServer; + } + boolean detailed = status != null && pairingStatus.of(activeServer) == PairingState.PAIRED; + if (status == null) { + if (links.link() != LinkState.LIVE) { + setLink(LinkState.DOWN); + if (versionService.markUnreachable()) { + events.publish("versions", versionService.versions()); + } + } + return cleared; + } + if (detailed) { + HealthSummary summary = new HealthSummary(status.backupInterval(), status.backupRetentionCount()); + if (!summary.equals(health)) { + health = summary; + events.publish("config", summary); + } + } + if (links.link() != LinkState.LIVE) { + boolean recovered = links.link() != LinkState.DEGRADED; + boolean wasDown = links.link() == LinkState.DOWN; + setLink(LinkState.DEGRADED); + if (detailed && links.setPolledRunning(status.running())) { + backups.forgetListing(); + } + if (recovered && versionService.invalidate(wasDown)) { + versionRefresh.request(); + } + } + return cleared; + } + + private void fetchVersion() { + if (versionService.refresh()) { + publishVersions(); + } + } + + private void publishVersions() { + synchronized (lock) { + events.publish("versions", versionService.versions()); + } + } + + private void publishServers() { + Map payload = new LinkedHashMap<>(); + payload.put("knownServers", knownServers); + payload.put("activeServer", activeServer); + events.publish("servers", payload); + } + + private void setLink(LinkState next) { + if (links.setLink(next, activeServer) && next != LinkState.DEGRADED) { + backups.forget(); + } + } + + private DashboardState snapshot() { + return new DashboardState(activeServer, knownServers, links.link(), links.running(), health, versionService.versions(), pairingStatus.of(activeServer)); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/DownloadFailedException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/DownloadFailedException.java new file mode 100644 index 0000000..1e5feb4 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/DownloadFailedException.java @@ -0,0 +1,12 @@ +package wellatleastitried.mediagarrdclient.service; + +public class DownloadFailedException extends RuntimeException { + + public DownloadFailedException(String message) { + super(message); + } + + public DownloadFailedException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/InvalidRequestException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/InvalidRequestException.java new file mode 100644 index 0000000..3425a99 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/InvalidRequestException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class InvalidRequestException extends RuntimeException { + + public InvalidRequestException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/LinkStateMachine.java b/src/main/java/wellatleastitried/mediagarrdclient/service/LinkStateMachine.java new file mode 100644 index 0000000..4a71252 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/LinkStateMachine.java @@ -0,0 +1,69 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Clock; +import java.util.LinkedHashMap; +import java.util.Map; + +import wellatleastitried.mediagarrdclient.dto.LinkState; + +final class LinkStateMachine { + + private final DashboardEvents events; + private final Clock clock; + private LinkState link = LinkState.DOWN; + private Boolean running; + + LinkStateMachine(DashboardEvents events, Clock clock) { + this.events = events; + this.clock = clock; + } + + LinkState link() { + return link; + } + + Boolean running() { + return running; + } + + boolean reachable() { + return link == LinkState.LIVE || link == LinkState.DEGRADED; + } + + void reset(boolean serverSelected) { + link = serverSelected ? LinkState.CONNECTING : LinkState.DOWN; + running = null; + } + + void setRunning(boolean now) { + running = now; + } + + boolean setLink(LinkState next, String activeServer) { + if (link == next) { + return false; + } + link = next; + if (!reachable()) { + running = null; + } + Map payload = new LinkedHashMap<>(); + payload.put("server", activeServer == null ? "" : activeServer); + payload.put("state", next); + events.publish("link", payload); + return true; + } + + boolean setPolledRunning(boolean polled) { + if (Boolean.valueOf(polled).equals(running)) { + return false; + } + boolean runFinished = Boolean.TRUE.equals(running) && !polled; + running = polled; + Map payload = new LinkedHashMap<>(); + payload.put("running", polled); + payload.put("at", clock.instant().toString()); + events.publish("state", payload); + return runFinished; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/LoginAttempts.java b/src/main/java/wellatleastitried/mediagarrdclient/service/LoginAttempts.java new file mode 100644 index 0000000..2f1b078 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/LoginAttempts.java @@ -0,0 +1,131 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class LoginAttempts { + + static final int FREE_FAILURES = 3; + static final Duration FIRST_LOCK = Duration.ofSeconds(5); + static final Duration MAX_LOCK = Duration.ofMinutes(5); + static final Duration FORGET_AFTER = Duration.ofHours(1); + static final int MAX_TRACKED = 1000; + static final int BUCKET_CAPACITY = 30; + static final Duration BUCKET_REFILL_PERIOD = Duration.ofMinutes(1); + public static final Duration BUSY_RETRY = Duration.ofSeconds(1); + + private static final class Record { + private int failures; + private Instant lockedUntil = Instant.MIN; + private Instant lastFailure = Instant.MIN; + } + + private final Clock clock; + private final int maxTracked; + private final Map records = new LinkedHashMap<>(); + private final Set inFlight = new HashSet<>(); + private double tokens = BUCKET_CAPACITY; + private Instant lastRefill; + + @Autowired + public LoginAttempts() { + this(Clock.systemUTC(), MAX_TRACKED); + } + + LoginAttempts(Clock clock, int maxTracked) { + this.clock = clock; + this.maxTracked = maxTracked; + this.lastRefill = clock.instant(); + } + + public synchronized Optional tryBegin(String source) { + Optional locked = lockedFor(source); + if (locked.isPresent()) { + return locked; + } + if (!inFlight.add(source)) { + return Optional.of(BUSY_RETRY); + } + refill(); + if (tokens < 1) { + inFlight.remove(source); + double missing = 1 - tokens; + return Optional.of(Duration.ofNanos((long) Math.ceil(missing * BUCKET_REFILL_PERIOD.toNanos() / BUCKET_CAPACITY))); + } + tokens -= 1; + return Optional.empty(); + } + + public synchronized void abandon(String source) { + if (inFlight.remove(source)) { + refund(); + } + } + + private void refill() { + Instant now = clock.instant(); + if (now.isAfter(lastRefill)) { + double elapsed = Duration.between(lastRefill, now).toNanos(); + tokens = Math.min(BUCKET_CAPACITY, tokens + elapsed * BUCKET_CAPACITY / BUCKET_REFILL_PERIOD.toNanos()); + lastRefill = now; + } + } + + private void refund() { + refill(); + tokens = Math.min(BUCKET_CAPACITY, tokens + 1); + } + + public synchronized Optional lockedFor(String source) { + Record record = records.get(source); + if (record == null) { + return Optional.empty(); + } + Instant now = clock.instant(); + if (Duration.between(record.lastFailure, now).compareTo(FORGET_AFTER) >= 0) { + records.remove(source); + return Optional.empty(); + } + if (now.isBefore(record.lockedUntil)) { + return Optional.of(Duration.between(now, record.lockedUntil)); + } + return Optional.empty(); + } + + public synchronized void failed(String source) { + Instant now = clock.instant(); + inFlight.remove(source); + Record record = records.remove(source); + if (record == null || Duration.between(record.lastFailure, now).compareTo(FORGET_AFTER) >= 0) { + record = new Record(); + } + while (records.size() >= maxTracked) { + records.remove(records.keySet().iterator().next()); + } + record.failures++; + record.lastFailure = now; + if (record.failures > FREE_FAILURES) { + long doublings = Math.min(record.failures - FREE_FAILURES - 1, 20); + Duration lock = FIRST_LOCK.multipliedBy(1L << doublings); + record.lockedUntil = now.plus(lock.compareTo(MAX_LOCK) > 0 ? MAX_LOCK : lock); + } + records.put(source, record); + } + + public synchronized void succeeded(String source) { + if (inFlight.remove(source)) { + refund(); + } + records.remove(source); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/NoBackupsException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/NoBackupsException.java new file mode 100644 index 0000000..648fb5c --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/NoBackupsException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class NoBackupsException extends NotFoundException { + + public NoBackupsException() { + super("No backups found on server"); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/NotFoundException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/NotFoundException.java new file mode 100644 index 0000000..1dd1480 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/NotFoundException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class NotFoundException extends RuntimeException { + + public NotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/OwnerOnlyFiles.java b/src/main/java/wellatleastitried/mediagarrdclient/service/OwnerOnlyFiles.java new file mode 100644 index 0000000..65d493d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/OwnerOnlyFiles.java @@ -0,0 +1,50 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.PosixFilePermissions; + +final class OwnerOnlyFiles { + + private OwnerOnlyFiles() { + } + + static void write(Path target, byte[] content) throws IOException { + Files.createDirectories(target.getParent()); + Path temp = target.resolveSibling(target.getFileName() + ".tmp"); + Files.deleteIfExists(temp); + try { + Files.createFile(temp, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); + } catch (UnsupportedOperationException e) { + Files.createFile(temp); + } + try { + Files.write(temp, content); + Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } finally { + Files.deleteIfExists(temp); + } + } + + static void createDirectories(Path directory) throws IOException { + try { + Files.createDirectories(directory, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))); + } catch (UnsupportedOperationException e) { + Files.createDirectories(directory); + } + } + + static OutputStream newOutputStream(Path file) throws IOException { + Files.deleteIfExists(file); + try { + Files.createFile(file, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); + } catch (UnsupportedOperationException e) { + Files.createFile(file); + } + return Files.newOutputStream(file, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/PairingRequiredException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/PairingRequiredException.java new file mode 100644 index 0000000..8a883e5 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/PairingRequiredException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class PairingRequiredException extends RuntimeException { + + public PairingRequiredException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/PairingStatus.java b/src/main/java/wellatleastitried/mediagarrdclient/service/PairingStatus.java new file mode 100644 index 0000000..68230d6 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/PairingStatus.java @@ -0,0 +1,56 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.util.LinkedHashMap; +import java.util.Map; + +import wellatleastitried.mediagarrdclient.dto.PairingState; + +final class PairingStatus { + + private final ClientStateService stateService; + private final DashboardEvents events; + private boolean rejected; + + PairingStatus(ClientStateService stateService, DashboardEvents events) { + this.stateService = stateService; + this.events = events; + } + + PairingState of(String activeServer) { + if (activeServer == null) { + return PairingState.NONE; + } + if (!stateService.hasPairing(activeServer)) { + return PairingState.REQUIRED; + } + return rejected ? PairingState.REJECTED : PairingState.PAIRED; + } + + void clear() { + rejected = false; + } + + void reject(String activeServer) { + if (rejected) { + return; + } + rejected = true; + publish(activeServer); + } + + boolean observe(boolean tokenRejected, String activeServer) { + if (tokenRejected == rejected) { + return false; + } + boolean cleared = rejected && !tokenRejected; + rejected = tokenRejected; + publish(activeServer); + return cleared; + } + + private void publish(String activeServer) { + Map payload = new LinkedHashMap<>(); + payload.put("state", of(activeServer)); + events.publish("pairing", payload); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/PasswordService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/PasswordService.java new file mode 100644 index 0000000..ace68e2 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/PasswordService.java @@ -0,0 +1,158 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.Base64; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import tools.jackson.core.JacksonException; +import tools.jackson.databind.ObjectMapper; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; + +@Service +public class PasswordService { + + private static final Logger LOGGER = LoggerFactory.getLogger(PasswordService.class); + static final int ITERATIONS = 600_000; + static final int MIN_LENGTH = 8; + static final int MAX_LENGTH = 256; + private static final int SALT_BYTES = 16; + private static final int HASH_BITS = 256; + private static final String ALGORITHM = "PBKDF2WithHmacSHA256"; + + record StoredHash(int iterations, String salt, String hash) { + } + + private final Path file; + private final ObjectMapper mapper; + private final int iterations; + private final SecureRandom random = new SecureRandom(); + private final StoredHash environment; + private StoredHash stored; + + @Autowired + public PasswordService(MediaGarrdProperties configuration, ObjectMapper mapper) { + this(configuration, mapper, ITERATIONS); + } + + PasswordService(MediaGarrdProperties configuration, ObjectMapper mapper, int iterations) { + this.file = Path.of(configuration.getStateFile()).toAbsolutePath().normalize().resolveSibling("password.json"); + this.mapper = mapper; + this.iterations = iterations; + String fromEnvironment = configuration.getPassword(); + this.environment = fromEnvironment == null || fromEnvironment.isEmpty() ? null : hash(fromEnvironment, iterations); + if (configuration.isResetPassword()) { + reset(); + } + this.stored = load(); + if (environment != null) { + LOGGER.info("The dashboard password comes from CLIENT_PASSWORD"); + } else if (stored == null) { + LOGGER.warn("No dashboard password is set, the first person to open the dashboard can set it"); + } + } + + public boolean isConfigured() { + return environment != null || currentStored() != null; + } + + public boolean isFromEnvironment() { + return environment != null; + } + + public boolean matches(String password) { + StoredHash expected = environment != null ? environment : currentStored(); + if (expected == null || password == null || password.length() > MAX_LENGTH) { + return false; + } + byte[] actual = derive(password, Base64.getDecoder().decode(expected.salt()), expected.iterations()); + return MessageDigest.isEqual(actual, Base64.getDecoder().decode(expected.hash())); + } + + public synchronized void setInitial(String password) { + if (environment != null) { + throw new ConflictException("The password is set by CLIENT_PASSWORD and cannot be changed here"); + } + if (stored != null) { + throw new ConflictException("A password is already set"); + } + if (password == null || password.length() < MIN_LENGTH) { + throw new InvalidRequestException("The password must be at least " + MIN_LENGTH + " characters"); + } + if (password.length() > MAX_LENGTH) { + throw new InvalidRequestException("The password must be at most " + MAX_LENGTH + " characters"); + } + StoredHash created = hash(password, iterations); + try { + OwnerOnlyFiles.write(file, mapper.writeValueAsBytes(created)); + } catch (IOException | JacksonException e) { + throw new IllegalStateException("Failed to save the dashboard password to " + file, e); + } + stored = created; + LOGGER.info("The dashboard password was set"); + } + + private synchronized StoredHash currentStored() { + return stored; + } + + private void reset() { + try { + if (Files.deleteIfExists(file)) { + LOGGER.warn("CLIENT_RESET_PASSWORD is set: the stored dashboard password was removed, the first person to open the dashboard can set a new one. Remove CLIENT_RESET_PASSWORD now"); + } else { + LOGGER.warn("CLIENT_RESET_PASSWORD is set but no password was stored. Remove it"); + } + } catch (IOException e) { + throw new IllegalStateException("Could not remove the stored dashboard password " + file + ": " + e.getMessage(), e); + } + } + + private StoredHash load() { + if (!Files.exists(file)) { + return null; + } + try { + StoredHash loaded = mapper.readValue(file.toFile(), StoredHash.class); + if (loaded == null || loaded.salt() == null || loaded.hash() == null || loaded.iterations() < 1) { + throw new IOException("the file is incomplete"); + } + Base64.getDecoder().decode(loaded.salt()); + Base64.getDecoder().decode(loaded.hash()); + return loaded; + } catch (IOException | IllegalArgumentException | JacksonException e) { + throw new IllegalStateException("Could not read the stored dashboard password " + file + ": " + e.getMessage() + + ". Fix or delete the file, or start once with CLIENT_RESET_PASSWORD=true", e); + } + } + + private StoredHash hash(String password, int rounds) { + byte[] salt = new byte[SALT_BYTES]; + random.nextBytes(salt); + byte[] derived = derive(password, salt, rounds); + return new StoredHash(rounds, Base64.getEncoder().encodeToString(salt), Base64.getEncoder().encodeToString(derived)); + } + + private static byte[] derive(String password, byte[] salt, int rounds) { + PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, rounds, HASH_BITS); + try { + return SecretKeyFactory.getInstance(ALGORITHM).generateSecret(spec).getEncoded(); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("Password hashing is unavailable: " + e.getMessage(), e); + } finally { + spec.clearPassword(); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/PickupSchedule.java b/src/main/java/wellatleastitried/mediagarrdclient/service/PickupSchedule.java new file mode 100644 index 0000000..d0ebcfb --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/PickupSchedule.java @@ -0,0 +1,49 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.List; + +final class PickupSchedule { + + static final List BACKOFF = List.of(Duration.ofMinutes(1), Duration.ofMinutes(2), Duration.ofMinutes(5), Duration.ofMinutes(10), Duration.ofMinutes(15)); + + private final Clock clock; + private int failures; + private Instant retryAt; + + PickupSchedule(Clock clock) { + this.clock = clock; + } + + synchronized boolean due(Instant lastPickup, Duration interval) { + Instant now = clock.instant(); + if (retryAt != null) { + Instant cap = now.plus(BACKOFF.getLast()); + if (retryAt.isAfter(cap)) { + retryAt = cap; + } + if (now.isBefore(retryAt)) { + return false; + } + } + return !now.isBefore(dueAt(lastPickup, interval)); + } + + Instant dueAt(Instant lastPickup, Duration interval) { + Instant now = clock.instant(); + return lastPickup == null || lastPickup.isAfter(now) ? now : lastPickup.plus(interval); + } + + synchronized Instant failed() { + retryAt = clock.instant().plus(BACKOFF.get(Math.min(failures, BACKOFF.size() - 1))); + failures++; + return retryAt; + } + + synchronized void reset() { + failures = 0; + retryAt = null; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/QuietFiles.java b/src/main/java/wellatleastitried/mediagarrdclient/service/QuietFiles.java new file mode 100644 index 0000000..99511a8 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/QuietFiles.java @@ -0,0 +1,25 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +final class QuietFiles { + + private static final Logger LOGGER = LoggerFactory.getLogger(QuietFiles.class); + + private QuietFiles() { + } + + static boolean delete(Path path) { + try { + return Files.deleteIfExists(path); + } catch (IOException e) { + LOGGER.warn("Could not delete {}: {}", path, e.getMessage()); + return false; + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicy.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicy.java new file mode 100644 index 0000000..fc4f898 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicy.java @@ -0,0 +1,47 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Duration; + +final class ReconnectPolicy { + + enum Outcome { + ROLLOVER, + UNSUPPORTED, + REJECTED, + FAILED + } + + record Decision(Outcome outcome, Duration delay) { + } + + private final Duration initialBackoff; + private final Duration maxBackoff; + private final Duration unsupportedRetry; + private final Duration minLifetime; + private Duration backoff; + + ReconnectPolicy(Duration initialBackoff, Duration maxBackoff, Duration unsupportedRetry, Duration minLifetime) { + this.initialBackoff = initialBackoff; + this.maxBackoff = maxBackoff; + this.unsupportedRetry = unsupportedRetry; + this.minLifetime = minLifetime; + this.backoff = initialBackoff; + } + + Decision next(Outcome outcome, boolean eventsSeen, long lifetimeNanos) { + boolean shortLived = lifetimeNanos < minLifetime.toNanos(); + if (eventsSeen && !shortLived) { + backoff = initialBackoff; + } + Outcome effective = outcome == Outcome.ROLLOVER && shortLived ? Outcome.FAILED : outcome; + Duration delay = effective == Outcome.UNSUPPORTED ? unsupportedRetry : backoff; + if (effective == Outcome.FAILED) { + backoff = min(backoff.multipliedBy(2), maxBackoff); + } + return new Decision(effective, delay); + } + + private static Duration min(Duration a, Duration b) { + return a.compareTo(b) <= 0 ? a : b; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/RequestTimeouts.java b/src/main/java/wellatleastitried/mediagarrdclient/service/RequestTimeouts.java new file mode 100644 index 0000000..5c02ce1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/RequestTimeouts.java @@ -0,0 +1,37 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.net.SocketTimeoutException; +import java.net.http.HttpConnectTimeoutException; +import java.net.http.HttpTimeoutException; +import java.util.concurrent.TimeoutException; + +public final class RequestTimeouts { + + private static final int MAX_DEPTH = 16; + + private RequestTimeouts() { + } + + public static boolean isTimeout(Throwable e) { + int depth = 0; + for (Throwable t = e; t != null && depth++ < MAX_DEPTH; t = t.getCause()) { + if (t instanceof HttpTimeoutException || t instanceof SocketTimeoutException || t instanceof TimeoutException) { + return true; + } + } + return false; + } + + public static boolean isReadTimeout(Throwable e) { + int depth = 0; + for (Throwable t = e; t != null && depth++ < MAX_DEPTH; t = t.getCause()) { + if (t instanceof HttpConnectTimeoutException) { + return false; + } + if (t instanceof HttpTimeoutException || t instanceof SocketTimeoutException || t instanceof TimeoutException) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/SemVer.java b/src/main/java/wellatleastitried/mediagarrdclient/service/SemVer.java new file mode 100644 index 0000000..7ee55da --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/SemVer.java @@ -0,0 +1,78 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public record SemVer(long major, long minor, long patch, List prerelease) implements Comparable { + + private static final String IDENTIFIERS = "[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*"; + private static final Pattern PATTERN = Pattern.compile( + "v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-(" + IDENTIFIERS + "))?(?:\\+" + IDENTIFIERS + ")?"); + + public static Optional parse(String text) { + if (text == null) { + return Optional.empty(); + } + Matcher matcher = PATTERN.matcher(text.strip()); + if (!matcher.matches()) { + return Optional.empty(); + } + try { + List prerelease = matcher.group(4) == null ? List.of() : Arrays.asList(matcher.group(4).split("\\.")); + return Optional.of(new SemVer( + Long.parseLong(matcher.group(1)), + Long.parseLong(matcher.group(2)), + Long.parseLong(matcher.group(3)), + prerelease)); + } catch (NumberFormatException e) { + return Optional.empty(); + } + } + + @Override + public int compareTo(SemVer other) { + int result = Long.compare(major, other.major); + if (result == 0) { + result = Long.compare(minor, other.minor); + } + if (result == 0) { + result = Long.compare(patch, other.patch); + } + return result != 0 ? result : comparePrerelease(prerelease, other.prerelease); + } + + @Override + public String toString() { + String core = major + "." + minor + "." + patch; + return prerelease.isEmpty() ? core : core + "-" + String.join(".", prerelease); + } + + private static int comparePrerelease(List left, List right) { + if (left.isEmpty() || right.isEmpty()) { + return Boolean.compare(left.isEmpty(), right.isEmpty()); + } + for (int i = 0; i < Math.min(left.size(), right.size()); i++) { + int result = compareIdentifier(left.get(i), right.get(i)); + if (result != 0) { + return result; + } + } + return Integer.compare(left.size(), right.size()); + } + + private static int compareIdentifier(String left, String right) { + boolean leftNumeric = left.chars().allMatch(Character::isDigit); + boolean rightNumeric = right.chars().allMatch(Character::isDigit); + if (leftNumeric && rightNumeric) { + return new BigInteger(left).compareTo(new BigInteger(right)); + } + if (leftNumeric != rightNumeric) { + return leftNumeric ? -1 : 1; + } + return left.compareTo(right); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java new file mode 100644 index 0000000..1b623cd --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java @@ -0,0 +1,492 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.time.Duration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Consumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.client.JdkClientHttpRequestFactory; +import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter; +import org.springframework.stereotype.Service; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClient; +import org.springframework.web.client.RestClientResponseException; +import org.springframework.web.util.UriUtils; + +import jakarta.annotation.PreDestroy; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.PairingCodeDto; +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; +import wellatleastitried.mediagarrdclient.dto.WebhookStatusDto; +import wellatleastitried.mediagarrdclient.dto.WebhookTestDto; +import wellatleastitried.mediagarrdclient.protocol.Endpoints; + +@Service +public class ServerApiService { + + @FunctionalInterface + public interface DownloadProgressListener { + void onProgress(long bytesWritten, long totalBytes); + } + + private static final Logger LOGGER = LoggerFactory.getLogger(ServerApiService.class); + private static final JacksonJsonHttpMessageConverter JSON = new JacksonJsonHttpMessageConverter( + JsonMapper.builder().disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)); + private static final String SERVICE_PATH = Endpoints.SERVER_SERVICES.getPath() + "/{name}"; + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(3); + private static final Duration HEALTH_TIMEOUT = Duration.ofSeconds(5); + private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(30); + static final Duration MIN_BACKUP_RUN_TIMEOUT = Duration.ofMinutes(1); + private static final Duration DOWNLOAD_STALL_TIMEOUT = Duration.ofSeconds(60); + private static final int BUFFER_SIZE = 64 * 1024; + + private record ServerError(String error) { + } + + private record PairReply(String token, String id, String name) { + + @Override + public String toString() { + return "PairReply[id=" + id + ", name=" + name + "]"; + } + } + + private record ConfirmReply(boolean healthy, Boolean running, Integer backupRetentionCount, Duration backupInterval) { + } + + private final ServerTokens tokens; + private final HttpClient httpClient; + private final RestClient healthClient; + private final RestClient restClient; + private final RestClient backupRunClient; + private final Duration backupRunTimeout; + private final Duration stallTimeout; + private final ScheduledExecutorService stallWatchdog = Executors.newSingleThreadScheduledExecutor( + runnable -> Thread.ofPlatform().daemon().name("download-stall-watchdog").unstarted(runnable)); + private final List> tokenRejectedListeners = new CopyOnWriteArrayList<>(); + + @Autowired + public ServerApiService(MediaGarrdProperties properties, ClientStateService stateService, ServerTls tls) { + this(checked(properties.getBackupRunTimeout()), stateService, tls); + } + + private static Duration checked(Duration backupRunTimeout) { + if (backupRunTimeout == null || backupRunTimeout.compareTo(MIN_BACKUP_RUN_TIMEOUT) < 0) { + throw new IllegalStateException("mediagarrd.client.backup-run-timeout must be at least " + MIN_BACKUP_RUN_TIMEOUT + ", was " + backupRunTimeout); + } + return backupRunTimeout; + } + + ServerApiService(Duration backupRunTimeout, ServerTokens tokens, ServerTls tls) { + this(backupRunTimeout, DOWNLOAD_STALL_TIMEOUT, tokens, tls); + } + + ServerApiService(Duration backupRunTimeout, Duration stallTimeout, ServerTokens tokens, ServerTls tls) { + this(backupRunTimeout, stallTimeout, HEALTH_TIMEOUT, REQUEST_TIMEOUT, tokens, tls); + } + + ServerApiService(Duration backupRunTimeout, Duration stallTimeout, Duration healthTimeout, Duration requestTimeout, ServerTokens tokens, ServerTls tls) { + this.backupRunTimeout = backupRunTimeout; + this.stallTimeout = stallTimeout; + this.tokens = tokens; + this.httpClient = HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NEVER) + .sslContext(tls.context()) + .build(); + this.healthClient = restClient(healthTimeout); + this.restClient = restClient(requestTimeout); + this.backupRunClient = restClient(backupRunTimeout); + } + + private RestClient restClient(Duration readTimeout) { + JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient); + if (readTimeout != null) { + requestFactory.setReadTimeout(readTimeout); + } + return RestClient.builder().requestFactory(requestFactory).configureMessageConverters(converters -> converters.withJsonConverter(JSON)).build(); + } + + public ServerStatusDto health(String serverUrl) { + RestClient.RequestHeadersSpec request = healthClient.get().uri(serverUrl + Endpoints.SERVER_HEALTH.getPath()); + Optional token = tokens.tokenFor(serverUrl); + if (token.isPresent()) { + request = request.header(HttpHeaders.AUTHORIZATION, "Bearer " + token.get()); + } + ServerStatusDto status = checked(request.retrieve()).body(ServerStatusDto.class); + LOGGER.debug("Server health of {}: {}", serverUrl, status); + return status; + } + + public VersionStatusDto serverVersion(String serverUrl) { + return checked(healthClient.get() + .uri(serverUrl + Endpoints.SERVER_VERSION.getPath()) + .retrieve()) + .body(VersionStatusDto.class); + } + + public List listBackups(String serverUrl) { + List backups = authed(restClient.get().uri(serverUrl + Endpoints.SERVER_BACKUPS.getPath()), serverUrl) + .body(new ParameterizedTypeReference<>() {}); + LOGGER.debug("Received {} backup(s) from {}", backups == null ? 0 : backups.size(), serverUrl); + return backups == null ? List.of() : backups; + } + + public void triggerBackup(String serverUrl) { + LOGGER.info("Triggering backup on {}", serverUrl); + try { + authed(backupRunClient.post().uri(serverUrl + Endpoints.SERVER_BACKUP_RUN.getPath()), serverUrl) + .toBodilessEntity(); + } catch (ResourceAccessException e) { + if (RequestTimeouts.isReadTimeout(e)) { + LOGGER.warn("Backup on {} did not finish within {}", serverUrl, backupRunTimeout); + throw new BackupRunTimeoutException("The backup did not finish within " + backupRunTimeout + + " and is probably still running on the server. The dashboard's live status shows when it finishes.", e); + } + throw e; + } catch (RestClientResponseException e) { + if (e.getStatusCode().is5xxServerError()) { + throw new BackupRunFailedException(failureReason(e), e); + } + throw e; + } + LOGGER.info("Backup finished on {}", serverUrl); + } + + private static String failureReason(RestClientResponseException e) { + try { + ServerError body = e.getResponseBodyAs(ServerError.class); + if (body != null && body.error() != null && !body.error().isBlank()) { + return body.error(); + } + } catch (RuntimeException ignored) { + } + return "MediaGarrd server responded with " + e.getStatusCode().value(); + } + + public ServerStatusDto updateServerSchedule(String serverUrl, Duration interval) { + LOGGER.info("Updating server schedule on {} to {}", serverUrl, interval); + return authed(restClient.put() + .uri(serverUrl + Endpoints.SERVER_SCHEDULE.getPath()) + .contentType(MediaType.APPLICATION_JSON) + .body(Map.of("backupInterval", interval.toString())), serverUrl) + .body(ServerStatusDto.class); + } + + public ServerConfigDto serverConfig(String serverUrl) { + return authed(restClient.get().uri(serverUrl + Endpoints.SERVER_CONFIG.getPath()), serverUrl) + .body(ServerConfigDto.class); + } + + public ServerConfigDto updateServerConfig(String serverUrl, String backupLocation, Integer retentionCount) { + LOGGER.info("Updating server configuration on {}: backupLocation={}, retentionCount={}", serverUrl, backupLocation, retentionCount); + Map body = new HashMap<>(); + body.put("backupLocation", backupLocation); + body.put("retentionCount", retentionCount); + return authed(restClient.put() + .uri(serverUrl + Endpoints.SERVER_CONFIG.getPath()) + .contentType(MediaType.APPLICATION_JSON) + .body(body), serverUrl) + .body(ServerConfigDto.class); + } + + public WebhookStatusDto webhook(String serverUrl) { + return authed(restClient.get().uri(serverUrl + Endpoints.SERVER_WEBHOOK.getPath()), serverUrl) + .body(WebhookStatusDto.class); + } + + public WebhookStatusDto updateWebhook(String serverUrl, String url) { + LOGGER.info("{} the failure webhook on {}", url == null || url.isBlank() ? "Clearing" : "Updating", serverUrl); + Map body = new HashMap<>(); + body.put("url", url); + return authed(restClient.put() + .uri(serverUrl + Endpoints.SERVER_WEBHOOK.getPath()) + .contentType(MediaType.APPLICATION_JSON) + .body(body), serverUrl) + .body(WebhookStatusDto.class); + } + + public WebhookTestDto testWebhook(String serverUrl) { + LOGGER.info("Sending a test message through the failure webhook on {}", serverUrl); + return authed(restClient.post().uri(serverUrl + Endpoints.SERVER_WEBHOOK_TEST.getPath()), serverUrl) + .body(WebhookTestDto.class); + } + + public List listServices(String serverUrl) { + List services = authed(restClient.get().uri(serverUrl + Endpoints.SERVER_SERVICES.getPath()), serverUrl) + .body(new ParameterizedTypeReference<>() {}); + return services == null ? List.of() : services; + } + + public ServiceDto addService(String serverUrl, ServiceDto service) { + LOGGER.info("Adding service {} on {}", service.name(), serverUrl); + return authed(restClient.post() + .uri(serverUrl + Endpoints.SERVER_SERVICES.getPath()) + .contentType(MediaType.APPLICATION_JSON) + .body(service), serverUrl) + .body(ServiceDto.class); + } + + public ServiceDto updateService(String serverUrl, String name, ServiceDto service) { + LOGGER.info("Updating service {} on {}", name, serverUrl); + return authed(restClient.put() + .uri(serverUrl + SERVICE_PATH, name) + .contentType(MediaType.APPLICATION_JSON) + .body(service), serverUrl) + .body(ServiceDto.class); + } + + public void removeService(String serverUrl, String name) { + LOGGER.info("Removing service {} from {}", name, serverUrl); + authed(restClient.delete().uri(serverUrl + SERVICE_PATH, name), serverUrl) + .toBodilessEntity(); + } + + public StoredPairing pair(String serverUrl, String credential, String name) { + LOGGER.info("Pairing with {}", serverUrl); + Map body = new HashMap<>(); + body.put("pin", credential); + if (name != null && !name.isBlank()) { + body.put("name", name); + } + PairReply reply; + try { + reply = redirectsRefused(restClient.post() + .uri(serverUrl + Endpoints.SERVER_PAIR.getPath()) + .contentType(MediaType.APPLICATION_JSON) + .body(body) + .retrieve()) + .body(PairReply.class); + } catch (RestClientResponseException e) { + if (e.getStatusCode().value() == 401) { + throw new InvalidRequestException(serverMessage(e, "The PIN or pairing code was not accepted")); + } + throw e; + } + if (reply == null || reply.token() == null || reply.token().isBlank()) { + throw new UpstreamResponseException("The server did not return a token"); + } + return new StoredPairing(reply.token(), reply.id(), reply.name()); + } + + public void confirmPairing(String serverUrl, String token) { + LOGGER.info("Confirming the pairing with {}", serverUrl); + ConfirmReply reply; + try { + reply = redirectsRefused(healthClient.get() + .uri(serverUrl + Endpoints.SERVER_HEALTH.getPath()) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) + .retrieve()) + .body(ConfirmReply.class); + } catch (RestClientResponseException e) { + if (e.getStatusCode().value() == 401) { + throw new InvalidRequestException("The server did not accept this pairing. Enter the PIN or a pairing code again"); + } + int status = e.getStatusCode().value(); + String message = "The server could not confirm the pairing (status " + status + "). Try again"; + if (status == 502 || status == 503 || status == 504) { + throw new ConfirmationUnavailableException(message); + } + throw new UpstreamResponseException(message); + } + if (reply == null || reply.running() == null || reply.backupRetentionCount() == null) { + throw new ConfirmationRefusedException("The server did not confirm the pairing. Check that it is a current MediaGarrd Server and try again"); + } + } + + public PairingCodeDto createPairingCode(String serverUrl) { + return authed(restClient.post().uri(serverUrl + Endpoints.SERVER_PAIRING_CODES.getPath()), serverUrl) + .body(PairingCodeDto.class); + } + + public void revokeClient(String serverUrl, String clientId) { + LOGGER.info("Unpairing from {}", serverUrl); + authed(restClient.delete().uri(serverUrl + Endpoints.SERVER_CLIENTS.getPath() + "/{id}", clientId), serverUrl) + .toBodilessEntity(); + } + + public void addTokenRejectedListener(Consumer listener) { + tokenRejectedListeners.add(listener); + } + + private RestClient.ResponseSpec authed(RestClient.RequestHeadersSpec request, String serverUrl) { + String token = requireToken(serverUrl); + return checked(request.header(HttpHeaders.AUTHORIZATION, "Bearer " + token).retrieve(), serverUrl); + } + + private RestClient.ResponseSpec checked(RestClient.ResponseSpec response, String serverUrl) { + return redirectsRefused(response).onStatus(status -> status.value() == 401, (request, reply) -> { + throw rejected(serverUrl); + }); + } + + private PairingRequiredException rejected(String serverUrl) { + for (Consumer listener : tokenRejectedListeners) { + try { + listener.accept(serverUrl); + } catch (RuntimeException e) { + LOGGER.warn("Token rejected listener failed: {}", e.getMessage()); + } + } + return rejected(); + } + + private static RestClient.ResponseSpec checked(RestClient.ResponseSpec response) { + return redirectsRefused(response).onStatus(status -> status.value() == 401, (request, reply) -> { + throw rejected(); + }); + } + + private static RestClient.ResponseSpec redirectsRefused(RestClient.ResponseSpec response) { + return response.onStatus(status -> status.is3xxRedirection(), (request, reply) -> { + throw new ServerRedirectException(reply.getStatusCode().value(), reply.getHeaders().getFirst(HttpHeaders.LOCATION)); + }); + } + + private String requireToken(String serverUrl) { + return tokens.tokenFor(serverUrl) + .orElseThrow(() -> new PairingRequiredException("This client is not paired with the server, pair it first")); + } + + private static PairingRequiredException rejected() { + return new PairingRequiredException("The server rejected this client's token, pair it again"); + } + + private static String serverMessage(RestClientResponseException e, String fallback) { + try { + Map body = e.getResponseBodyAs(Map.class); + Object message = body == null ? null : body.get("error"); + return message == null ? fallback : message.toString(); + } catch (RuntimeException ignored) { + return fallback; + } + } + + public Path downloadById(String serverUrl, String backupId, Path destination, DownloadProgressListener progressListener) { + URI uri = URI.create(serverUrl + Endpoints.SERVER_BACKUPS.getPath() + "/" + UriUtils.encodePathSegment(backupId, StandardCharsets.UTF_8) + "/download"); + LOGGER.info("Downloading backup {} from {} to {}", backupId, serverUrl, destination); + Path temp = destination.resolveSibling(destination.getFileName() + ".part"); + String token = requireToken(serverUrl); + try { + HttpRequest request = HttpRequest.newBuilder(uri) + .timeout(REQUEST_TIMEOUT) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) + .GET() + .build(); + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream()); + try (InputStream body = response.body()) { + if (response.statusCode() == 401) { + throw rejected(serverUrl); + } + if (response.statusCode() / 100 == 3) { + throw new ServerRedirectException(response.statusCode(), response.headers().firstValue(HttpHeaders.LOCATION).orElse(null)); + } + if (response.statusCode() / 100 != 2) { + String snippet = new String(body.readNBytes(256), StandardCharsets.UTF_8); + LOGGER.error("Download of backup {} failed with HTTP {}: {}", backupId, response.statusCode(), snippet); + throw new DownloadFailedException("Download of backup " + backupId + " failed with HTTP " + response.statusCode()); + } + OwnerOnlyFiles.createDirectories(destination.getParent()); + long totalBytes = response.headers().firstValueAsLong("Content-Length").orElse(-1L); + copy(body, temp, totalBytes, progressListener); + } + if (!looksLikeZip(temp)) { + throw new DownloadFailedException("Server returned non-zip content for backup " + backupId); + } + Files.move(temp, destination, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + LOGGER.info("Downloaded backup {} to {} ({} bytes)", backupId, destination, Files.size(destination)); + return destination; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new DownloadFailedException("Download of backup " + backupId + " was interrupted", e); + } catch (IOException e) { + LOGGER.error("Failed to save backup {} to {}", backupId, destination, e); + throw new DownloadFailedException("Failed to download backup " + backupId, e); + } finally { + QuietFiles.delete(temp); + } + } + + private void copy(InputStream in, Path target, long totalBytes, DownloadProgressListener progressListener) throws IOException { + AtomicLong lastRead = new AtomicLong(System.nanoTime()); + AtomicBoolean stalled = new AtomicBoolean(); + long checkMillis = Math.max(10, stallTimeout.toMillis() / 4); + ScheduledFuture guard = stallWatchdog.scheduleWithFixedDelay(() -> { + if (System.nanoTime() - lastRead.get() > stallTimeout.toNanos() && stalled.compareAndSet(false, true)) { + try { + in.close(); + } catch (IOException | RuntimeException ignored) { + } + } + }, checkMillis, checkMillis, TimeUnit.MILLISECONDS); + try (OutputStream out = OwnerOnlyFiles.newOutputStream(target)) { + byte[] buffer = new byte[BUFFER_SIZE]; + long written = 0; + int read; + while ((read = in.read(buffer)) != -1) { + lastRead.set(System.nanoTime()); + out.write(buffer, 0, read); + written += read; + if (progressListener != null) { + progressListener.onProgress(written, totalBytes); + } + } + } catch (IOException e) { + if (stalled.get()) { + throw new DownloadFailedException("The server stopped sending data for " + stallTimeout.toSeconds() + " seconds", e); + } + throw e; + } finally { + guard.cancel(false); + } + } + + private static boolean looksLikeZip(Path path) throws IOException { + byte[] header = new byte[4]; + try (InputStream in = Files.newInputStream(path)) { + if (in.readNBytes(header, 0, 4) < 4) { + return false; + } + } + return header[0] == 'P' && header[1] == 'K' + && ((header[2] == 3 && header[3] == 4) || (header[2] == 5 && header[3] == 6) || (header[2] == 7 && header[3] == 8)); + } + + @PreDestroy + void shutdown() { + stallWatchdog.shutdownNow(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java new file mode 100644 index 0000000..1086fe9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java @@ -0,0 +1,425 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.io.InputStream; +import java.net.ConnectException; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.InterfaceAddress; +import java.net.NetworkInterface; +import java.net.Socket; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import tools.jackson.core.JacksonException; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.protocol.Endpoints; + +@Service +public class ServerDiscoveryService { + + private static final Logger LOGGER = LoggerFactory.getLogger(ServerDiscoveryService.class); + + private static final List COMMON_PORTS = List.of(38471, 8080, 80); + private static final List VIRTUAL_INTERFACE_PREFIXES = List.of("docker", "br-", "veth", "virbr", "vmnet", "vboxnet", "cni", "flannel", "cali", "tun", "tap", "wg", "zt", "tailscale"); + private static final int MIN_SCAN_PREFIX_LENGTH = 24; + private static final int FIRST_UNPRIVILEGED_PORT = 1024; + private static final int MAX_PORT = 65535; + private static final int HTTPS_PORT = 443; + private static final int MAX_CONCURRENT_PROBES = 256; + private static final int MAX_PROBE_BODY = 16 * 1024; + private static final Duration CONNECT_TIMEOUT = Duration.ofMillis(500); + private static final Duration HEALTH_TIMEOUT = Duration.ofSeconds(2); + static final Duration PREFERRED_ATTEMPT_DEADLINE = Duration.ofSeconds(3); + private static final int ATTEMPT_PENDING = 0; + private static final int ATTEMPT_RUNNING = 1; + private static final int ATTEMPT_ABANDONED = 2; + private static final Duration SCAN_DEADLINE = Duration.ofSeconds(20); + + enum Probe { OPEN, REFUSED, UNREACHABLE } + + record Candidate(String scheme, String host, InetAddress address, int port) { + Candidate(String host, InetAddress address, int port) { + this("http", host, address, port); + } + + String url() { + String authority = host.contains(":") ? "[" + host + "]" : host; + boolean defaultPort = "https".equals(scheme) && port == HTTPS_PORT; + return scheme + "://" + authority + (defaultPort ? "" : ":" + port); + } + } + + record HostInput(String scheme, String host, Integer port) { + boolean https() { + return "https".equals(scheme); + } + } + + private record ProbeResult(Probe probe, String server) { + } + + private record QuickResult(Optional server, boolean hostAlive) { + } + + private final MediaGarrdProperties configuration; + private final ClientStateService stateService; + private final ObjectMapper mapper; + private final HttpClient httpClient; + private final ExecutorService executor; + private final Duration preferredDeadline; + private final AtomicBoolean preferredAttempt = new AtomicBoolean(); + private final Semaphore probeSlots = new Semaphore(MAX_CONCURRENT_PROBES); + + @Autowired + public ServerDiscoveryService(MediaGarrdProperties configuration, ClientStateService stateService, ObjectMapper mapper, ServerTls tls) { + this(configuration, stateService, mapper, tls, Executors.newVirtualThreadPerTaskExecutor(), PREFERRED_ATTEMPT_DEADLINE); + } + + ServerDiscoveryService(MediaGarrdProperties configuration, ClientStateService stateService, ObjectMapper mapper, ServerTls tls, ExecutorService executor, Duration preferredDeadline) { + this.httpClient = HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT.multipliedBy(2)) + .followRedirects(HttpClient.Redirect.NEVER) + .sslContext(tls.context()) + .build(); + this.executor = executor; + this.preferredDeadline = preferredDeadline; + this.configuration = configuration; + this.stateService = stateService; + this.mapper = mapper; + } + + @Scheduled(initialDelay = 1_000, fixedDelay = 4_000) + public void connectPreferredServer() { + String active = stateService.getActiveServer(); + if ((active != null && !active.isBlank()) || !preferredAttempt.compareAndSet(false, true)) { + return; + } + AtomicInteger phase = new AtomicInteger(ATTEMPT_PENDING); + Future> attempt; + try { + attempt = executor.submit(() -> { + if (!phase.compareAndSet(ATTEMPT_PENDING, ATTEMPT_RUNNING)) { + return Optional.empty(); + } + try { + return resolvePreferredServer(); + } finally { + preferredAttempt.set(false); + } + }); + } catch (RuntimeException e) { + preferredAttempt.set(false); + return; + } + try { + attempt.get(preferredDeadline.toMillis(), TimeUnit.MILLISECONDS).ifPresent(stateService::setActiveServerIfBlank); + } catch (TimeoutException e) { + abandon(attempt, phase); + LOGGER.debug("Resolving the preferred server took longer than {} ms, retrying on the next tick", preferredDeadline.toMillis()); + } catch (ExecutionException e) { + LOGGER.debug("Resolving the preferred server failed: {}", e.getCause() == null ? e.getMessage() : e.getCause().getMessage()); + } catch (InterruptedException e) { + abandon(attempt, phase); + Thread.currentThread().interrupt(); + } + } + + private void abandon(Future attempt, AtomicInteger phase) { + attempt.cancel(true); + if (phase.compareAndSet(ATTEMPT_PENDING, ATTEMPT_ABANDONED)) { + preferredAttempt.set(false); + } + } + + public List discover() { + long start = System.nanoTime(); + Set discovered = new LinkedHashSet<>(); + resolvePreferredServer().ifPresent(discovered::add); + + List hosts = localSubnetHosts(); + List ports = quickPorts(null); + List candidates = hosts.stream() + .flatMap(host -> ports.stream().map(port -> new Candidate(host.getHostAddress(), host, port))) + .toList(); + LOGGER.info("Scanning {} host(s) on ports {} ({} candidates)", hosts.size(), ports, candidates.size()); + discovered.addAll(findServers(candidates, deadline())); + + LOGGER.info("Network discovery found {} server(s) in {} ms: {}", discovered.size(), elapsedMillis(start), discovered); + return List.copyOf(discovered); + } + + public Optional resolvePreferredServer() { + String preferred = configuration.getPreferredServerIp(); + if (preferred == null || preferred.isBlank()) { + return Optional.empty(); + } + HostInput input = parseHost(preferred); + InetAddress address = input == null ? null : resolve(input.host()); + if (address == null) { + return Optional.empty(); + } + if (input.https()) { + return probeSecure(input, input.port()); + } + return quickResolve(input.host(), address, input.port(), deadline()).server(); + } + + private Optional probeSecure(HostInput input, Integer port) { + Candidate candidate = new Candidate("https", input.host(), null, port != null ? port : HTTPS_PORT); + boolean found = isMediaGarrdServer(candidate); + if (found) { + LOGGER.info("Resolved MediaGarrd server at {}", candidate.url()); + } else { + LOGGER.debug("No MediaGarrd server answered at {}", candidate.url()); + } + return found ? Optional.of(candidate.url()) : Optional.empty(); + } + + public Optional resolveServerByIp(String input, Integer port) { + HostInput parsed = parseHost(input); + InetAddress address = parsed == null ? null : resolve(parsed.host()); + if (address == null) { + LOGGER.warn("Cannot resolve a server from '{}'", input); + return Optional.empty(); + } + Integer preferredPort = port != null ? port : parsed.port(); + if (parsed.https()) { + return probeSecure(parsed, preferredPort); + } + long deadline = deadline(); + QuickResult quick = quickResolve(parsed.host(), address, preferredPort, deadline); + if (quick.server().isPresent() || !quick.hostAlive()) { + return quick.server(); + } + + LOGGER.info("No MediaGarrd server on the common ports of {}, scanning ports {}-{}", parsed.host(), FIRST_UNPRIVILEGED_PORT, MAX_PORT); + long start = System.nanoTime(); + Set probed = Set.copyOf(quickPorts(preferredPort)); + List candidates = IntStream.rangeClosed(FIRST_UNPRIVILEGED_PORT, MAX_PORT) + .filter(candidatePort -> !probed.contains(candidatePort)) + .mapToObj(candidatePort -> new Candidate(parsed.host(), address, candidatePort)) + .toList(); + Optional found = findServers(candidates, deadline).stream().findFirst(); + LOGGER.info("Port scan of {} finished in {} ms: {}", parsed.host(), elapsedMillis(start), found.orElse("no server found")); + return found; + } + + private QuickResult quickResolve(String host, InetAddress address, Integer preferredPort, long deadline) { + List> probes = quickPorts(preferredPort).stream() + .map(port -> probeAsync(new Candidate(host, address, port), deadline)) + .toList(); + List results = probes.stream().map(CompletableFuture::join).toList(); + Optional server = results.stream().map(ProbeResult::server).filter(Objects::nonNull).findFirst(); + boolean alive = results.stream().anyMatch(result -> result.probe() != Probe.UNREACHABLE); + server.ifPresentOrElse( + url -> LOGGER.info("Resolved MediaGarrd server at {}", url), + () -> LOGGER.debug("No MediaGarrd server on the common ports of {} (host {})", host, alive ? "reachable" : "unreachable")); + return new QuickResult(server, alive); + } + + private List findServers(List candidates, long deadline) { + List> probes = candidates.stream().map(candidate -> probeAsync(candidate, deadline)).toList(); + return probes.stream() + .map(CompletableFuture::join) + .map(ProbeResult::server) + .filter(Objects::nonNull) + .distinct() + .toList(); + } + + private CompletableFuture probeAsync(Candidate candidate, long deadline) { + return CompletableFuture.supplyAsync(() -> { + Probe probe = connect(candidate, deadline); + return new ProbeResult(probe, probe == Probe.OPEN && isMediaGarrdServer(candidate) ? candidate.url() : null); + }, executor); + } + + private Probe connect(Candidate candidate, long deadline) { + try { + probeSlots.acquire(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return Probe.UNREACHABLE; + } + try (Socket socket = new Socket()) { + if (System.nanoTime() > deadline) { + return Probe.UNREACHABLE; + } + socket.connect(new InetSocketAddress(candidate.address(), candidate.port()), (int) CONNECT_TIMEOUT.toMillis()); + return Probe.OPEN; + } catch (ConnectException e) { + return e.getMessage() != null && e.getMessage().contains("refused") ? Probe.REFUSED : Probe.UNREACHABLE; + } catch (IOException | IllegalArgumentException e) { + return Probe.UNREACHABLE; + } finally { + probeSlots.release(); + } + } + + boolean isMediaGarrdServer(Candidate candidate) { + return isMediaGarrdServer(candidate.url()); + } + + public boolean isMediaGarrdServer(String serverUrl) { + HttpRequest request; + try { + request = HttpRequest.newBuilder(URI.create(serverUrl + Endpoints.SERVER_HEALTH.getPath())) + .timeout(HEALTH_TIMEOUT) + .GET() + .build(); + } catch (IllegalArgumentException e) { + return false; + } + try { + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream()); + try (InputStream body = response.body()) { + if (response.statusCode() != 200) { + return false; + } + byte[] bytes = body.readNBytes(MAX_PROBE_BODY + 1); + if (bytes.length > MAX_PROBE_BODY) { + return false; + } + JsonNode health = mapper.readTree(bytes); + return health.path("healthy").isBoolean() && health.has("backupInterval"); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } catch (IOException | IllegalArgumentException | JacksonException e) { + LOGGER.debug("{} is not a MediaGarrd server: {}", serverUrl, e.getMessage()); + return false; + } + } + + private List quickPorts(Integer preferredPort) { + return Stream.concat(Stream.of(preferredPort, configuration.getServerPort()), COMMON_PORTS.stream()) + .filter(Objects::nonNull) + .distinct() + .toList(); + } + + private List localSubnetHosts() { + Set hosts = new LinkedHashSet<>(); + try { + for (NetworkInterface networkInterface : NetworkInterface.networkInterfaces().toList()) { + if (!networkInterface.isUp() || networkInterface.isLoopback() || networkInterface.isVirtual() || isVirtualBridge(networkInterface)) { + continue; + } + for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { + if (address.getAddress() instanceof Inet4Address ipv4) { + hosts.addAll(subnetHosts(ipv4, address.getNetworkPrefixLength())); + } + } + } + } catch (SocketException e) { + LOGGER.warn("Could not list network interfaces: {}", e.getMessage()); + } + return List.copyOf(hosts); + } + + static List subnetHosts(Inet4Address address, int prefixLength) { + int prefix = Math.min(Math.max(prefixLength, MIN_SCAN_PREFIX_LENGTH), 30); + int ip = toInt(address.getAddress()); + int mask = -1 << (32 - prefix); + int network = ip & mask; + int broadcast = network | ~mask; + List hosts = new ArrayList<>(broadcast - network - 1); + for (int host = network + 1; host < broadcast; host++) { + hosts.add(toAddress(host)); + } + return hosts; + } + + private static boolean isVirtualBridge(NetworkInterface networkInterface) { + String name = networkInterface.getName(); + return VIRTUAL_INTERFACE_PREFIXES.stream().anyMatch(name::startsWith); + } + + static HostInput parseHost(String input) { + if (input == null || input.isBlank()) { + return null; + } + String trimmed = input.trim(); + try { + URI uri = URI.create(trimmed.contains("://") ? trimmed : "http://" + trimmed); + if (uri.getHost() == null || uri.getHost().isBlank()) { + return null; + } + String host = uri.getHost().startsWith("[") ? uri.getHost().substring(1, uri.getHost().length() - 1) : uri.getHost(); + String scheme = "https".equalsIgnoreCase(uri.getScheme()) ? "https" : "http"; + return new HostInput(scheme, host, uri.getPort() > 0 ? uri.getPort() : null); + } catch (IllegalArgumentException e) { + return null; + } + } + + private static int toInt(byte[] bytes) { + return (bytes[0] & 0xFF) << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF); + } + + private static InetAddress toAddress(int ip) { + try { + return InetAddress.getByAddress(new byte[] {(byte) (ip >>> 24), (byte) (ip >>> 16), (byte) (ip >>> 8), (byte) ip}); + } catch (UnknownHostException e) { + throw new IllegalStateException(e); + } + } + + private static InetAddress resolve(String host) { + try { + return InetAddress.getByName(host); + } catch (UnknownHostException e) { + LOGGER.debug("Cannot resolve host {}: {}", host, e.getMessage()); + return null; + } + } + + private static long deadline() { + return System.nanoTime() + SCAN_DEADLINE.toNanos(); + } + + private static long elapsedMillis(long start) { + return Duration.ofNanos(System.nanoTime() - start).toMillis(); + } + + @PreDestroy + void shutdown() { + executor.shutdownNow(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java new file mode 100644 index 0000000..9e53c9f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java @@ -0,0 +1,417 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.LongSupplier; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import tools.jackson.core.JacksonException; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdclient.protocol.Endpoints; + +@Service +public class ServerEventStreamService { + + private static final Logger LOGGER = LoggerFactory.getLogger(ServerEventStreamService.class); + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(3); + private static final Duration HEADER_TIMEOUT = Duration.ofSeconds(10); + private static final Duration WATCHDOG = Duration.ofSeconds(45); + private static final Duration INITIAL_BACKOFF = Duration.ofSeconds(1); + private static final Duration MAX_BACKOFF = Duration.ofSeconds(30); + private static final Duration UNSUPPORTED_RETRY = Duration.ofMinutes(5); + private static final Duration MIN_STREAM_LIFETIME = Duration.ofSeconds(5); + private static final Set FORWARDED_EVENTS = Set.of("state", "run-started", "run-finished", "backups-changed", "config-changed"); + + public record Timing(Duration headerTimeout, Duration watchdog, Duration initialBackoff, Duration maxBackoff, Duration unsupportedRetry, Duration minStreamLifetime) { + } + + private final class Subscription implements Runnable { + + private final String serverUrl; + private final CountDownLatch cancelled = new CountDownLatch(1); + private volatile CompletableFuture> pending; + private volatile InputStream body; + private volatile long lastActivityNanos; + private volatile boolean rejected; + private boolean linkUp; + private boolean eventsSeen; + private Thread thread; + + private Subscription(String serverUrl) { + this.serverUrl = serverUrl; + } + + private boolean isCancelled() { + return cancelled.getCount() == 0; + } + + private void cancel() { + cancelled.countDown(); + CompletableFuture> future = pending; + if (future != null) { + future.cancel(true); + } + closeBody(); + Thread worker = thread; + if (worker != null) { + worker.interrupt(); + } + } + + private void closeBody() { + InputStream stream = body; + if (stream != null) { + try { + stream.close(); + } catch (IOException | RuntimeException e) { + LOGGER.debug("Closing event stream failed: {}", e.getMessage()); + } + } + } + + private boolean pause(Duration delay) { + try { + return cancelled.await(delay.toMillis(), TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + return true; + } + } + + @Override + public void run() { + ReconnectPolicy policy = new ReconnectPolicy(timing.initialBackoff(), timing.maxBackoff(), timing.unsupportedRetry(), timing.minStreamLifetime()); + try { + while (!isCancelled()) { + ReconnectPolicy.Outcome outcome; + long startedNanos = System.nanoTime(); + try { + outcome = connectAndRead(); + } catch (RuntimeException e) { + LOGGER.warn("Event stream of {} failed: {}", serverUrl, e.getMessage()); + outcome = ReconnectPolicy.Outcome.FAILED; + } + if (isCancelled()) { + break; + } + ReconnectPolicy.Decision decision = policy.next(outcome, eventsSeen, System.nanoTime() - startedNanos); + eventsSeen = false; + if (decision.outcome() == ReconnectPolicy.Outcome.ROLLOVER) { + continue; + } + reportLink(false); + if (decision.outcome() == ReconnectPolicy.Outcome.REJECTED) { + rejected = true; + reportRejected(); + break; + } + if (pause(decision.delay())) { + break; + } + } + } finally { + closeBody(); + } + } + + private ReconnectPolicy.Outcome connectAndRead() { + Optional token = stateService.tokenFor(serverUrl); + if (token.isEmpty()) { + return ReconnectPolicy.Outcome.REJECTED; + } + HttpRequest request = HttpRequest.newBuilder(URI.create(serverUrl + Endpoints.SERVER_EVENTS.getPath())) + .timeout(timing.headerTimeout()) + .header("Accept", "text/event-stream") + .header("Authorization", "Bearer " + token.get()) + .GET() + .build(); + CompletableFuture> future = httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()); + pending = future; + if (isCancelled()) { + future.cancel(true); + return ReconnectPolicy.Outcome.FAILED; + } + HttpResponse response; + try { + response = future.get(); + } catch (InterruptedException | CancellationException e) { + return ReconnectPolicy.Outcome.FAILED; + } catch (ExecutionException e) { + LOGGER.debug("Could not open event stream of {}: {}", serverUrl, e.getCause() == null ? e.getMessage() : e.getCause().getMessage()); + return ReconnectPolicy.Outcome.FAILED; + } + body = response.body(); + if (isCancelled()) { + closeBody(); + return ReconnectPolicy.Outcome.FAILED; + } + int status = response.statusCode(); + if (status == 401) { + closeBody(); + LOGGER.warn("{} rejected this client's token, the event stream stays closed until the client is paired again", serverUrl); + return ReconnectPolicy.Outcome.REJECTED; + } + if (status / 100 == 3) { + closeBody(); + LOGGER.warn("Event stream of {} was answered with a redirect to {}, the client does not follow redirects, use that address instead", + serverUrl, response.headers().firstValue("Location").orElse("an unknown location")); + return ReconnectPolicy.Outcome.FAILED; + } + if (status == 404) { + closeBody(); + LOGGER.debug("{} has no event stream, falling back to polling and retrying in {}", serverUrl, timing.unsupportedRetry()); + return ReconnectPolicy.Outcome.UNSUPPORTED; + } + String contentType = response.headers().firstValue("Content-Type").orElse(""); + if (status / 100 != 2 || !contentType.toLowerCase().startsWith("text/event-stream")) { + closeBody(); + LOGGER.debug("Event stream of {} answered {} {}", serverUrl, status, contentType); + return ReconnectPolicy.Outcome.FAILED; + } + return read(response.body()); + } + + private ReconnectPolicy.Outcome read(InputStream input) { + lastActivityNanos = System.nanoTime(); + ScheduledFuture watchdog = scheduler.scheduleWithFixedDelay(this::checkWatchdog, checkPeriodMillis(), checkPeriodMillis(), TimeUnit.MILLISECONDS); + try { + boolean sawEvent = SseReader.read(input, () -> lastActivityNanos = System.nanoTime(), (name, data) -> { + if (!eventsSeen) { + eventsSeen = true; + reportLink(true); + } + dispatch(name, data); + }); + return sawEvent ? ReconnectPolicy.Outcome.ROLLOVER : ReconnectPolicy.Outcome.FAILED; + } catch (IOException | RuntimeException e) { + if (!isCancelled()) { + LOGGER.debug("Event stream of {} ended: {}", serverUrl, e.getMessage()); + } + return ReconnectPolicy.Outcome.FAILED; + } finally { + watchdog.cancel(false); + } + } + + private long checkPeriodMillis() { + return Math.max(10, timing.watchdog().toMillis() / 4); + } + + private void checkWatchdog() { + if (System.nanoTime() - lastActivityNanos > timing.watchdog().toNanos()) { + LOGGER.warn("Event stream of {} went quiet for {}, reconnecting", serverUrl, timing.watchdog()); + closeBody(); + } + } + + private void reportLink(boolean connected) { + if (linkUp == connected || isCancelled()) { + return; + } + linkUp = connected; + synchronized (lock) { + if (current == this) { + if (connected) { + dashboard.streamUp(serverUrl); + } else { + dashboard.streamDown(serverUrl); + } + } + } + } + + private void reportRejected() { + synchronized (lock) { + if (current == this) { + dashboard.pairingRejected(serverUrl); + } + } + } + + private void dispatch(String name, String data) { + if (!FORWARDED_EVENTS.contains(name)) { + return; + } + try { + JsonNode node = mapper.readTree(data); + if (name.equals("state") && !node.has("running")) { + return; + } + String forwarded = mapper.writeValueAsString(node); + boolean running = !name.equals("run-finished") && node.path("running").asBoolean(false); + synchronized (lock) { + if (current != this) { + return; + } + switch (name) { + case "backups-changed" -> dashboard.backupsChanged(serverUrl, forwarded); + case "config-changed" -> dashboard.configChanged(serverUrl); + default -> dashboard.runEvent(serverUrl, name, forwarded, running); + } + } + } catch (JacksonException e) { + LOGGER.debug("Ignoring malformed {} event from {}", name, serverUrl); + } + } + } + + private final ClientStateService stateService; + private final DashboardService dashboard; + private final ObjectMapper mapper; + private final Timing timing; + private final HttpClient httpClient; + private final ThreadFactory threadFactory; + private final ScheduledExecutorService scheduler; + private final LongSupplier nanoTime; + private final Object lock = new Object(); + private Subscription current; + private long lastRecoveryRestartNanos; + private boolean recoveryRestarted; + private ScheduledFuture deferredRecovery; + + @Autowired + public ServerEventStreamService(ClientStateService stateService, DashboardService dashboard, ObjectMapper mapper, ServerTls tls) { + this(stateService, dashboard, mapper, tls, new Timing(HEADER_TIMEOUT, WATCHDOG, INITIAL_BACKOFF, MAX_BACKOFF, UNSUPPORTED_RETRY, MIN_STREAM_LIFETIME)); + } + + ServerEventStreamService(ClientStateService stateService, DashboardService dashboard, ObjectMapper mapper, ServerTls tls, Timing timing) { + this(stateService, dashboard, mapper, tls, timing, System::nanoTime, Executors.newSingleThreadScheduledExecutor( + runnable -> Thread.ofPlatform().daemon().name("server-event-watchdog").unstarted(runnable))); + } + + ServerEventStreamService(ClientStateService stateService, DashboardService dashboard, ObjectMapper mapper, ServerTls tls, Timing timing, + LongSupplier nanoTime, ScheduledExecutorService scheduler) { + this.nanoTime = nanoTime; + this.httpClient = HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NEVER) + .sslContext(tls.context()) + .build(); + this.stateService = stateService; + this.dashboard = dashboard; + this.mapper = mapper; + this.timing = timing; + AtomicInteger counter = new AtomicInteger(); + this.threadFactory = runnable -> Thread.ofPlatform().daemon().name("server-event-stream-" + counter.incrementAndGet()).unstarted(runnable); + this.scheduler = scheduler; + } + + @PostConstruct + void start() { + stateService.addActiveServerListener(ignored -> reconcile()); + stateService.addPairingListener(this::pairingChanged); + dashboard.addRecoveryListener(this::recovered); + reconcile(); + } + + void pairingChanged(String serverUrl) { + synchronized (lock) { + if (current != null && Objects.equals(current.serverUrl, serverUrl)) { + dropCurrent(); + } + reconcile(); + } + } + + void recovered(String serverUrl) { + synchronized (lock) { + if (current != null && Objects.equals(current.serverUrl, serverUrl)) { + recover(current); + } + } + } + + private void recover(Subscription stream) { + synchronized (lock) { + if (current != stream || !stream.rejected) { + return; + } + long now = nanoTime.getAsLong(); + if (recoveryRestarted && now - lastRecoveryRestartNanos < timing.unsupportedRetry().toNanos()) { + long remaining = timing.unsupportedRetry().toNanos() - (now - lastRecoveryRestartNanos); + cancelDeferredRecovery(); + try { + deferredRecovery = scheduler.schedule(() -> recover(stream), remaining, TimeUnit.NANOSECONDS); + } catch (RejectedExecutionException ignored) { + deferredRecovery = null; + } + return; + } + recoveryRestarted = true; + lastRecoveryRestartNanos = now; + dropCurrent(); + reconcile(); + } + } + + private void dropCurrent() { + cancelDeferredRecovery(); + if (current != null) { + current.cancel(); + current = null; + } + } + + private void cancelDeferredRecovery() { + if (deferredRecovery != null) { + deferredRecovery.cancel(false); + deferredRecovery = null; + } + } + + void reconcile() { + synchronized (lock) { + String active = ServerUrls.nullIfBlank(stateService.getActiveServer()); + String target = active != null && stateService.hasPairing(active) ? active : null; + String running = current == null ? null : current.serverUrl; + if (Objects.equals(target, running)) { + return; + } + dropCurrent(); + dashboard.sync(); + if (target != null) { + Subscription stream = new Subscription(target); + stream.thread = threadFactory.newThread(stream); + current = stream; + stream.thread.start(); + LOGGER.debug("Subscribing to live events of {}", target); + } + } + } + + @PreDestroy + void shutdown() { + synchronized (lock) { + dropCurrent(); + } + scheduler.shutdownNow(); + httpClient.shutdownNow(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerRedirectException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerRedirectException.java new file mode 100644 index 0000000..ea94be7 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerRedirectException.java @@ -0,0 +1,17 @@ +package wellatleastitried.mediagarrdclient.service; + +public class ServerRedirectException extends RuntimeException { + + private final String location; + + public ServerRedirectException(int status, String location) { + super("The server answered with a redirect (HTTP " + status + ")" + + (location == null || location.isBlank() ? "" : " to " + location) + + ". The client does not follow redirects, so use that address as the server address instead."); + this.location = location; + } + + public String location() { + return location; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerSelectionService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerSelectionService.java new file mode 100644 index 0000000..905f95d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerSelectionService.java @@ -0,0 +1,39 @@ +package wellatleastitried.mediagarrdclient.service; + +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import wellatleastitried.mediagarrdclient.dto.ServerSelectionRequest; + +@Service +public class ServerSelectionService { + + private final ClientStateService stateService; + private final ServerDiscoveryService discoveryService; + + public ServerSelectionService(ClientStateService stateService, ServerDiscoveryService discoveryService) { + this.stateService = stateService; + this.discoveryService = discoveryService; + } + + public void select(ServerSelectionRequest request) { + if (StringUtils.hasText(request.serverUrl())) { + String serverUrl = ServerUrls.requireHttp(request.serverUrl()); + if (!stateService.isKnownServer(serverUrl) && !discoveryService.isMediaGarrdServer(serverUrl)) { + throw new InvalidRequestException("No MediaGarrd server found at " + serverUrl); + } + stateService.setActiveServer(serverUrl); + return; + } + if (!StringUtils.hasText(request.serverIp())) { + throw new InvalidRequestException("Either serverUrl or serverIp must be provided"); + } + Integer port = request.serverPort(); + if (port != null && (port < 1 || port > 65535)) { + throw new InvalidRequestException("serverPort must be between 1 and 65535"); + } + String resolved = discoveryService.resolveServerByIp(request.serverIp(), port) + .orElseThrow(() -> new InvalidRequestException("No MediaGarrd server found at " + request.serverIp().trim())); + stateService.setActiveServer(resolved); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerTls.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerTls.java new file mode 100644 index 0000000..6b85af7 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerTls.java @@ -0,0 +1,175 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.io.InputStream; +import java.net.Socket; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Collection; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509ExtendedTrustManager; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; + +@Component +public class ServerTls { + + private static final Logger LOGGER = LoggerFactory.getLogger(ServerTls.class); + + private final SSLContext context; + + @Autowired + public ServerTls(MediaGarrdProperties configuration) { + this(configuration.getServerCa()); + } + + ServerTls(String caFile) { + this.context = caFile == null || caFile.isBlank() ? platformDefault() : withExtraAuthorities(Path.of(caFile.trim())); + } + + public static ServerTls defaults() { + return new ServerTls(""); + } + + public SSLContext context() { + return context; + } + + private static SSLContext platformDefault() { + try { + return SSLContext.getDefault(); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("Could not load the default TLS configuration: " + e.getMessage(), e); + } + } + + private static SSLContext withExtraAuthorities(Path caFile) { + try { + X509ExtendedTrustManager extra = extraTrustManager(readCertificates(caFile)); + X509ExtendedTrustManager composite = new CompositeTrustManager(defaultTrustManager(), extra); + SSLContext created = SSLContext.getInstance("TLS"); + created.init(null, new TrustManager[] {composite}, null); + LOGGER.info("Trusting the certificate authorities in {} in addition to the default ones for MediaGarrd servers", caFile); + return created; + } catch (IOException | GeneralSecurityException e) { + throw new IllegalStateException("MEDIAGARRD_SERVER_CA " + caFile + " could not be used: " + e.getMessage(), e); + } + } + + private static Collection readCertificates(Path caFile) throws IOException, CertificateException { + try (InputStream in = Files.newInputStream(caFile)) { + Collection certificates = CertificateFactory.getInstance("X.509").generateCertificates(in); + if (certificates.isEmpty()) { + throw new CertificateException("the file contains no PEM certificates"); + } + return certificates; + } + } + + private static X509ExtendedTrustManager extraTrustManager(Collection certificates) throws IOException, GeneralSecurityException { + KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType()); + store.load(null, null); + int index = 0; + for (Certificate certificate : certificates) { + store.setCertificateEntry("mediagarrd-ca-" + index++, certificate); + } + return extended(store); + } + + private static X509ExtendedTrustManager defaultTrustManager() throws GeneralSecurityException { + return extended(null); + } + + private static X509ExtendedTrustManager extended(KeyStore store) throws GeneralSecurityException { + TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + factory.init(store); + for (TrustManager manager : factory.getTrustManagers()) { + if (manager instanceof X509ExtendedTrustManager extended) { + return extended; + } + } + throw new GeneralSecurityException("No X509ExtendedTrustManager available"); + } + + private static final class CompositeTrustManager extends X509ExtendedTrustManager { + + private final X509ExtendedTrustManager primary; + private final X509ExtendedTrustManager secondary; + + private CompositeTrustManager(X509ExtendedTrustManager primary, X509ExtendedTrustManager secondary) { + this.primary = primary; + this.secondary = secondary; + } + + @FunctionalInterface + private interface Check { + void run(X509ExtendedTrustManager manager) throws CertificateException; + } + + private static void either(X509ExtendedTrustManager first, X509ExtendedTrustManager second, Check check) throws CertificateException { + try { + check.run(first); + } catch (CertificateException e) { + try { + check.run(second); + } catch (CertificateException ignored) { + throw e; + } + } + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { + either(primary, secondary, manager -> manager.checkServerTrusted(chain, authType, socket)); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { + either(primary, secondary, manager -> manager.checkServerTrusted(chain, authType, engine)); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + either(primary, secondary, manager -> manager.checkServerTrusted(chain, authType)); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { + throw new CertificateException("Client certificates are not used"); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { + throw new CertificateException("Client certificates are not used"); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + throw new CertificateException("Client certificates are not used"); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + X509Certificate[] first = primary.getAcceptedIssuers(); + X509Certificate[] second = secondary.getAcceptedIssuers(); + X509Certificate[] all = java.util.Arrays.copyOf(first, first.length + second.length); + System.arraycopy(second, 0, all, first.length, second.length); + return all; + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerTokens.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerTokens.java new file mode 100644 index 0000000..43162f3 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerTokens.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.util.Optional; + +@FunctionalInterface +public interface ServerTokens { + + Optional tokenFor(String serverUrl); +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerUrls.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerUrls.java new file mode 100644 index 0000000..75ecd6d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerUrls.java @@ -0,0 +1,55 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.net.URI; +import java.util.Locale; + +public final class ServerUrls { + + private ServerUrls() { + } + + public static String normalize(String url) { + if (url == null) { + return null; + } + String trimmed = url.trim(); + try { + URI uri = URI.create(trimmed); + String scheme = uri.getScheme() == null ? null : uri.getScheme().toLowerCase(Locale.ROOT); + String host = uri.getHost(); + if (scheme == null || host == null || host.isBlank()) { + return stripTrailingSlashes(trimmed); + } + int port = uri.getPort(); + boolean defaultPort = port < 0 || ("http".equals(scheme) && port == 80) || ("https".equals(scheme) && port == 443); + String path = uri.getRawPath() == null ? "" : stripTrailingSlashes(uri.getRawPath()); + return scheme + "://" + host.toLowerCase(Locale.ROOT) + (defaultPort ? "" : ":" + port) + path; + } catch (IllegalArgumentException e) { + return stripTrailingSlashes(trimmed); + } + } + + public static String requireHttp(String serverUrl) { + String trimmed = stripTrailingSlashes(serverUrl.trim()); + try { + URI uri = URI.create(trimmed); + if (("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) && uri.getHost() != null && !uri.getHost().isBlank()) { + return normalize(trimmed); + } + } catch (IllegalArgumentException ignored) { + } + throw new InvalidRequestException("serverUrl must be an http:// or https:// URL: " + serverUrl); + } + + public static String nullIfBlank(String url) { + return url == null || url.isBlank() ? null : url; + } + + private static String stripTrailingSlashes(String value) { + int end = value.length(); + while (end > 0 && value.charAt(end - 1) == '/') { + end--; + } + return value.substring(0, end); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServiceNames.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServiceNames.java new file mode 100644 index 0000000..9c04a96 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServiceNames.java @@ -0,0 +1,18 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.util.regex.Pattern; + +public final class ServiceNames { + + private static final Pattern VALID = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_.-]{0,63}"); + + private ServiceNames() { + } + + public static String require(String name) { + if (name == null || !VALID.matcher(name).matches()) { + throw new InvalidRequestException("Service names use letters, digits, '.', '_' and '-', start with a letter or digit and have at most 64 characters"); + } + return name; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/SessionService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/SessionService.java new file mode 100644 index 0000000..618ee99 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/SessionService.java @@ -0,0 +1,188 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +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.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; + + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class SessionService { + + private static final Logger LOGGER = LoggerFactory.getLogger(SessionService.class); + static final Duration IDLE_TIMEOUT = Duration.ofHours(12); + static final Duration ABSOLUTE_TIMEOUT = Duration.ofDays(7); + static final int MAX_SESSIONS = 100; + private static final int TOKEN_BYTES = 32; + + private static final class Session { + private final Instant createdAt; + private Instant lastSeen; + + private Session(Instant now) { + this.createdAt = now; + this.lastSeen = now; + } + } + + private final Clock clock; + private final Duration idleTimeout; + private final Duration absoluteTimeout; + private final int maxSessions; + private final SecureRandom random = new SecureRandom(); + private final Map sessions = new LinkedHashMap<>(); + private final List> endedListeners = new CopyOnWriteArrayList<>(); + + @Autowired + public SessionService() { + this(Clock.systemUTC(), IDLE_TIMEOUT, ABSOLUTE_TIMEOUT, MAX_SESSIONS); + } + + SessionService(Clock clock, Duration idleTimeout, Duration absoluteTimeout, int maxSessions) { + this.clock = clock; + this.idleTimeout = idleTimeout; + this.absoluteTimeout = absoluteTimeout; + this.maxSessions = maxSessions; + } + + public synchronized String create() { + Instant now = clock.instant(); + evictExpired(now); + while (sessions.size() >= maxSessions) { + Iterator oldest = sessions.keySet().iterator(); + oldest.next(); + oldest.remove(); + } + byte[] bytes = new byte[TOKEN_BYTES]; + random.nextBytes(bytes); + String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + sessions.put(key(token), new Session(now)); + return token; + } + + public boolean validate(String token) { + if (token == null || token.isEmpty() || token.length() > 128) { + return false; + } + String key = keyOf(token); + boolean valid; + boolean expired = false; + synchronized (this) { + Instant now = clock.instant(); + Session session = sessions.get(key); + if (session == null) { + return false; + } + expired = expired(session, now); + if (expired) { + sessions.remove(key); + } else { + session.lastSeen = now; + } + valid = !expired; + } + if (expired) { + notifyEnded(List.of(key)); + } + return valid; + } + + public boolean isActive(String key) { + if (key == null) { + return false; + } + boolean expired = false; + boolean active; + synchronized (this) { + Session session = sessions.get(key); + if (session == null) { + return false; + } + expired = expired(session, clock.instant()); + if (expired) { + sessions.remove(key); + } + active = !expired; + } + if (expired) { + notifyEnded(List.of(key)); + } + return active; + } + + public void invalidate(String token) { + if (token == null) { + return; + } + String key = keyOf(token); + boolean removed; + synchronized (this) { + removed = sessions.remove(key) != null; + } + if (removed) { + notifyEnded(List.of(key)); + } + } + + public void clear() { + List keys; + synchronized (this) { + keys = List.copyOf(sessions.keySet()); + sessions.clear(); + } + notifyEnded(keys); + } + + public void addEndedListener(Consumer listener) { + endedListeners.add(listener); + } + + private void notifyEnded(List keys) { + for (String key : keys) { + for (Consumer listener : endedListeners) { + try { + listener.accept(key); + } catch (RuntimeException e) { + LOGGER.warn("Session listener failed: {}", e.getMessage()); + } + } + } + } + + private void evictExpired(Instant now) { + sessions.values().removeIf(session -> expired(session, now)); + } + + private boolean expired(Session session, Instant now) { + return Duration.between(session.lastSeen, now).compareTo(idleTimeout) >= 0 + || Duration.between(session.createdAt, now).compareTo(absoluteTimeout) >= 0; + } + + public static String keyOf(String token) { + return token == null ? null : key(token); + } + + private static String key(String token) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/SseReader.java b/src/main/java/wellatleastitried/mediagarrdclient/service/SseReader.java new file mode 100644 index 0000000..ed406e2 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/SseReader.java @@ -0,0 +1,88 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +final class SseReader { + + static final int MAX_LINE_CHARS = 1024 * 1024; + static final int MAX_EVENT_CHARS = 1024 * 1024; + + interface Handler { + + void onEvent(String name, String data); + } + + private SseReader() { + } + + static boolean read(InputStream input, Runnable onActivity, Handler handler) throws IOException { + return read(input, onActivity, handler, MAX_LINE_CHARS, MAX_EVENT_CHARS); + } + + static boolean read(InputStream input, Runnable onActivity, Handler handler, int maxLine, int maxEvent) throws IOException { + boolean dispatched = false; + String name = null; + StringBuilder data = new StringBuilder(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) { + String line; + while ((line = readLine(reader, maxLine)) != null) { + onActivity.run(); + if (line.isEmpty()) { + if (data.length() > 0) { + dispatched = true; + handler.onEvent(name == null ? "message" : name, data.toString()); + } + name = null; + data.setLength(0); + } else if (line.startsWith(":")) { + continue; + } else { + int colon = line.indexOf(':'); + String field = colon < 0 ? line : line.substring(0, colon); + String value = colon < 0 ? "" : line.substring(colon + 1); + if (value.startsWith(" ")) { + value = value.substring(1); + } + if (field.equals("event")) { + name = value; + } else if (field.equals("data")) { + if (data.length() > 0) { + data.append('\n'); + } + if (data.length() + value.length() > maxEvent) { + throw new IOException("The event is larger than " + maxEvent + " characters"); + } + data.append(value); + } + } + } + } + return dispatched; + } + + private static String readLine(BufferedReader reader, int maxLine) throws IOException { + StringBuilder line = new StringBuilder(); + int c; + while ((c = reader.read()) != -1) { + if (c == '\n') { + return line.toString(); + } + if (c == '\r') { + reader.mark(1); + if (reader.read() != '\n') { + reader.reset(); + } + return line.toString(); + } + if (line.length() >= maxLine) { + throw new IOException("The line is longer than " + maxLine + " characters"); + } + line.append((char) c); + } + return line.length() == 0 ? null : line.toString(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/StoredPairing.java b/src/main/java/wellatleastitried/mediagarrdclient/service/StoredPairing.java new file mode 100644 index 0000000..abff567 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/StoredPairing.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdclient.service; + +public record StoredPairing(String token, String id, String name) { + + @Override + public String toString() { + return "StoredPairing[id=" + id + ", name=" + name + "]"; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/UpdateCheckService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/UpdateCheckService.java new file mode 100644 index 0000000..bbe670b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/UpdateCheckService.java @@ -0,0 +1,193 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.info.BuildProperties; +import org.springframework.context.annotation.Lazy; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.JdkClientHttpRequestFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClient; +import org.springframework.web.client.RestClientResponseException; +import org.springframework.web.util.UriUtils; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; + +@Service +@Lazy(false) +public class UpdateCheckService { + + @JsonIgnoreProperties(ignoreUnknown = true) + record GithubRelease(@JsonProperty("tag_name") String tagName, @JsonProperty("html_url") String htmlUrl) { + } + + private static final Logger LOGGER = LoggerFactory.getLogger(UpdateCheckService.class); + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(3); + private static final Duration READ_TIMEOUT = Duration.ofSeconds(5); + private static final String GITHUB_PAGES = "https://github.com/"; + static final Duration MIN_INTERVAL = Duration.ofHours(1); + + private final String currentVersion; + private final Optional current; + private final String repository; + private final Clock clock; + private final RestClient client; + private final AtomicReference status; + private final List> listeners = new CopyOnWriteArrayList<>(); + + @Autowired + public UpdateCheckService(MediaGarrdProperties properties, ObjectProvider buildProperties) { + this(properties, versionOf(buildProperties), Clock.systemUTC()); + } + + UpdateCheckService(MediaGarrdProperties properties, String currentVersion, Clock clock) { + Duration interval = properties.getUpdateCheckInterval(); + if (interval == null || interval.compareTo(MIN_INTERVAL) < 0) { + throw new IllegalStateException("mediagarrd.client.update-check-interval must be at least " + MIN_INTERVAL + ", was " + interval); + } + this.currentVersion = currentVersion; + this.current = SemVer.parse(currentVersion); + this.repository = properties.getUpdateRepository(); + this.clock = clock; + HttpClient httpClient = HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NORMAL) + .build(); + JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient); + requestFactory.setReadTimeout(READ_TIMEOUT); + this.client = RestClient.builder() + .baseUrl(properties.getGithubApiBaseUrl().replaceAll("/+$", "")) + .requestFactory(requestFactory) + .defaultHeader(HttpHeaders.USER_AGENT, "MediaGarrd-Client/" + (currentVersion == null ? "unknown" : currentVersion)) + .defaultHeader(HttpHeaders.ACCEPT, "application/vnd.github+json") + .build(); + this.status = new AtomicReference<>(result(CheckState.NOT_CHECKED, null, null, null)); + } + + public VersionStatusDto status() { + return status.get(); + } + + public void addStatusListener(Consumer listener) { + listeners.add(listener); + } + + @Scheduled(initialDelayString = "PT5S", fixedDelayString = "${mediagarrd.client.update-check-interval:PT24H}") + public void check() { + VersionStatusDto previous = status.get(); + VersionStatusDto next = fetch(); + status.set(next); + logChange(previous, next); + if (changed(previous, next)) { + for (Consumer listener : listeners) { + try { + listener.accept(next); + } catch (RuntimeException e) { + LOGGER.warn("Update status listener failed: {}", e.getMessage()); + } + } + } + } + + private VersionStatusDto fetch() { + if (current.isEmpty()) { + return result(CheckState.ERROR, null, null, "Current version is unknown"); + } + try { + GithubRelease release = client.get() + .uri("/repos/" + repository + "/releases/latest") + .retrieve() + .body(GithubRelease.class); + return fromRelease(release); + } catch (RestClientResponseException e) { + return fromHttpFailure(e); + } catch (ResourceAccessException e) { + LOGGER.debug("GitHub is unreachable", e); + return result(CheckState.ERROR, null, null, "GitHub is unreachable"); + } catch (RuntimeException e) { + LOGGER.debug("Unexpected update check failure", e); + return result(CheckState.ERROR, null, null, "Unexpected response from GitHub"); + } + } + + private VersionStatusDto fromRelease(GithubRelease release) { + Optional latest = release == null ? Optional.empty() : SemVer.parse(release.tagName()); + if (latest.isEmpty()) { + return result(CheckState.ERROR, null, null, "Latest release has an unrecognized version tag"); + } + String url = release.htmlUrl() != null && release.htmlUrl().startsWith(GITHUB_PAGES) + ? release.htmlUrl() + : GITHUB_PAGES + repository + "/releases/tag/" + UriUtils.encodePathSegment(release.tagName().strip(), StandardCharsets.UTF_8); + return result(CheckState.OK, latest.get(), url, null); + } + + private VersionStatusDto fromHttpFailure(RestClientResponseException e) { + int code = e.getStatusCode().value(); + if (code == HttpStatus.NOT_FOUND.value()) { + return result(CheckState.NO_RELEASES, null, null, null); + } + boolean limitExhausted = code == HttpStatus.FORBIDDEN.value() + && e.getResponseHeaders() != null + && "0".equals(e.getResponseHeaders().getFirst("X-RateLimit-Remaining")); + if (code == HttpStatus.TOO_MANY_REQUESTS.value() || limitExhausted) { + return result(CheckState.ERROR, null, null, "GitHub rate limit reached"); + } + return result(CheckState.ERROR, null, null, "GitHub returned HTTP " + code); + } + + private VersionStatusDto result(CheckState state, SemVer latest, String url, String message) { + boolean update = state == CheckState.OK && latest != null && current.isPresent() && latest.compareTo(current.get()) > 0; + return new VersionStatusDto( + currentVersion, + latest == null ? null : latest.toString(), + url, + update, + state, + state == CheckState.NOT_CHECKED ? null : clock.instant(), + message); + } + + private static boolean changed(VersionStatusDto previous, VersionStatusDto next) { + return previous.checkState() != next.checkState() + || !Objects.equals(previous.latestVersion(), next.latestVersion()) + || !Objects.equals(previous.message(), next.message()); + } + + private static void logChange(VersionStatusDto previous, VersionStatusDto next) { + if (!changed(previous, next)) { + LOGGER.debug("Update check unchanged: {}", next.checkState()); + } else if (next.checkState() == CheckState.ERROR) { + LOGGER.warn("Update check failed: {}", next.message()); + } else if (next.updateAvailable()) { + LOGGER.info("Update available: {} -> {} ({})", next.currentVersion(), next.latestVersion(), next.releaseUrl()); + } else { + LOGGER.info("Update check: {}, running {}", next.checkState(), next.currentVersion()); + } + } + + private static String versionOf(ObjectProvider buildProperties) { + BuildProperties build = buildProperties.getIfAvailable(); + return build == null ? null : build.getVersion(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/UpstreamResponseException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/UpstreamResponseException.java new file mode 100644 index 0000000..fc6807f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/UpstreamResponseException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class UpstreamResponseException extends RuntimeException { + + public UpstreamResponseException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/VersionService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/VersionService.java new file mode 100644 index 0000000..262a1d1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/VersionService.java @@ -0,0 +1,151 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; +import wellatleastitried.mediagarrdclient.dto.VersionsDto; + +@Service +public class VersionService { + + private static final Logger LOGGER = LoggerFactory.getLogger(VersionService.class); + static final Duration REFRESH_INTERVAL = Duration.ofHours(1); + static final Duration RETRY_INTERVAL = Duration.ofMinutes(10); + static final Duration PENDING_RETRY_INTERVAL = Duration.ofSeconds(30); + static final Duration ERROR_RETRY_INTERVAL = Duration.ofMinutes(5); + static final Duration RECENT_SUCCESS = Duration.ofMinutes(5); + private static final VersionStatusDto SERVER_UNAVAILABLE = + new VersionStatusDto(null, null, null, false, CheckState.UNAVAILABLE, null, "Server version is unavailable"); + private static final VersionStatusDto SERVER_PENDING = + new VersionStatusDto(null, null, null, false, CheckState.NOT_CHECKED, null, null); + + private final UpdateCheckService updateCheckService; + private final ServerApiService serverApiService; + private final Clock clock; + private final Object lock = new Object(); + private String selected; + private VersionStatusDto server; + private Instant fetchedAt; + private Instant lastSuccess; + + @Autowired + public VersionService(UpdateCheckService updateCheckService, ServerApiService serverApiService) { + this(updateCheckService, serverApiService, Clock.systemUTC()); + } + + VersionService(UpdateCheckService updateCheckService, ServerApiService serverApiService, Clock clock) { + this.updateCheckService = updateCheckService; + this.serverApiService = serverApiService; + this.clock = clock; + } + + public VersionsDto versions() { + synchronized (lock) { + return new VersionsDto(updateCheckService.status(), server); + } + } + + public boolean select(String serverUrl) { + String next = serverUrl == null || serverUrl.isBlank() ? null : serverUrl; + synchronized (lock) { + if (Objects.equals(next, selected)) { + return false; + } + selected = next; + server = next == null ? null : SERVER_PENDING; + fetchedAt = null; + lastSuccess = null; + return true; + } + } + + public boolean invalidate(boolean force) { + synchronized (lock) { + if (selected == null) { + return false; + } + if (!force && lastSuccess != null && Duration.between(lastSuccess, clock.instant()).compareTo(RECENT_SUCCESS) < 0) { + return false; + } + fetchedAt = null; + return true; + } + } + + public boolean markUnreachable() { + synchronized (lock) { + if (selected == null || server != SERVER_PENDING) { + return false; + } + server = SERVER_UNAVAILABLE; + fetchedAt = clock.instant(); + return true; + } + } + + public boolean needsRefresh() { + synchronized (lock) { + if (selected == null) { + return false; + } + if (fetchedAt == null) { + return true; + } + return Duration.between(fetchedAt, clock.instant()).compareTo(limitFor(server)) >= 0; + } + } + + private static Duration limitFor(VersionStatusDto status) { + if (status == null) { + return REFRESH_INTERVAL; + } + return switch (status.checkState()) { + case NOT_CHECKED -> PENDING_RETRY_INTERVAL; + case ERROR -> ERROR_RETRY_INTERVAL; + case UNAVAILABLE -> RETRY_INTERVAL; + default -> REFRESH_INTERVAL; + }; + } + + public boolean refresh() { + String url; + synchronized (lock) { + url = selected; + } + if (url == null) { + return false; + } + VersionStatusDto fetched = fetch(url); + synchronized (lock) { + if (!url.equals(selected)) { + return false; + } + boolean changed = !fetched.equals(server); + server = fetched; + fetchedAt = clock.instant(); + if (fetched.checkState() == CheckState.OK || fetched.checkState() == CheckState.NO_RELEASES) { + lastSuccess = fetchedAt; + } + return changed; + } + } + + private VersionStatusDto fetch(String serverUrl) { + try { + VersionStatusDto version = serverApiService.serverVersion(serverUrl); + return version == null ? SERVER_UNAVAILABLE : version; + } catch (RuntimeException e) { + LOGGER.debug("Version of {} is unavailable: {}", serverUrl, e.getMessage()); + return SERVER_UNAVAILABLE; + } + } +} diff --git a/src/main/java/wellatleastitried/mediaguardclient/Configuration.java b/src/main/java/wellatleastitried/mediaguardclient/Configuration.java deleted file mode 100644 index 15cbedd..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/Configuration.java +++ /dev/null @@ -1,55 +0,0 @@ -package wellatleastitried.mediagarrdclient; - -import java.time.Duration; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -@ConfigurationProperties(prefix = "mediagarrd.client") -public class Configuration { - - private String stateFile = "./data/client/state.json"; - private String downloadDirectory = "./data/client/downloads"; - private Duration pickupInterval = Duration.ofHours(12); - private int serverPort = 8080; - private String preferredServerIp = ""; - - public String getStateFile() { - return stateFile; - } - - public void setStateFile(String stateFile) { - this.stateFile = stateFile; - } - - public String getDownloadDirectory() { - return downloadDirectory; - } - - public void setDownloadDirectory(String downloadDirectory) { - this.downloadDirectory = downloadDirectory; - } - - public Duration getPickupInterval() { - return pickupInterval; - } - - public void setPickupInterval(Duration pickupInterval) { - this.pickupInterval = pickupInterval; - } - - public int getServerPort() { - return serverPort; - } - - public void setServerPort(int serverPort) { - this.serverPort = serverPort; - } - - public String getPreferredServerIp() { - return preferredServerIp; - } - - public void setPreferredServerIp(String preferredServerIp) { - this.preferredServerIp = preferredServerIp; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/WebMvcConfig.java b/src/main/java/wellatleastitried/mediaguardclient/WebMvcConfig.java deleted file mode 100644 index dabc55a..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/WebMvcConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrdclient; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class WebMvcConfig implements WebMvcConfigurer { - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry - .addResourceHandler("/css/**", "/js/**", "/images/**", "/*.png", "/*.ico", "/*.svg") - .addResourceLocations("classpath:/static/") - .setCachePeriod(0); - - registry - .addResourceHandler("/index.html") - .addResourceLocations("classpath:/static/index.html") - .setCachePeriod(0); - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/api/ClientController.java b/src/main/java/wellatleastitried/mediaguardclient/api/ClientController.java deleted file mode 100644 index e3fe178..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/api/ClientController.java +++ /dev/null @@ -1,216 +0,0 @@ -package wellatleastitried.mediagarrdclient.api; - -import java.time.Duration; -import java.util.List; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ResponseStatusException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import wellatleastitried.mediagarrdclient.Configuration; -import wellatleastitried.mediagarrdclient.dto.BackupDto; -import wellatleastitried.mediagarrdclient.dto.ClientStatusDto; -import wellatleastitried.mediagarrdclient.dto.ConnectionStatusDto; -import wellatleastitried.mediagarrdclient.dto.IntervalUpdateRequest; -import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; -import wellatleastitried.mediagarrdclient.dto.PickupStartDto; -import wellatleastitried.mediagarrdclient.dto.ServerSelectionRequest; -import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; -import wellatleastitried.mediagarrdclient.service.BackupPickupService; -import wellatleastitried.mediagarrdclient.service.ClientStateService; -import wellatleastitried.mediagarrdclient.service.ServerApiService; -import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; - -@RestController -@RequestMapping("/api/client") -public class ClientController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ClientController.class); - - private final Configuration configuration; - private final ClientStateService stateService; - private final ServerDiscoveryService discoveryService; - private final ServerApiService serverApiService; - private final BackupPickupService pickupService; - - public ClientController( - Configuration configuration, - ClientStateService stateService, - ServerDiscoveryService discoveryService, - ServerApiService serverApiService, - BackupPickupService pickupService - ) { - this.configuration = configuration; - this.stateService = stateService; - this.discoveryService = discoveryService; - this.serverApiService = serverApiService; - this.pickupService = pickupService; - } - - @GetMapping("/status") - public ClientStatusDto status() { - LOGGER.info("GET /api/client/status"); - String activeServer = stateService.getActiveServer(); - if (activeServer == null || activeServer.isBlank()) { - String preferredIp = configuration.getPreferredServerIp(); - if (preferredIp != null && !preferredIp.isBlank()) { - LOGGER.info("No active server, probing preferred IP: {}", preferredIp); - discoveryService.resolveServerByIp(preferredIp).ifPresent(url -> { - LOGGER.info("Auto-resolved server from preferred IP: {}", url); - stateService.setActiveServer(url); - }); - } - } - - ClientStatusDto dto = new ClientStatusDto( - stateService.getActiveServer(), - stateService.getPickupInterval(), - stateService.getKnownServers() - ); - LOGGER.info("Status: activeServer={}, pickupInterval={}, knownServers={}", dto.activeServer(), dto.pickupInterval(), dto.knownServers()); - return dto; - } - - @PostMapping("/discover") - public ClientStatusDto discover() { - LOGGER.info("POST /api/client/discover, starting network scan"); - List discovered = discoveryService.discover(); - LOGGER.info("Discovery complete, found {} server(s): {}", discovered.size(), discovered); - stateService.updateKnownServers(discovered); - return status(); - } - - @GetMapping("/server-health") - public ConnectionStatusDto serverHealth() { - LOGGER.info("GET /api/client/server-health"); - String activeServer = stateService.getActiveServer(); - if (activeServer == null || activeServer.isBlank()) { - LOGGER.warn("server-health: no active server configured"); - return new ConnectionStatusDto("", false); - } - - try { - ServerStatusDto serverStatus = serverApiService.health(activeServer); - LOGGER.info("server-health: {} is reachable", activeServer); - return new ConnectionStatusDto(activeServer, true, serverStatus); - } catch (RuntimeException ex) { - LOGGER.warn("server-health: {} is unreachable: {}", activeServer, ex.getMessage()); - return new ConnectionStatusDto(activeServer, false); - } - } - - @PutMapping("/server") - public ClientStatusDto setServer(@RequestBody ServerSelectionRequest request) { - LOGGER.info("PUT /api/client/server, request={}", request); - if (request == null) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Request body is required"); - } - - String requestedUrl = request.serverUrl(); - if (requestedUrl != null && !requestedUrl.isBlank()) { - LOGGER.info("Setting active server by URL: {}", requestedUrl.trim()); - stateService.setActiveServer(requestedUrl.trim()); - return status(); - } - - String serverIp = request.serverIp(); - if (serverIp == null || serverIp.isBlank()) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Either serverUrl or serverIp must be provided"); - } - - Integer serverPort = request.serverPort(); - if (serverPort != null && (serverPort < 1 || serverPort > 65535)) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "serverPort must be between 1 and 65535"); - } - - LOGGER.info("Resolving server by IP={}, port={}", serverIp, serverPort); - String resolved = discoveryService.resolveServerByIp(serverIp, serverPort) - .orElseThrow(() -> { - LOGGER.warn("Unable to resolve server at IP={}, port={}", serverIp, serverPort); - return new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unable to resolve MediaGarrd server on provided IP"); - }); - LOGGER.info("Resolved server: {}", resolved); - stateService.setActiveServer(resolved); - return status(); - } - - @GetMapping("/backups") - public List listBackups() { - String activeServer = requireActiveServer(); - LOGGER.info("GET /api/client/backups, forwarding to {}", activeServer); - List backups = serverApiService.listBackups(activeServer); - LOGGER.info("Received {} backup(s) from server", backups.size()); - return backups; - } - - @PostMapping("/backups/run") - public void runBackup() { - String activeServer = requireActiveServer(); - LOGGER.info("POST /api/client/backups/run, triggering backup on {}", activeServer); - serverApiService.triggerBackup(activeServer); - LOGGER.info("Backup triggered successfully on {}", activeServer); - } - - @PostMapping("/pickup") - public PickupStartDto pickupNow() { - LOGGER.info("POST /api/client/pickup, manual pickup requested"); - PickupStartDto task = pickupService.startPickupLatestTask(); - LOGGER.info("Pickup task started: {}", task.taskId()); - return task; - } - - @PostMapping("/pickup/{id}") - public PickupStartDto pickupById(@PathVariable String id) { - LOGGER.info("POST /api/client/pickup/{}, manual pickup by id requested", id); - PickupStartDto task = pickupService.startPickupByIdTask(id); - LOGGER.info("Pickup-by-id task started: {} for {}", task.taskId(), id); - return task; - } - - @GetMapping("/pickup/progress/{taskId}") - public PickupProgressDto pickupProgress(@PathVariable String taskId) { - LOGGER.debug("GET /api/client/pickup/progress/{}", taskId); - PickupProgressDto progress = pickupService.pickupProgress(taskId); - LOGGER.debug("Pickup progress returned: taskId={}, status={}, bytesWritten={}, totalBytes={}", - taskId, progress.status(), progress.bytesWritten(), progress.totalBytes()); - return progress; - } - - @PutMapping("/pickup-interval") - public ClientStatusDto updatePickupInterval(@RequestBody IntervalUpdateRequest request) { - LOGGER.info("PUT /api/client/pickup-interval, requested={}", request.interval()); - Duration duration = pickupService.updatePickupInterval(request.interval()); - LOGGER.info("Pickup interval updated to: {}", duration); - return new ClientStatusDto( - stateService.getActiveServer(), - duration, - stateService.getKnownServers() - ); - } - - @PutMapping("/server-schedule") - public void updateServerSchedule(@RequestBody IntervalUpdateRequest request) { - String activeServer = requireActiveServer(); - LOGGER.info("PUT /api/client/server-schedule, interval={}, target={}", request.interval(), activeServer); - serverApiService.updateServerSchedule(activeServer, request.interval()); - LOGGER.info("Server schedule updated on {}", activeServer); - } - - private String requireActiveServer() { - String activeServer = stateService.getActiveServer(); - if (activeServer == null || activeServer.isBlank()) { - LOGGER.warn("Request rejected: no active server configured"); - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No active MediaGarrd server selected"); - } - return activeServer; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/api/Endpoints.java b/src/main/java/wellatleastitried/mediaguardclient/api/Endpoints.java deleted file mode 100644 index f4ca708..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/api/Endpoints.java +++ /dev/null @@ -1,28 +0,0 @@ -package wellatleastitried.mediagarrdclient.api; - -public enum Endpoints { - - CLIENT_STATUS("/api/client/status"), - CLIENT_DISCOVER("/api/client/discover"), - CLIENT_SERVER("/api/client/server"), - CLIENT_BACKUPS("/api/client/backups"), - CLIENT_BACKUP_RUN("/api/client/backups/run"), - CLIENT_PICKUP("/api/client/pickup"), - CLIENT_PICKUP_INTERVAL("/api/client/pickup-interval"), - CLIENT_SERVER_SCHEDULE("/api/client/server-schedule"), - SERVER_HEALTH("/api/v1/health"), - SERVER_BACKUPS("/api/v1/backups"), - SERVER_BACKUP_RUN("/api/v1/backups/run"), - SERVER_BACKUP_LATEST_DOWNLOAD("/api/v1/backups/latest/download"), - SERVER_SCHEDULE("/api/v1/schedule"); - - private final String path; - - Endpoints(String path) { - this.path = path; - } - - public String getPath() { - return path; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/api/WebController.java b/src/main/java/wellatleastitried/mediaguardclient/api/WebController.java deleted file mode 100644 index 9a2eb36..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/api/WebController.java +++ /dev/null @@ -1,13 +0,0 @@ -package wellatleastitried.mediagarrdclient.api; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; - -@Controller -public class WebController { - - @GetMapping("/") - public String index() { - return "forward:/index.html"; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/ConnectionStatusDto.java b/src/main/java/wellatleastitried/mediaguardclient/dto/ConnectionStatusDto.java deleted file mode 100644 index 6c6631d..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/dto/ConnectionStatusDto.java +++ /dev/null @@ -1,7 +0,0 @@ -package wellatleastitried.mediagarrdclient.dto; - -public record ConnectionStatusDto(String activeServer, boolean connected, ServerStatusDto serverStatus) { - public ConnectionStatusDto(String activeServer, boolean connected) { - this(activeServer, connected, null); - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/service/BackupPickupService.java b/src/main/java/wellatleastitried/mediaguardclient/service/BackupPickupService.java deleted file mode 100644 index 09dd29f..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/service/BackupPickupService.java +++ /dev/null @@ -1,330 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import jakarta.annotation.PreDestroy; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import wellatleastitried.mediagarrdclient.Configuration; -import wellatleastitried.mediagarrdclient.dto.BackupDto; -import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; -import wellatleastitried.mediagarrdclient.dto.PickupStartDto; - -@Service -public class BackupPickupService { - - private static final Logger LOGGER = LoggerFactory.getLogger(BackupPickupService.class); - private static final String AUTO_DOWNLOAD_SUFFIX = "-AD"; - - private final Configuration configuration; - private final ClientStateService clientStateService; - private final ServerApiService serverApiService; - private final ExecutorService pickupExecutor = Executors.newCachedThreadPool(); - private final Map pickupTasks = new ConcurrentHashMap<>(); - private Instant nextPickup; - - private enum PickupStatus { - QUEUED, - RUNNING, - COMPLETED, - FAILED - } - - private static final class PickupTaskState { - private final String taskId; - private final String backupId; - private final String fileName; - private volatile PickupStatus status; - private volatile long bytesWritten; - private volatile long totalBytes; - private volatile Path savedPath; - private volatile String error; - - private PickupTaskState(String taskId, String backupId, String fileName, long totalBytes) { - this.taskId = taskId; - this.backupId = backupId; - this.fileName = fileName; - this.totalBytes = totalBytes; - this.status = PickupStatus.QUEUED; - this.bytesWritten = 0L; - } - } - - public BackupPickupService( - Configuration configuration, - ClientStateService clientStateService, - ServerApiService serverApiService - ) { - this.configuration = configuration; - this.clientStateService = clientStateService; - this.serverApiService = serverApiService; - this.nextPickup = Instant.now().plus(clientStateService.getPickupInterval()); - } - - @Scheduled(fixedDelay = 60000) - public void scheduledPickup() { - Instant now = Instant.now(); - if (now.isBefore(nextPickup)) { - return; - } - LOGGER.info("Scheduled pickup triggered, next scheduled check was {}", nextPickup); - try { - Path result = pickupLatestAuto(); - LOGGER.info("Scheduled pickup complete: {}", result); - } catch (RuntimeException ex) { - LOGGER.warn("Scheduled pickup failed", ex); - } - nextPickup = now.plus(clientStateService.getPickupInterval()); - LOGGER.info("Next pickup scheduled at: {}", nextPickup); - } - - public Path pickupLatest() { - String activeServer = requireActiveServer(); - List backups = serverApiService.listBackups(activeServer); - BackupDto latest = latestRequired(backups); - - return pickupManual(activeServer, latest); - } - - public PickupStartDto startPickupLatestTask() { - String activeServer = requireActiveServer(); - List backups = serverApiService.listBackups(activeServer); - BackupDto latest = latestRequired(backups); - return startPickupTask(activeServer, latest); - } - - public PickupStartDto startPickupByIdTask(String backupId) { - String activeServer = requireActiveServer(); - return startPickupTask(activeServer, requireBackup(activeServer, backupId)); - } - - public PickupProgressDto pickupProgress(String taskId) { - PickupTaskState state = pickupTasks.get(taskId); - if (state == null) { - LOGGER.warn("Pickup task not found: {}", taskId); - throw new IllegalStateException("Pickup task not found: " + taskId); - } - - LOGGER.debug("Pickup task status requested: taskId={}, status={}, bytesWritten={}, totalBytes={}", - taskId, state.status, state.bytesWritten, state.totalBytes); - - return new PickupProgressDto( - state.taskId, - state.status.name(), - state.backupId, - state.fileName, - state.bytesWritten, - state.totalBytes, - state.savedPath == null ? null : state.savedPath.toString(), - state.error - ); - } - - public Path pickupById(String backupId) { - String activeServer = requireActiveServer(); - return pickupManual(activeServer, requireBackup(activeServer, backupId)); - } - - private Path pickupLatestAuto() { - String activeServer = requireActiveServer(); - List backups = serverApiService.listBackups(activeServer); - BackupDto latest = latestRequired(backups); - - Path downloadsDir = downloadsDirectory(); - Path existingPath = findExistingCopy(downloadsDir, latest); - if (existingPath != null) { - LOGGER.info("Auto pickup skipped for {} because local copy already exists at {}", latest.id(), existingPath); - return existingPath; - } - - Path latestAutoPath = downloadsDir.resolve(withAutoSuffix(latest.fileName())); - LOGGER.info("Auto pickup downloading {} to {}", latest.fileName(), latestAutoPath); - Path downloaded = serverApiService.downloadById(activeServer, latest.id(), latestAutoPath); - deletePlainDuplicate(downloadsDir, latest); - - if (backups.size() > 1) { - BackupDto secondMostRecent = backups.get(1); - Path secondAutoPath = downloadsDir.resolve(withAutoSuffix(secondMostRecent.fileName())); - if (Files.exists(secondAutoPath)) { - try { - Files.deleteIfExists(secondAutoPath); - LOGGER.info("Auto pickup removed second-most-recent auto-downloaded backup {}", secondAutoPath.getFileName()); - } catch (IOException e) { - LOGGER.warn("Auto pickup failed to remove second-most-recent auto-downloaded backup {}", secondAutoPath, e); - } - } - } - - return downloaded; - } - - private Path findExistingCopy(Path downloadsDir, BackupDto backup) { - Path autoPath = downloadsDir.resolve(withAutoSuffix(backup.fileName())); - if (matchesBackup(autoPath, backup)) { - return autoPath; - } - - Path plainPath = downloadsDir.resolve(backup.fileName()); - if (matchesBackup(plainPath, backup)) { - return plainPath; - } - - return null; - } - - private boolean matchesBackup(Path candidate, BackupDto backup) { - if (!Files.exists(candidate)) { - return false; - } - - try { - return Files.size(candidate) == backup.sizeBytes(); - } catch (IOException e) { - LOGGER.warn("Failed to inspect local file {} for backup {}", candidate, backup.id(), e); - return false; - } - } - - private void deletePlainDuplicate(Path downloadsDir, BackupDto backup) { - Path plainPath = downloadsDir.resolve(backup.fileName()); - Path autoPath = downloadsDir.resolve(withAutoSuffix(backup.fileName())); - - if (!Files.exists(autoPath) || !Files.exists(plainPath)) { - return; - } - - try { - long autoSize = Files.size(autoPath); - long plainSize = Files.size(plainPath); - if (autoSize == backup.sizeBytes() && plainSize == backup.sizeBytes()) { - Files.deleteIfExists(plainPath); - LOGGER.info("Auto pickup removed plain duplicate for backup {} and kept {}", backup.id(), autoPath.getFileName()); - } - } catch (IOException e) { - LOGGER.warn("Auto pickup failed to reconcile plain duplicate for backup {}", backup.id(), e); - } - } - - private PickupStartDto startPickupTask(String activeServer, BackupDto backup) { - Path downloadsDir = downloadsDirectory(); - Path existingPath = findExistingCopy(downloadsDir, backup); - if (existingPath != null) { - String taskId = UUID.randomUUID().toString(); - PickupTaskState existingState = new PickupTaskState(taskId, backup.id(), backup.fileName(), backup.sizeBytes()); - existingState.status = PickupStatus.COMPLETED; - existingState.bytesWritten = backup.sizeBytes(); - existingState.savedPath = existingPath; - pickupTasks.put(taskId, existingState); - LOGGER.info("Pickup task {} reused existing local copy for backup {} at {}", taskId, backup.id(), existingPath); - return new PickupStartDto(taskId, backup.id(), backup.fileName(), backup.sizeBytes()); - } - - Path destination = downloadsDir.resolve(backup.fileName()); - String taskId = UUID.randomUUID().toString(); - PickupTaskState state = new PickupTaskState(taskId, backup.id(), backup.fileName(), backup.sizeBytes()); - pickupTasks.put(taskId, state); - - LOGGER.info("Starting pickup task {} for backup {} to {}", taskId, backup.id(), destination); - pickupExecutor.submit(() -> runPickupTask(activeServer, backup, destination, state)); - - return new PickupStartDto(taskId, backup.id(), backup.fileName(), backup.sizeBytes()); - } - - private Path pickupManual(String activeServer, BackupDto backup) { - Path downloadsDir = downloadsDirectory(); - Path existingPath = findExistingCopy(downloadsDir, backup); - if (existingPath != null) { - LOGGER.info("Manual pickup: skipping {} because client already has a local copy at {}", backup.id(), existingPath); - return existingPath; - } - - Path destination = downloadsDir.resolve(backup.fileName()); - LOGGER.info("Manual pickup: downloading {} to {}", backup.fileName(), destination); - return serverApiService.downloadById(activeServer, backup.id(), destination); - } - - private void runPickupTask(String activeServer, BackupDto backup, Path destination, PickupTaskState state) { - state.status = PickupStatus.RUNNING; - try { - Path downloaded = serverApiService.downloadById( - activeServer, - backup.id(), - destination, - (bytesWritten, totalBytes) -> { - state.bytesWritten = bytesWritten; - if (totalBytes > 0) { - state.totalBytes = totalBytes; - } - } - ); - state.savedPath = downloaded; - if (state.totalBytes <= 0) { - state.totalBytes = state.bytesWritten; - } - state.status = PickupStatus.COMPLETED; - LOGGER.info("Pickup task {} completed: {}", state.taskId, downloaded); - } catch (RuntimeException ex) { - state.status = PickupStatus.FAILED; - state.error = ex.getMessage(); - LOGGER.warn("Pickup task {} failed for backup {}", state.taskId, backup.id(), ex); - } - } - - private BackupDto requireBackup(String activeServer, String backupId) { - return serverApiService.listBackups(activeServer).stream() - .filter(backup -> backup.id().equals(backupId)) - .findFirst() - .orElseThrow(() -> new IllegalStateException("Backup not found: " + backupId)); - } - - private String requireActiveServer() { - String activeServer = clientStateService.getActiveServer(); - if (activeServer == null || activeServer.isBlank()) { - LOGGER.error("Pickup requested but no active server is configured"); - throw new IllegalStateException("No active server selected"); - } - return activeServer; - } - - private BackupDto latestRequired(List backups) { - if (backups == null || backups.isEmpty()) { - throw new IllegalStateException("No backups found on server"); - } - return backups.get(0); - } - - private Path downloadsDirectory() { - return Path.of(configuration.getDownloadDirectory()).toAbsolutePath().normalize(); - } - - private String withAutoSuffix(String fileName) { - if (fileName.endsWith(".zip")) { - return fileName.substring(0, fileName.length() - 4) + AUTO_DOWNLOAD_SUFFIX + ".zip"; - } - return fileName + AUTO_DOWNLOAD_SUFFIX; - } - - @PreDestroy - public void shutdownPickupExecutor() { - pickupExecutor.shutdownNow(); - } - - public Duration updatePickupInterval(Duration interval) { - Duration updated = clientStateService.setPickupInterval(interval); - nextPickup = Instant.now().plus(updated); - return updated; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/service/ClientStateService.java b/src/main/java/wellatleastitried/mediaguardclient/service/ClientStateService.java deleted file mode 100644 index 9919fcd..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/service/ClientStateService.java +++ /dev/null @@ -1,133 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.ObjectMapper; - -import wellatleastitried.mediagarrdclient.Configuration; - -@Service -public class ClientStateService { - - private static final Logger LOGGER = LoggerFactory.getLogger(ClientStateService.class); - - @JsonIgnoreProperties(ignoreUnknown = true) - private static class ClientState { - public String activeServer = ""; - public long pickupIntervalSeconds = 43_200; - public List knownServers = new ArrayList<>(); - } - - private final Configuration configuration; - private final ObjectMapper mapper; - private final List knownServers = new ArrayList<>(); - private String activeServer; - private Duration pickupInterval; - - public ClientStateService(Configuration configuration, ObjectMapper mapper) { - this.configuration = configuration; - this.mapper = mapper; - this.pickupInterval = safe(configuration.getPickupInterval()); - this.activeServer = null; - load(); - LOGGER.info("ClientStateService initialized: activeServer={}, pickupInterval={}, knownServers={}", - activeServer, pickupInterval, knownServers); - } - - public synchronized String getActiveServer() { - return activeServer; - } - - public synchronized Duration getPickupInterval() { - return pickupInterval; - } - - public synchronized List getKnownServers() { - return List.copyOf(knownServers); - } - - public synchronized void updateKnownServers(List servers) { - knownServers.clear(); - knownServers.addAll(servers.stream().distinct().toList()); - if ((activeServer == null || activeServer.isBlank()) && !knownServers.isEmpty()) { - activeServer = knownServers.getFirst(); - LOGGER.info("Auto-selected first known server: {}", activeServer); - } - LOGGER.info("Known servers updated: {}", knownServers); - save(); - } - - public synchronized void setActiveServer(String serverUrl) { - LOGGER.info("Active server changed: {} -> {}", activeServer, serverUrl); - this.activeServer = serverUrl; - if (serverUrl != null && !serverUrl.isBlank() && !knownServers.contains(serverUrl)) { - knownServers.add(serverUrl); - } - save(); - } - - public synchronized Duration setPickupInterval(Duration interval) { - this.pickupInterval = safe(interval); - LOGGER.info("Pickup interval updated to: {}", this.pickupInterval); - save(); - return this.pickupInterval; - } - - private void load() { - Path path = statePath(); - if (!Files.exists(path)) { - LOGGER.info("No state file found at {}, starting fresh", path); - return; - } - try { - ClientState state = mapper.readValue(path.toFile(), ClientState.class); - activeServer = state.activeServer; - pickupInterval = Duration.ofSeconds(state.pickupIntervalSeconds); - knownServers.clear(); - knownServers.addAll(state.knownServers); - if ((activeServer == null || activeServer.isBlank()) && !knownServers.isEmpty()) { - activeServer = knownServers.getFirst(); - } - LOGGER.info("State loaded from {}: activeServer={}, pickupInterval={}, knownServers={}", - path, activeServer, pickupInterval, knownServers); - } catch (IOException e) { - LOGGER.warn("Failed to load state from {}, starting with defaults", path, e); - } - } - - private void save() { - Path path = statePath(); - try { - Files.createDirectories(path.getParent()); - ClientState state = new ClientState(); - state.activeServer = activeServer == null ? "" : activeServer; - state.pickupIntervalSeconds = pickupInterval.toSeconds(); - state.knownServers = List.copyOf(knownServers); - mapper.writerWithDefaultPrettyPrinter().writeValue(path.toFile(), state); - LOGGER.debug("Client state persisted to {}", path); - } catch (IOException e) { - throw new IllegalStateException("Failed to persist client state", e); - } - } - - private Path statePath() { - return Path.of(configuration.getStateFile()).toAbsolutePath().normalize(); - } - - private Duration safe(Duration duration) { - if (duration == null || duration.isNegative() || duration.isZero()) { - return Duration.ofHours(12); - } - return duration; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/service/ServerApiService.java b/src/main/java/wellatleastitried/mediaguardclient/service/ServerApiService.java deleted file mode 100644 index 1c4628d..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/service/ServerApiService.java +++ /dev/null @@ -1,192 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.time.Duration; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.MediaType; -import org.springframework.http.client.JdkClientHttpRequestFactory; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestClient; - -import wellatleastitried.mediagarrdclient.api.Endpoints; -import wellatleastitried.mediagarrdclient.dto.BackupDto; -import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; - -@Service -public class ServerApiService { - - @FunctionalInterface - public interface DownloadProgressListener { - void onProgress(long bytesWritten, long totalBytes); - } - - private static final Logger LOGGER = LoggerFactory.getLogger(ServerApiService.class); - - private final HttpClient httpClient = HttpClient.newBuilder() - .followRedirects(HttpClient.Redirect.ALWAYS) - .build(); - - private final RestClient restClient = RestClient.builder() - .requestFactory(new JdkClientHttpRequestFactory(httpClient)) - .build(); - - public ServerStatusDto health(String serverUrl) { - LOGGER.info("Probing server health: {}", serverUrl); - ServerStatusDto dto = restClient.get() - .uri(serverUrl + Endpoints.SERVER_HEALTH.getPath()) - .retrieve() - .body(ServerStatusDto.class); - LOGGER.info("Server health OK: {}, running={}, interval={}", serverUrl, - dto != null ? dto.running() : "?", dto != null ? dto.backupInterval() : "?"); - return dto; - } - - public List listBackups(String serverUrl) { - LOGGER.info("Fetching backup list from: {}", serverUrl); - List response = restClient.get() - .uri(serverUrl + Endpoints.SERVER_BACKUPS.getPath()) - .retrieve() - .body(new ParameterizedTypeReference<>() {}); - List result = response == null ? List.of() : response; - LOGGER.info("Received {} backup(s) from {}", result.size(), serverUrl); - return result; - } - - public void triggerBackup(String serverUrl) { - LOGGER.info("Triggering backup on: {}", serverUrl); - restClient.post() - .uri(serverUrl + Endpoints.SERVER_BACKUP_RUN.getPath()) - .retrieve() - .toBodilessEntity(); - LOGGER.info("Backup trigger acknowledged by: {}", serverUrl); - } - - public void updateServerSchedule(String serverUrl, Duration interval) { - LOGGER.info("Updating server schedule on {} to interval={}", serverUrl, interval); - restClient.put() - .uri(serverUrl + Endpoints.SERVER_SCHEDULE.getPath()) - .contentType(MediaType.APPLICATION_JSON) - .body("{\"backupInterval\":\"" + interval + "\"}") - .retrieve() - .toBodilessEntity(); - LOGGER.info("Server schedule update acknowledged by: {}", serverUrl); - } - - public Path downloadLatest(String serverUrl, Path destinationPath) { - return downloadLatest(serverUrl, destinationPath, null); - } - - public Path downloadLatest(String serverUrl, Path destinationPath, DownloadProgressListener progressListener) { - LOGGER.info("Downloading latest backup from {} to {}", serverUrl, destinationPath); - - return downloadFromUri( - URI.create(serverUrl + Endpoints.SERVER_BACKUP_LATEST_DOWNLOAD.getPath()), - destinationPath, - "latest backup", - progressListener - ); - } - - public Path downloadById(String serverUrl, String backupId, Path destinationPath) { - return downloadById(serverUrl, backupId, destinationPath, null); - } - - public Path downloadById(String serverUrl, String backupId, Path destinationPath, DownloadProgressListener progressListener) { - LOGGER.info("Downloading backup id={} from {} to {}", backupId, serverUrl, destinationPath); - - return downloadFromUri( - URI.create(serverUrl + Endpoints.SERVER_BACKUPS.getPath() + "/" + backupId + "/download"), - destinationPath, - "backup " + backupId, - progressListener - ); - } - - private Path downloadFromUri(URI uri, Path destinationPath, String operationName, DownloadProgressListener progressListener) { - HttpRequest request = HttpRequest.newBuilder(uri).GET().build(); - - try { - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream()); - int status = response.statusCode(); - if (status < 200 || status >= 300) { - String snippet; - try (InputStream errorBody = response.body()) { - snippet = new String(errorBody.readNBytes(256)); - } - LOGGER.error("{} download failed from {} with HTTP {}: {}", operationName, uri, status, snippet); - throw new IllegalStateException(operationName + " download failed with HTTP " + status); - } - - Files.createDirectories(destinationPath.getParent()); - Path tempPath = destinationPath.resolveSibling(destinationPath.getFileName().toString() + ".tmp"); - long totalBytes = response.headers().firstValueAsLong("Content-Length").orElse(-1L); - - try (InputStream inputStream = response.body(); - OutputStream outputStream = Files.newOutputStream( - tempPath, - StandardOpenOption.CREATE, - StandardOpenOption.TRUNCATE_EXISTING, - StandardOpenOption.WRITE - )) { - byte[] buffer = new byte[8192]; - long bytesWritten = 0L; - int read; - while ((read = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, read); - bytesWritten += read; - if (progressListener != null) { - progressListener.onProgress(bytesWritten, totalBytes); - } - } - } - - if (!looksLikeZip(tempPath)) { - long size = Files.size(tempPath); - Files.deleteIfExists(tempPath); - LOGGER.error("{} download returned non-zip payload from {} ({} bytes)", operationName, uri, size); - throw new IllegalStateException("Server returned non-zip content for " + operationName + " download"); - } - - Files.move(tempPath, destinationPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); - LOGGER.info("Download complete: {} ({} bytes)", destinationPath.getFileName(), Files.size(destinationPath)); - return destinationPath; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - LOGGER.error("{} download interrupted for {}", operationName, uri, e); - throw new IllegalStateException(operationName + " download interrupted", e); - } catch (IOException e) { - LOGGER.error("Failed to persist {} download to {}", operationName, destinationPath, e); - throw new IllegalStateException("Failed to persist " + operationName + " download", e); - } - } - - private boolean looksLikeZip(Path path) throws IOException { - byte[] header = new byte[4]; - try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ)) { - int read = in.read(header); - if (read < 4) { - return false; - } - } - - return header[0] == 'P' - && header[1] == 'K' - && ((header[2] == 3 && header[3] == 4) - || (header[2] == 5 && header[3] == 6) - || (header[2] == 7 && header[3] == 8)); - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/service/ServerDiscoveryService.java b/src/main/java/wellatleastitried/mediaguardclient/service/ServerDiscoveryService.java deleted file mode 100644 index 5de7b05..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/service/ServerDiscoveryService.java +++ /dev/null @@ -1,293 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.URI; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.net.http.HttpClient; -import java.time.Duration; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CompletionService; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ExecutorCompletionService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.springframework.http.HttpStatusCode; -import org.springframework.http.client.JdkClientHttpRequestFactory; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestClient; -import org.springframework.web.client.RestClientException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import wellatleastitried.mediagarrdclient.Configuration; - -@Service -public class ServerDiscoveryService { - - private static final Logger LOGGER = LoggerFactory.getLogger(ServerDiscoveryService.class); - - private static final int MIN_NON_STANDARD_PORT = 1024; - private static final int MAX_PORT = 65535; - private static final int PORT_SCAN_THREADS = 128; - private static final int DISCOVERY_THREADS = 64; - - private final Configuration configuration; - private final RestClient restClient; - - public ServerDiscoveryService(Configuration configuration) { - this.configuration = configuration; - HttpClient httpClient = HttpClient.newBuilder() - .followRedirects(HttpClient.Redirect.NORMAL) - .connectTimeout(Duration.ofMillis(2500)) - .build(); - JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient); - requestFactory.setReadTimeout(Duration.ofMillis(3000)); - this.restClient = RestClient.builder().requestFactory(requestFactory).build(); - } - - public List discover() { - List prefixes = localPrefixes(); - Set discovered = new java.util.LinkedHashSet<>(); - - LOGGER.info("Starting network discovery: localPrefixes={}", prefixes); - - String preferredServerIp = configuration.getPreferredServerIp(); - if (preferredServerIp != null && !preferredServerIp.isBlank()) { - LOGGER.info("Probing preferred server IP: {}", preferredServerIp); - resolveServerByIp(preferredServerIp).ifPresent(url -> { - LOGGER.info("Preferred IP resolved: {}", url); - discovered.add(url); - }); - } - - if (prefixes.isEmpty()) { - LOGGER.warn("No local network prefixes detected, skipping subnet scan"); - return discovered.stream().toList(); - } - - List portsToProbe = discoveryPorts(); - LOGGER.info("Scanning {} subnet prefix(es) with {} port(s) each, ports={}", prefixes.size(), portsToProbe.size(), portsToProbe); - Set candidates = new java.util.LinkedHashSet<>(); - for (String prefix : prefixes) { - for (int host = 1; host <= 254; host++) { - String ip = prefix + "." + host; - for (Integer port : portsToProbe) { - candidates.add("http://" + ip + ":" + port); - } - } - } - - ExecutorService executor = Executors.newFixedThreadPool(DISCOVERY_THREADS); - LOGGER.info("Probing {} candidate endpoints with {} threads", candidates.size(), DISCOVERY_THREADS); - try { - CompletionService completionService = new ExecutorCompletionService<>(executor); - int submitted = 0; - for (String candidate : candidates) { - completionService.submit(() -> isHealthy(candidate) ? candidate : null); - submitted++; - } - - for (int i = 0; i < submitted; i++) { - try { - String healthy = completionService.take().get(); - if (healthy != null) { - LOGGER.info("Discovered server: {}", healthy); - discovered.add(healthy); - } - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - break; - } catch (ExecutionException ignored) { - } - } - } finally { - executor.shutdownNow(); - } - - LOGGER.info("Network discovery complete, found {} server(s): {}", discovered.size(), discovered); - return discovered.stream().toList(); - } - - private List discoveryPorts() { - Set ports = new java.util.LinkedHashSet<>(); - ports.add(configuration.getServerPort()); - ports.add(38471); - ports.add(8080); - ports.add(3000); - ports.add(5000); - ports.add(8081); - ports.add(80); - ports.add(443); - return new ArrayList<>(ports); - } - - public Optional resolveServerByIp(String input) { - return resolveServerByIp(input, null); - } - - public Optional resolveServerByIp(String input, Integer preferredPort) { - String host = normalizeHost(input); - if (host == null) { - LOGGER.warn("resolveServerByIp: invalid input '{}'", input); - return Optional.empty(); - } - - LOGGER.info("Resolving server at host={}, preferredPort={}", host, preferredPort); - - if (preferredPort != null) { - String preferredCandidate = toUrl(host, preferredPort); - LOGGER.debug("Probing preferred port: {}", preferredCandidate); - if (isHealthy(preferredCandidate)) { - LOGGER.info("Server found at preferred port: {}", preferredCandidate); - return Optional.of(preferredCandidate); - } - LOGGER.debug("Preferred port {} not responding", preferredPort); - } - - int defaultPort = configuration.getServerPort(); - String defaultCandidate = toUrl(host, defaultPort); - LOGGER.debug("Probing default port: {}", defaultCandidate); - if (isHealthy(defaultCandidate)) { - LOGGER.info("Server found at default port: {}", defaultCandidate); - return Optional.of(defaultCandidate); - } - - LOGGER.debug("Default port {} not responding, trying common ports", defaultPort); - for (Integer quickPort : discoveryPorts()) { - if (quickPort == defaultPort) { - continue; - } - if (preferredPort != null && quickPort.equals(preferredPort)) { - continue; - } - String quickCandidate = toUrl(host, quickPort); - LOGGER.debug("Probing common port: {}", quickCandidate); - if (isHealthy(quickCandidate)) { - LOGGER.info("Server found at common port: {}", quickCandidate); - return Optional.of(quickCandidate); - } - } - - LOGGER.info("Common ports exhausted for {}, starting full port scan ({}-{})", host, MIN_NON_STANDARD_PORT, MAX_PORT); - ExecutorService executor = Executors.newFixedThreadPool(PORT_SCAN_THREADS); - AtomicBoolean stop = new AtomicBoolean(false); - try { - CompletionService completionService = new ExecutorCompletionService<>(executor); - int submitted = 0; - for (int port = MIN_NON_STANDARD_PORT; port <= MAX_PORT; port++) { - if (port == defaultPort) { - continue; - } - if (preferredPort != null && port == preferredPort) { - continue; - } - - final int candidatePort = port; - completionService.submit(() -> { - if (stop.get()) { - return null; - } - String candidate = toUrl(host, candidatePort); - if (isHealthy(candidate)) { - stop.set(true); - return candidate; - } - return null; - }); - submitted++; - } - - for (int i = 0; i < submitted; i++) { - String candidate = completionService.take().get(); - if (candidate != null) { - LOGGER.info("Server found via full port scan: {}", candidate); - return Optional.of(candidate); - } - } - LOGGER.warn("Full port scan exhausted for {}, no server found", host); - return Optional.empty(); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - LOGGER.warn("Port scan interrupted for {}", host); - return Optional.empty(); - } catch (ExecutionException ex) { - LOGGER.warn("Port scan execution error for {}: {}", host, ex.getMessage()); - return Optional.empty(); - } finally { - executor.shutdownNow(); - } - } - - private List localPrefixes() { - List prefixes = new ArrayList<>(); - try { - Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); - while (interfaces.hasMoreElements()) { - NetworkInterface networkInterface = interfaces.nextElement(); - if (!networkInterface.isUp() || networkInterface.isLoopback()) { - continue; - } - Enumeration addresses = networkInterface.getInetAddresses(); - while (addresses.hasMoreElements()) { - InetAddress address = addresses.nextElement(); - if (address instanceof Inet4Address ipv4 && !ipv4.isLoopbackAddress()) { - byte[] bytes = ipv4.getAddress(); - prefixes.add((bytes[0] & 0xFF) + "." + (bytes[1] & 0xFF) + "." + (bytes[2] & 0xFF)); - } - } - } - } catch (SocketException ignored) { - } - return prefixes.stream().distinct().toList(); - } - - private boolean isHealthy(String candidate) { - try { - HttpStatusCode status = restClient.get() - .uri(candidate + "/api/v1/health") - .retrieve() - .toBodilessEntity() - .getStatusCode(); - boolean ok = status.is2xxSuccessful(); - if (ok) { - LOGGER.debug("Health check OK: {}", candidate); - } - return ok; - } catch (RestClientException ex) { - LOGGER.debug("Health check failed for {}: {}", candidate, ex.getMessage()); - return false; - } - } - - private String normalizeHost(String input) { - if (input == null) { - return null; - } - String trimmed = input.trim(); - if (trimmed.isBlank()) { - return null; - } - - try { - URI uri = trimmed.contains("://") ? URI.create(trimmed) : URI.create("http://" + trimmed); - if (uri.getHost() != null && !uri.getHost().isBlank()) { - return uri.getHost(); - } - } catch (IllegalArgumentException ignored) { - } - return trimmed; - } - - private String toUrl(String host, int port) { - return "http://" + host + ":" + port; - } -} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index fdda830..e37934f 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,10 +1,30 @@ server: port: ${CLIENT_PORT:8081} +spring: + jackson: + deserialization: + fail-on-null-for-primitives: false + task: + scheduling: + pool: + size: 2 + web: + resources: + cache: + period: 0 + mediagarrd: client: - state-file: ${CLIENT_STATE_FILE:./data/client/state.json} - download-directory: ${CLIENT_DOWNLOAD_DIRECTORY:./data/client/downloads} + state-file: ${CLIENT_STATE_FILE:/var/lib/mediagarrd/client/state.json} + download-directory: ${CLIENT_DOWNLOAD_DIRECTORY:/var/lib/mediagarrd/downloads} pickup-interval: ${CLIENT_PICKUP_INTERVAL:PT12H} - server-port: ${MEDIAGARRD_SERVER_PORT:8080} + server-port: ${MEDIAGARRD_SERVER_PORT:38471} preferred-server-ip: ${MEDIAGARRD_SERVER_IP:} + update-repository: ${MEDIAGARRD_UPDATE_REPOSITORY:MediaGarrd/Client} + github-api-base-url: ${MEDIAGARRD_GITHUB_API_URL:https://api.github.com} + update-check-interval: ${MEDIAGARRD_UPDATE_CHECK_INTERVAL:PT24H} + backup-run-timeout: ${CLIENT_BACKUP_RUN_TIMEOUT:PT6H} + server-ca: ${MEDIAGARRD_SERVER_CA:} + password: ${CLIENT_PASSWORD:} + reset-password: ${CLIENT_RESET_PASSWORD:false} diff --git a/src/main/resources/static/css/mediagarrd.css b/src/main/resources/static/css/mediagarrd.css new file mode 100644 index 0000000..839bfd1 --- /dev/null +++ b/src/main/resources/static/css/mediagarrd.css @@ -0,0 +1,409 @@ +:root { + --bg: #000; + --surface: #0a0a0a; + --surface-raised: #111; + --ink: #f5f5f5; + --muted: #8a8a8a; + --subtle: #404040; + --border: #1f1f1f; + --border-mid: #2e2e2e; + --accent: #f5f5f5; + --accent-dim: #d4d4d4; + --ok: #22c55e; + --warn: #ef4444; + --mono: "JetBrains Mono", "Fira Code", ui-monospace, monospace; +} + +*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } + +body { + font-family: "Space Grotesk", "Inter", "Avenir Next", ui-sans-serif, system-ui, sans-serif; + background: var(--bg); + color: var(--ink); + min-height: 100vh; + font-size: 14px; + line-height: 1.5; +} + +[hidden] { display: none !important; } + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + flex-wrap: wrap; + padding: 0.85rem 1.5rem; + border-bottom: 1px solid var(--border); + background: var(--surface); + position: sticky; + top: 0; + z-index: 10; +} + +.brand { display: flex; flex-direction: column; } +.brand-title { font-size: 1rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; } +.brand-sub { font-size: 0.72rem; color: var(--muted); letter-spacing: 0.05em; } + +.view-toggle { display: flex; border: 1px solid var(--border-mid); } +.view-toggle button { background: transparent; color: var(--muted); border: none; padding: 0.4rem 0.85rem; } +.view-toggle button:hover { background: var(--surface-raised); color: var(--ink); } +.view-toggle button[aria-pressed="true"] { background: var(--accent); color: #000; } + +.conn-badge { + display: flex; + align-items: center; + gap: 0.45rem; + padding: 0.32rem 0.75rem; + border: 1px solid var(--border-mid); + font-size: 0.75rem; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--muted); + background: var(--surface-raised); + white-space: nowrap; + max-width: 22rem; +} +.conn-badge [data-label] { overflow: hidden; text-overflow: ellipsis; } +.conn-badge .dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--subtle); + flex-shrink: 0; + transition: background 300ms; +} +.conn-badge.ok { color: #a3e8bc; border-color: #1e3b2a; } +.conn-badge.ok .dot { background: var(--ok); box-shadow: 0 0 6px var(--ok); } +.conn-badge.down { color: #fca5a5; border-color: #3b1111; } +.conn-badge.down .dot { background: var(--warn); box-shadow: 0 0 6px var(--warn); } +.conn-badge.degraded { color: #fcd34d; border-color: #4a3510; } +.conn-badge.degraded .dot { background: #f59e0b; box-shadow: 0 0 6px #f59e0b; } +.conn-badge.checking { color: var(--accent-dim); } +.conn-badge.checking .dot { background: #a3a3a3; } + +.page { max-width: 1200px; margin: 0 auto; padding: 1.5rem; animation: fadein 350ms ease; } +.workspace { + display: grid; + grid-template-columns: 360px minmax(0, 1fr); + gap: 1rem; + align-items: start; +} +.workspace > * { min-width: 0; } +.stack { display: flex; flex-direction: column; gap: 1rem; } +@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; } +.panel-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0.7rem 1rem; + border-bottom: 1px solid var(--border); +} +.panel-title { font-size: 0.72rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: var(--accent-dim); } +.panel-body { padding: 1rem; } +.panel-body + .panel-body { border-top: 1px solid var(--border); } +.section-label { + font-size: 0.68rem; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); + margin-bottom: 0.6rem; +} + +.field-group { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 0.75rem; } +.field-label { font-size: 0.7rem; color: var(--muted); letter-spacing: 0.04em; } +.note { font-size: 0.72rem; color: var(--muted); margin-top: 0.45rem; overflow-wrap: anywhere; } +.note + .field-group { margin-top: 0.75rem; } +.input-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0.5rem; } +.input-row-2 { display: grid; grid-template-columns: minmax(0, 1fr) 110px; gap: 0.5rem; } +.button-row { display: flex; gap: 0.5rem; flex-wrap: wrap; } +.button-row > button { flex: 1; } + +input, select { + width: 100%; + min-width: 0; + background: var(--bg); + color: var(--ink); + border: 1px solid var(--border-mid); + padding: 0.5rem 0.65rem; + font: inherit; + font-size: 0.85rem; + transition: border-color 150ms; +} +input:focus, select:focus { border-color: var(--subtle); } +input:focus-visible, select:focus-visible, button:focus-visible, a:focus-visible { + outline: 2px solid var(--ink); + outline-offset: 2px; +} +input::placeholder { color: var(--muted); } + +button { + background: var(--accent); + color: #000; + border: 1px solid var(--accent); + padding: 0.5rem 0.85rem; + font: inherit; + font-size: 0.78rem; + font-weight: 700; + letter-spacing: 0.05em; + text-transform: uppercase; + cursor: pointer; + white-space: nowrap; + transition: background 120ms, color 120ms, border-color 120ms, transform 70ms, box-shadow 120ms; +} +button:hover { background: var(--accent-dim); border-color: var(--accent-dim); } +button:active, button.clicked { transform: translateY(1px) scale(0.98); box-shadow: inset 0 0 0 2px #000; } +button:disabled, +button:disabled:hover, +button.ghost:disabled, +button.ghost:disabled:hover, +button.danger:disabled, +button.danger:disabled:hover { + cursor: not-allowed; + opacity: 0.45; + transform: none; + box-shadow: none; + background: transparent; + color: var(--muted); + border-color: var(--border-mid); +} +button.ghost { background: transparent; color: var(--ink); border-color: var(--border-mid); } +button.ghost:hover { border-color: var(--subtle); background: var(--surface-raised); } +button.danger { background: transparent; color: #fca5a5; border-color: #3b1111; } +button.danger:hover { background: #1c0606; } +button.full { width: 100%; } +button.small { padding: 0.3rem 0.65rem; font-size: 0.7rem; } + +.action-btn { position: relative; overflow: hidden; } +.action-btn .btn-label { position: relative; z-index: 1; } +.btn-progress { + position: absolute; + left: 0; + right: 0; + bottom: 0; + height: 2px; + display: none; + background: rgba(255, 255, 255, 0.12); + overflow: hidden; +} +.action-btn.busy .btn-progress { display: block; } +.btn-progress.indeterminate::after { + content: ''; + display: block; + width: 34%; + height: 100%; + background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.85), transparent); + animation: sweep 1.1s linear infinite; +} +.btn-progress-fill { + display: block; + width: 0; + height: 100%; + background: linear-gradient(90deg, #9ca3af, #f5f5f5); + transition: width 120ms linear; +} + +.stat-row { + display: flex; + align-items: baseline; + justify-content: space-between; + padding: 0.35rem 0; + border-bottom: 1px solid var(--border); + font-size: 0.83rem; +} +.stat-row:last-child { border-bottom: none; } +.stat-key { color: var(--muted); font-size: 0.75rem; letter-spacing: 0.03em; } +.stat-val { font-weight: 600; text-align: right; font-variant-numeric: tabular-nums; } + +.version-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; padding: 1rem; } +@media (max-width: 900px) { .version-list { grid-template-columns: minmax(0, 1fr); } } +.version-row { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0.3rem 0.75rem; + padding: 0.7rem 0.9rem; + background: var(--surface-raised); + border: 1px solid var(--border); + font-size: 0.83rem; +} +.version-name { min-width: 3.5rem; color: var(--muted); font-size: 0.75rem; letter-spacing: 0.03em; } +.version-number { font-family: var(--mono); font-weight: 600; font-variant-numeric: tabular-nums; } +.version-state { margin-left: auto; text-align: right; font-weight: 600; } +.version-row.current .version-state { color: #a3e8bc; } +.version-row.unknown .version-state, +.version-row.checking .version-state { color: var(--muted); font-weight: 400; } +.version-row.outdated { background: #1c0606; border-color: #3b1111; color: #fca5a5; } +.version-row.outdated .version-name { color: #fca5a5; } +.release-link { flex-basis: 100%; color: inherit; font-size: 0.78rem; text-decoration: underline; text-underline-offset: 2px; } + +.tag { + display: inline-block; + padding: 0.12rem 0.45rem; + font-size: 0.7rem; + font-weight: 700; + letter-spacing: 0.07em; + text-transform: uppercase; + border: 1px solid var(--border-mid); + color: var(--muted); +} +.tag.running { color: #a3e8bc; border-color: #1e3b2a; } + +.scan-bar { display: none; height: 2px; background: var(--border); overflow: hidden; margin-top: 0.6rem; } +.scan-bar.active { display: block; } +.scan-bar > span { + display: block; + width: 30%; + height: 100%; + background: linear-gradient(90deg, transparent, var(--accent-dim), transparent); + animation: sweep 1.1s linear infinite; +} + +.server-url { + font-family: var(--mono); + font-size: 0.78rem; + color: var(--accent-dim); + word-break: break-all; + padding: 0.4rem 0.6rem; + background: var(--surface-raised); + border: 1px solid var(--border); + margin-bottom: 0.75rem; +} + +.table-scroll { overflow-x: auto; } +table { width: 100%; border-collapse: collapse; font-size: 0.82rem; } +thead th { + padding: 0.5rem 0.75rem; + text-align: left; + font-size: 0.68rem; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); + border-bottom: 1px solid var(--border-mid); +} +thead th.sortable { cursor: pointer; user-select: none; transition: color 120ms; white-space: nowrap; } +thead th .sort-btn { + background: transparent; + border: none; + padding: 0; + color: inherit; + font: inherit; + letter-spacing: inherit; + text-transform: inherit; + cursor: pointer; +} +thead th .sort-btn:hover { background: transparent; } +thead th.sortable:hover, thead th.sortable.active { color: var(--accent-dim); } +.sort-indicator { margin-left: 0.25rem; font-size: 0.65rem; color: var(--subtle); vertical-align: middle; } +thead th.sortable.active .sort-indicator { color: var(--accent-dim); } +tbody tr { border-bottom: 1px solid var(--border); transition: background 100ms; } +tbody tr:last-child { border-bottom: none; } +tbody tr:hover { background: var(--surface-raised); } +tbody td { padding: 0.55rem 0.75rem; vertical-align: middle; } +.td-mono { font-family: var(--mono); font-size: 0.78rem; color: var(--accent-dim); white-space: pre-line; word-break: break-all; } +.td-muted { color: var(--muted); } +.td-id { font-size: 0.7rem; } +.actions-cell { text-align: right; white-space: nowrap; } +.actions-cell button + button { margin-left: 0.4rem; } +.empty-state { padding: 2.5rem 1rem; text-align: center; color: var(--muted); font-size: 0.83rem; } + +.icon-btn { + min-width: 44px; + height: 36px; + padding: 0; + font-size: 0.95rem; + line-height: 1; + font-weight: 800; + letter-spacing: 0; + text-transform: none; +} +.row-progress-circle { + width: 16px; + height: 16px; + border-radius: 50%; + display: inline-block; + position: relative; + background: conic-gradient(var(--accent-dim) var(--p, 0%), var(--border-mid) 0); +} +.row-progress-circle::after { + content: ''; + position: absolute; + inset: 3px; + border-radius: 50%; + background: var(--surface); +} + +.banner { + display: none; + margin-bottom: 1rem; + padding: 0.65rem 1rem; + font-size: 0.82rem; + background: #1c0606; + border: 1px solid #3b1111; + color: #fca5a5; +} +.banner.visible { display: block; } +.banner { scroll-margin-top: 5rem; } +.banner.warn { background: #1c1306; border-color: #4a3510; color: #fcd34d; } +.banner.ok { background: #06140b; border-color: #1e3b2a; color: #a3e8bc; } + +@keyframes sweep { + from { transform: translateX(-150%); } + to { transform: translateX(420%); } +} + +@keyframes fadein { + from { opacity: 0; transform: translateY(6px); } + to { opacity: 1; transform: translateY(0); } +} + +.topbar-end { display: flex; align-items: center; gap: 0.6rem; } + +.auth { + position: fixed; + inset: 0; + z-index: 20; + display: flex; + align-items: center; + justify-content: center; + padding: 1rem; + background: var(--bg); +} +.auth-card { width: min(380px, 100%); } +.auth-error { padding: 0 1rem 1rem; font-size: 0.8rem; color: #fca5a5; } +.auth-error:empty { display: none; } + +.code-box { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 0.75rem; + margin-top: 0.75rem; + padding: 0.6rem 0.75rem; + border: 1px solid var(--border-mid); + background: var(--bg); +} +.code-box .code { font-family: var(--mono); font-size: 1.05rem; letter-spacing: 0.08em; user-select: all; } + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + animation-duration: 0.001ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.001ms !important; + } +} diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html index f15c498..082b5e7 100644 --- a/src/main/resources/static/index.html +++ b/src/main/resources/static/index.html @@ -4,1198 +4,301 @@ MediaGarrd Client - + + - -
MediaGarrd Client Dashboard
-
- - Connecting... + +
+
+ + Connecting… +
+
-
- - -
-
- Server Connection -
- - -
- + - - -
- + + +
- - -
- - - -

Last scan: not run yet.

-
+
+ + +
+ + +
+ + +
+ + +
+
+
Server Connection
+ +
+ +
+
+ + +
+
+ +
- -
-
- Server Status -
- - -
-
No server connected.
-
+ +
+
Server Status
+ +
+

Connecting…

+ -
- State - IDLE + +
+ + -
- -
- -
- - +
+ +
+ + +
-
- -
- -
- - +
+ +
+ + +
+ +
+
+ +
+
+ Backup Archives +
-
- - +
+ + + + + + + + + + + +
Get
-
-
- - -
+

No backups loaded. Connect to a server to view archives.

- -
-
- Backup Archives - -
- - + + + +
+
Versions
+
+
+ Server + — + Checking… + +
+
+ Client + — + Checking… + +
+
+
+ + +
+ + +
NamePathsActions
+
+

No services configured yet.

+ + +
+
Failure Notifications
+
+
+ + +

The server sends a message when a backup fails or only partly succeeds, so you hear about it before the next scheduled try. Works with Discord, Slack and any receiver that accepts JSON. The saved address is never shown again.

+

Checking…

+
+
+ + + +
+
+
+ + + + diff --git a/src/main/resources/static/js/api.js b/src/main/resources/static/js/api.js new file mode 100644 index 0000000..b62c675 --- /dev/null +++ b/src/main/resources/static/js/api.js @@ -0,0 +1,99 @@ +let loginRequiredHandler = () => {}; +let pairingRequiredHandler = () => {}; + +export function onLoginRequired(handler) { + loginRequiredHandler = handler; +} + +export function onPairingRequired(handler) { + pairingRequiredHandler = handler; +} + +export function loginRequired() { + loginRequiredHandler(); +} + +export function retryAfterSeconds(value, now = Date.now()) { + if (value === null || value === undefined || String(value).trim() === '') return null; + const text = String(value).trim(); + if (/^\d+$/.test(text)) return Number(text); + const date = Date.parse(text); + return Number.isFinite(date) ? Math.max(0, Math.ceil((date - now) / 1000)) : null; +} + +export function errorMessage(data, fallback) { + const body = data && typeof data === 'object' ? data : {}; + for (const candidate of [body.message, body.error]) { + if (typeof candidate === 'string' && candidate.trim()) return candidate; + } + return fallback; +} + +export function fallbackMessage(status) { + if (status === 502 || status === 504) return 'The client or a proxy in front of it did not respond in time.'; + return `The client answered with an error (${status}).`; +} + +export function toApiError({ status, data, retryAfter }) { + const error = new Error(errorMessage(data, fallbackMessage(status))); + error.status = status; + error.pairing = data?.pairing; + error.retryAfter = retryAfterSeconds(retryAfter); + return error; +} + +async function request(method, url, body) { + const response = await fetch(url, { + method, + headers: body === undefined + ? { 'X-MediaGarrd-Request': '1' } + : { 'Content-Type': 'application/json', 'X-MediaGarrd-Request': '1' }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + if (!response.ok) { + const data = await response.json().catch(() => ({})); + if (response.status === 401 && data?.login === 'required') loginRequiredHandler(); + const error = toApiError({ + method, + url, + status: response.status, + data, + retryAfter: response.headers?.get('Retry-After'), + }); + if (error.pairing === 'required') pairingRequiredHandler(); + throw error; + } + const text = await response.text(); + return text ? JSON.parse(text) : null; +} + +const encode = encodeURIComponent; + +export const api = { + authStatus: () => request('GET', '/api/auth/status'), + login: (password) => request('POST', '/api/auth/login', { password }), + setPassword: (password) => request('POST', '/api/auth/set-password', { password }), + logout: () => request('POST', '/api/auth/logout'), + pair: (pin) => request('POST', '/api/client/pairing', { pin }), + createPairingCode: () => request('POST', '/api/client/pairing/code'), + unpair: () => request('DELETE', '/api/client/pairing'), + status: () => request('GET', '/api/client/status'), + discover: () => request('POST', '/api/client/discover'), + dashboard: () => request('GET', '/api/client/dashboard'), + selectServer: (selection) => request('PUT', '/api/client/server', selection), + listBackups: () => request('GET', '/api/client/backups'), + runBackup: () => request('POST', '/api/client/backups/run'), + pickupLatest: () => request('POST', '/api/client/pickup'), + pickupById: (id) => request('POST', `/api/client/pickup/${encode(id)}`), + pickupProgress: (taskId) => request('GET', `/api/client/pickup/progress/${encode(taskId)}`), + updatePickupInterval: (interval) => request('PUT', '/api/client/pickup-interval', { interval }), + serverConfig: () => request('GET', '/api/client/server-config'), + updateServerConfig: (config) => request('PUT', '/api/client/server-config', config), + webhook: () => request('GET', '/api/client/notifications/webhook'), + updateWebhook: (url) => request('PUT', '/api/client/notifications/webhook', { url }), + testWebhook: () => request('POST', '/api/client/notifications/webhook/test'), + listServices: () => request('GET', '/api/client/services'), + addService: (service) => request('POST', '/api/client/services', service), + updateService: (name, service) => request('PUT', `/api/client/services/${encode(name)}`, service), + removeService: (name) => request('DELETE', `/api/client/services/${encode(name)}`), +}; diff --git a/src/main/resources/static/js/auth-model.js b/src/main/resources/static/js/auth-model.js new file mode 100644 index 0000000..cf347cb --- /dev/null +++ b/src/main/resources/static/js/auth-model.js @@ -0,0 +1,17 @@ +export const MIN_PASSWORD_LENGTH = 8; + +export function authScreen(status) { + if (!status) return 'loading'; + if (status.authenticated) return 'none'; + return status.passwordSet ? 'login' : 'set-password'; +} + +export function passwordProblem(password, confirm) { + if (password.length < MIN_PASSWORD_LENGTH) return `Use at least ${MIN_PASSWORD_LENGTH} characters.`; + if (password !== confirm) return 'The passwords do not match.'; + return null; +} + +export function lockoutMessage(seconds) { + return seconds > 0 ? `Too many login attempts. Try again in ${seconds} second${seconds === 1 ? '' : 's'}.` : null; +} diff --git a/src/main/resources/static/js/auth.js b/src/main/resources/static/js/auth.js new file mode 100644 index 0000000..b836444 --- /dev/null +++ b/src/main/resources/static/js/auth.js @@ -0,0 +1,151 @@ +import { api, onLoginRequired } from './api.js'; +import { authScreen, lockoutMessage, passwordProblem } from './auth-model.js'; + +const RETRY_MIN_MS = 1000; +const RETRY_MAX_MS = 10000; +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +export function initAuth({ root, logoutButton, background = [] }) { + const loginForm = root.querySelector('[data-login-form]'); + const setForm = root.querySelector('[data-set-form]'); + const title = root.querySelector('[data-auth-title]'); + const error = root.querySelector('[data-auth-error]'); + let reloading = false; + let lockout = null; + + function reload() { + if (reloading) return; + reloading = true; + location.reload(); + } + + function clearLockout() { + clearInterval(lockout); + lockout = null; + } + + function show(screen) { + clearLockout(); + root.hidden = screen === 'none'; + background.forEach((element) => { element.inert = screen !== 'none'; }); + loginForm.hidden = screen !== 'login'; + setForm.hidden = screen !== 'set-password'; + title.textContent = screen === 'set-password' ? 'Set a password' : 'Sign in'; + error.textContent = ''; + loginForm.querySelector('button').disabled = false; + setForm.querySelector('button').disabled = false; + if (screen !== 'none') (screen === 'login' ? loginForm : setForm).elements.password.focus(); + } + + function holdUntil(form, seconds) { + const button = form.querySelector('button'); + const until = Date.now() + seconds * 1000; + button.disabled = true; + clearLockout(); + const tick = () => { + const remaining = Math.ceil((until - Date.now()) / 1000); + if (remaining <= 0) { + clearLockout(); + error.textContent = ''; + button.disabled = false; + form.elements.password.focus(); + return; + } + error.textContent = lockoutMessage(remaining); + }; + tick(); + lockout = setInterval(tick, 1000); + } + + async function submit(form, action) { + const button = form.querySelector('button'); + const refocus = document.activeElement === button; + error.textContent = ''; + button.disabled = true; + try { + await action(); + reload(); + } catch (failure) { + error.textContent = failure.message; + if (failure.status === 429 && failure.retryAfter > 0) { + holdUntil(form, failure.retryAfter); + return; + } + if (failure.status === 409) { + await current().catch(() => {}); + error.textContent = failure.message; + return; + } + button.disabled = false; + if (refocus) form.elements.password.focus(); + } + } + + async function current() { + const screen = authScreen(await api.authStatus()); + if (screen === 'none') { + reload(); + return screen; + } + show(screen); + logoutButton.hidden = true; + return screen; + } + + loginForm.addEventListener('submit', (event) => { + event.preventDefault(); + submit(loginForm, () => api.login(loginForm.elements.password.value)); + }); + + setForm.addEventListener('submit', (event) => { + event.preventDefault(); + const { password, confirm } = setForm.elements; + const problem = passwordProblem(password.value, confirm.value); + if (problem) { + error.textContent = problem; + return; + } + submit(setForm, () => api.setPassword(password.value)); + }); + + logoutButton.addEventListener('click', async () => { + try { + await api.logout(); + } finally { + reload(); + } + }); + + onLoginRequired(reload); + + function showConnecting(message) { + root.hidden = false; + background.forEach((element) => { element.inert = true; }); + loginForm.hidden = true; + setForm.hidden = true; + title.textContent = 'MediaGarrd Client'; + error.textContent = message; + } + + return { + async ensureSignedIn() { + let delay = RETRY_MIN_MS; + for (;;) { + let screen = 'loading'; + try { + screen = authScreen(await api.authStatus()); + } catch (failure) { + showConnecting(`Client unreachable: ${failure.message}. Retrying…`); + } + if (screen !== 'loading') { + show(screen); + logoutButton.hidden = screen !== 'none'; + return screen === 'none'; + } + if (!error.textContent) showConnecting('Connecting…'); + await wait(delay); + delay = Math.min(delay * 2, RETRY_MAX_MS); + } + }, + }; +} diff --git a/src/main/resources/static/js/backups.js b/src/main/resources/static/js/backups.js new file mode 100644 index 0000000..7384650 --- /dev/null +++ b/src/main/resources/static/js/backups.js @@ -0,0 +1,272 @@ +import { api } from './api.js'; +import { bytes, percent, relativeTime } from './format.js'; +import { listingError } from './view-model.js'; + +const POLL_INTERVAL_MS = 350; +const POLL_MAX_INTERVAL_MS = 1500; +const EMPTY_DEFAULT = 'No backup archives found on server.'; +const EMPTY_DISCONNECTED = 'No backups loaded. Connect to a server to view archives.'; +const EMPTY_UNPAIRED = 'No backups loaded. Pair this client with the server to view archives.'; + +export function initBackups({ root, actions }, notify) { + const rows = root.querySelector('tbody'); + const empty = root.querySelector('[data-empty]'); + const headers = root.querySelectorAll('th[data-sort-key]'); + const template = root.querySelector('#backupTemplate'); + const runButton = actions.querySelector('[data-run]'); + const pickupButton = actions.querySelector('[data-pickup]'); + const sort = { key: 'fileName', dir: 'asc' }; + const rowTasks = new Map(); + const rowButtons = new Map(); + let backups = []; + let serverRunning = false; + let runInFlight = false; + let available = false; + let latestTask = null; + let pollTimer = null; + let pollDelay = POLL_INTERVAL_MS; + let latestRequest = 0; + let generation = 0; + let pairingNeeded = false; + let emptyMessage = EMPTY_DISCONNECTED; + + function renderActions() { + const backupBusy = serverRunning || runInFlight; + runButton.disabled = backupBusy || !available; + runButton.classList.toggle('busy', backupBusy); + runButton.querySelector('.btn-label').textContent = backupBusy ? 'Backup In Progress' : 'Run Backup Now'; + + pickupButton.disabled = Boolean(latestTask) || !available; + pickupButton.classList.toggle('busy', Boolean(latestTask)); + pickupButton.querySelector('.btn-label').textContent = latestTask ? 'Downloading...' : 'Download Latest'; + pickupButton.querySelector('.btn-progress-fill').style.width = + `${latestTask ? percent(latestTask.bytesWritten, latestTask.totalBytes) : 0}%`; + } + + function renderRowButton(id) { + const button = rowButtons.get(id); + if (!button) return; + const task = rowTasks.get(id); + button.disabled = Boolean(task) || !available; + if (!task) { + button.textContent = '↓'; + return; + } + const progress = document.createElement('span'); + progress.className = 'row-progress-circle'; + progress.style.setProperty('--p', `${percent(task.bytesWritten, task.totalBytes)}%`); + button.replaceChildren(progress); + } + + function compare(a, b) { + const dir = sort.dir === 'asc' ? 1 : -1; + if (sort.key === 'sizeBytes') return ((a.sizeBytes ?? 0) - (b.sizeBytes ?? 0)) * dir; + if (sort.key === 'createdAt') return (new Date(a.createdAt) - new Date(b.createdAt)) * dir; + return String(a[sort.key] ?? '').localeCompare(String(b[sort.key] ?? ''), undefined, { sensitivity: 'base' }) * dir; + } + + function renderRow(backup) { + const row = template.content.firstElementChild.cloneNode(true); + row.querySelector('[data-file]').textContent = backup.fileName; + row.querySelector('[data-size]').textContent = bytes(backup.sizeBytes); + row.querySelector('[data-created]').textContent = relativeTime(backup.createdAt); + const id = row.querySelector('[data-id]'); + id.textContent = backup.id.length > 22 ? `${backup.id.slice(0, 22)}…` : backup.id; + id.title = backup.id; + const button = row.querySelector('button'); + button.addEventListener('click', () => pickupById(backup.id)); + rowButtons.set(backup.id, button); + renderRowButton(backup.id); + return row; + } + + function renderTable(message = emptyMessage) { + emptyMessage = message; + headers.forEach((header) => { + const active = header.dataset.sortKey === sort.key; + header.classList.toggle('active', active); + header.setAttribute('aria-sort', active ? (sort.dir === 'asc' ? 'ascending' : 'descending') : 'none'); + header.querySelector('.sort-indicator').textContent = active ? (sort.dir === 'asc' ? '▲' : '▼') : '↕'; + }); + rowButtons.clear(); + rows.replaceChildren(...[...backups].sort(compare).map(renderRow)); + empty.textContent = emptyMessage; + empty.hidden = backups.length > 0; + } + + async function refresh() { + const request = ++latestRequest; + try { + const loaded = await api.listBackups() || []; + if (request !== latestRequest) return; + backups = loaded; + renderTable(EMPTY_DEFAULT); + } catch (error) { + if (request !== latestRequest) return; + backups = []; + renderTable(listingError(error, available)); + } + } + + function finish(id) { + if (id === null) { + latestTask = null; + renderActions(); + refresh(); + } else { + rowTasks.delete(id); + renderRowButton(id); + } + } + + async function poll() { + const tasks = [...rowTasks].filter(([, task]) => task.taskId).map(([id, task]) => ({ id, task })); + if (latestTask?.taskId) tasks.push({ id: null, task: latestTask }); + if (!tasks.length) { + pollTimer = null; + return; + } + const mine = generation; + await Promise.all(tasks.map(async ({ id, task }) => { + try { + const progress = await api.pickupProgress(task.taskId); + if (mine !== generation) return; + task.bytesWritten = progress.bytesWritten || 0; + task.totalBytes = progress.totalBytes || task.totalBytes; + if (progress.status === 'FAILED') notify.error(progress.error || 'Download failed'); + if (progress.status === 'COMPLETED' || progress.status === 'FAILED') finish(id); + } catch (error) { + if (mine !== generation) return; + notify.error(error); + finish(id); + } + })); + if (mine !== generation) { + pollTimer = null; + return; + } + rowTasks.forEach((_, id) => renderRowButton(id)); + renderActions(); + pollDelay = Math.min(Math.round(pollDelay * 1.3), POLL_MAX_INTERVAL_MS); + pollTimer = setTimeout(poll, pollDelay); + } + + function startPolling() { + if (pollTimer) return; + pollDelay = POLL_INTERVAL_MS; + pollTimer = setTimeout(poll, pollDelay); + } + + function toTask(started) { + if (!started?.taskId) throw new Error('The client did not start a download.'); + return { taskId: started.taskId, bytesWritten: 0, totalBytes: started.totalBytes || 0 }; + } + + async function pickupById(id) { + if (rowTasks.has(id) || !available) return; + notify.clear(); + const mine = generation; + rowTasks.set(id, { taskId: null, bytesWritten: 0, totalBytes: 0 }); + renderRowButton(id); + try { + const task = toTask(await api.pickupById(id)); + if (mine !== generation) return; + rowTasks.set(id, task); + startPolling(); + } catch (error) { + if (mine !== generation) return; + rowTasks.delete(id); + notify.error(error); + } + renderRowButton(id); + } + + pickupButton.addEventListener('click', async () => { + if (latestTask || !available) return; + notify.clear(); + const mine = generation; + latestTask = { taskId: null, bytesWritten: 0, totalBytes: 0 }; + renderActions(); + try { + const task = toTask(await api.pickupLatest()); + if (mine !== generation) return; + latestTask = task; + startPolling(); + } catch (error) { + if (mine !== generation) return; + latestTask = null; + notify.error(error); + } + renderActions(); + }); + + runButton.addEventListener('click', async () => { + if (serverRunning || runInFlight || !available) return; + notify.clear(); + runInFlight = true; + renderActions(); + try { + await api.runBackup(); + } catch (error) { + notify.error(error); + } finally { + runInFlight = false; + renderActions(); + } + }); + + headers.forEach((header) => header.querySelector('button').addEventListener('click', () => { + const key = header.dataset.sortKey; + if (sort.key === key) { + sort.dir = sort.dir === 'asc' ? 'desc' : 'asc'; + } else { + sort.key = key; + sort.dir = key === 'createdAt' ? 'desc' : 'asc'; + } + renderTable(); + })); + + root.querySelector('[data-refresh]').addEventListener('click', () => { + notify.clear(); + refresh(); + }); + + renderTable(EMPTY_DISCONNECTED); + renderActions(); + + function clear() { + latestRequest++; + backups = []; + renderTable(pairingNeeded ? EMPTY_UNPAIRED : EMPTY_DISCONNECTED); + } + + return { + refresh, + rerender: () => renderTable(), + clear, + reset() { + generation++; + rowTasks.clear(); + latestTask = null; + clearTimeout(pollTimer); + pollTimer = null; + clear(); + renderActions(); + }, + setPairingNeeded(value) { + if (pairingNeeded === value) return; + pairingNeeded = value; + if (!available && backups.length === 0) renderTable(value ? EMPTY_UNPAIRED : EMPTY_DISCONNECTED); + }, + setAvailable(value) { + if (available === value) return; + available = value; + rowButtons.forEach((_, id) => renderRowButton(id)); + renderActions(); + }, + setServerRunning(running) { + serverRunning = running; + renderActions(); + }, + }; +} diff --git a/src/main/resources/static/js/busy.js b/src/main/resources/static/js/busy.js new file mode 100644 index 0000000..155f1b1 --- /dev/null +++ b/src/main/resources/static/js/busy.js @@ -0,0 +1,11 @@ +export async function withBusy(button, task) { + if (button.disabled) return undefined; + const refocus = document.activeElement === button; + button.disabled = true; + try { + return await task(); + } finally { + button.disabled = false; + if (refocus) button.focus(); + } +} diff --git a/src/main/resources/static/js/connection.js b/src/main/resources/static/js/connection.js new file mode 100644 index 0000000..19456cf --- /dev/null +++ b/src/main/resources/static/js/connection.js @@ -0,0 +1,114 @@ +import { api } from './api.js'; +import { linkView, planKnown } from './view-model.js'; + +export function initConnection({ root, statusPanel, badge }, notify, { resync }) { + const ipForm = root.querySelector('[data-ip-form]'); + const known = root.querySelector('[data-known]'); + const controls = root.querySelectorAll('button, input, select'); + const scanBar = root.querySelector('[data-scan-bar]'); + const scanNote = root.querySelector('[data-scan-note]'); + const details = statusPanel.querySelector('[data-details]'); + const noServer = statusPanel.querySelector('[data-no-server]'); + const degraded = statusPanel.querySelector('[data-degraded]'); + const runState = statusPanel.querySelector('[data-state]'); + let busy = false; + let latest = null; + let renderedFor; + let deferred = false; + + function setBadge(kind, label) { + badge.className = `conn-badge ${kind}`; + badge.querySelector('[data-label]').textContent = label; + } + + function renderKnown(state) { + const plan = planKnown({ + shown: [...known.options].map((option) => option.value), + knownServers: state.knownServers, + activeServer: state.activeServer, + selected: known.value, + focused: document.activeElement === known, + switched: renderedFor !== undefined && renderedFor !== state.activeServer, + }); + deferred = plan.action === 'defer'; + if (plan.action === 'defer') return; + renderedFor = state.activeServer; + if (plan.action === 'keep') return; + const options = plan.values[0] === '' + ? [new Option('— none discovered yet —', '')] + : plan.values.map((server) => new Option(server, server, false, server === plan.selected)); + known.replaceChildren(...options); + } + + function render(state) { + latest = state; + const view = linkView(state); + details.hidden = !view.showDetails; + noServer.hidden = view.showDetails; + noServer.textContent = view.message; + degraded.hidden = !view.degraded; + if (view.showDetails) { + statusPanel.querySelector('[data-url]').textContent = view.url; + statusPanel.querySelector('[data-interval]').textContent = view.interval; + statusPanel.querySelector('[data-retention]').textContent = view.retention; + runState.textContent = view.running ? 'Running' : 'Idle'; + runState.classList.toggle('running', view.running); + } + if (!busy) setBadge(view.badge.kind, view.badge.label); + if (state.loaded) renderKnown(state); + } + + async function connect(label, action) { + if (busy) return null; + notify.clear(); + busy = true; + const focused = root.contains(document.activeElement) ? document.activeElement : null; + setBadge('checking', label); + scanBar.classList.add('active'); + controls.forEach((control) => { control.disabled = true; }); + let result = null; + try { + result = await action(); + } catch (error) { + notify.error(error); + } + busy = false; + scanBar.classList.remove('active'); + controls.forEach((control) => { control.disabled = false; }); + if (focused) focused.focus(); + if (latest) render(latest); + await resync(); + return result; + } + + ipForm.addEventListener('submit', (event) => { + event.preventDefault(); + const { ip, port } = ipForm.elements; + connect('Probing…', () => api.selectServer({ + serverIp: ip.value.trim(), + serverPort: port.value ? Number(port.value) : null, + })); + }); + + root.querySelector('[data-connect-known]').addEventListener('click', () => { + if (!known.value) { + notify.error('No server selected.'); + return; + } + connect('Connecting…', () => api.selectServer({ serverUrl: known.value })); + }); + + root.querySelector('[data-discover]').addEventListener('click', async () => { + if (busy) return; + scanNote.textContent = 'Scan in progress…'; + const found = await connect('Scanning…', api.discover); + const count = found?.length ?? 0; + scanNote.textContent = found ? `Last scan: found ${count} server${count === 1 ? '' : 's'}.` : 'Last scan: failed.'; + }); + + known.addEventListener('blur', () => { + if (deferred && latest) renderKnown(latest); + }); + + return { render }; +} diff --git a/src/main/resources/static/js/dashboard-model.js b/src/main/resources/static/js/dashboard-model.js new file mode 100644 index 0000000..37dfa0c --- /dev/null +++ b/src/main/resources/static/js/dashboard-model.js @@ -0,0 +1,96 @@ +function reachableLink(link) { + return link === 'LIVE' || link === 'DEGRADED'; +} + +export function needsPairing(state) { + return state.activeServer !== null && (state.pairing === 'REQUIRED' || state.pairing === 'REJECTED'); +} + +export function canLoadBackups(state) { + return state.loaded && state.clientReachable && state.activeServer !== null && reachableLink(state.link) && !needsPairing(state); +} + +export function emptyState() { + return { + loaded: false, + clientReachable: true, + activeServer: null, + knownServers: [], + link: 'DOWN', + running: null, + health: null, + versions: null, + pairing: 'NONE', + }; +} + +function fromSnapshot(payload) { + return { + loaded: true, + clientReachable: true, + activeServer: payload.activeServer || null, + knownServers: payload.knownServers || [], + link: payload.link || 'DOWN', + running: payload.running ?? null, + health: payload.health || null, + versions: payload.versions || null, + pairing: payload.pairing || 'PAIRED', + }; +} + +export function reduce(state, name, payload) { + if (name === 'client') { + const reachable = Boolean(payload?.reachable); + return reachable === state.clientReachable ? state : { ...state, clientReachable: reachable }; + } + if (name === 'snapshot') return fromSnapshot(payload || {}); + const base = state.clientReachable ? state : { ...state, clientReachable: true }; + if (!state.loaded) return base; + switch (name) { + case 'link': { + const link = payload.state || 'DOWN'; + return { ...base, link, running: reachableLink(link) ? base.running : null }; + } + case 'state': + return { ...base, running: Boolean(payload.running) }; + case 'run-started': + return { ...base, running: true }; + case 'run-finished': + return { ...base, running: false }; + case 'servers': + return { ...base, knownServers: payload.knownServers || [], activeServer: payload.activeServer || null }; + case 'config': + return { ...base, health: { backupInterval: payload.backupInterval, backupRetentionCount: payload.backupRetentionCount } }; + case 'versions': + return { ...base, versions: payload }; + case 'pairing': + return { ...base, pairing: payload.state || 'PAIRED' }; + default: + return base; + } +} + +export function changes(prev, next, eventName) { + const none = { serverChanged: false, clearBackups: false, refreshBackups: false }; + if (!next.loaded) return none; + const first = !prev.loaded; + const serverChanged = !first && prev.activeServer !== next.activeServer; + const up = canLoadBackups(next); + const reachedAgain = !first && ( + (!reachableLink(prev.link) && reachableLink(next.link)) + || (!prev.clientReachable && next.clientReachable) + || (needsPairing(prev) && !needsPairing(next)) + ); + const finished = prev.running === true && next.running === false; + const announced = eventName === 'backups-changed' || eventName === 'run-finished'; + return { + serverChanged, + clearBackups: serverChanged, + refreshBackups: up && (first || serverChanged || reachedAgain || finished || announced), + }; +} + +export function applyEvent(state, name, payload) { + const next = reduce(state, name, payload); + return { state: next, effects: changes(state, next, name) }; +} diff --git a/src/main/resources/static/js/events.js b/src/main/resources/static/js/events.js new file mode 100644 index 0000000..743ba7e --- /dev/null +++ b/src/main/resources/static/js/events.js @@ -0,0 +1,98 @@ +import { createReachability } from './reachability.js'; + +const EVENTS_URL = '/api/client/events'; +export const EVENT_NAMES = ['snapshot', 'link', 'state', 'run-started', 'run-finished', 'servers', 'config', 'backups-changed', 'versions', 'pairing', 'ping']; +const RETRY_MIN_MS = 2000; +const RETRY_MAX_MS = 30000; +const SILENCE_LIMIT_MS = 60000; +const SILENCE_CHECK_MS = 15000; +const RECONNECT_GRACE_MS = 8000; + +export function initEvents({ onEvent, onConnection, checkSession = async () => {} }) { + let source = null; + let retryTimer = null; + let retryDelay = RETRY_MIN_MS; + let lastMessageAt = 0; + let opened = false; + const reachability = createReachability({ graceMs: RECONNECT_GRACE_MS, onChange: onConnection }); + + function parse(event) { + try { + return JSON.parse(event.data); + } catch { + return null; + } + } + + function scheduleReopen() { + if (retryTimer) return; + retryTimer = setTimeout(() => { + retryTimer = null; + open(); + }, retryDelay); + retryDelay = Math.min(retryDelay * 2, RETRY_MAX_MS); + } + + function close() { + reachability.cancel(); + clearTimeout(retryTimer); + retryTimer = null; + if (source) source.close(); + source = null; + } + + function open() { + if (source || document.hidden) return; + const created = new EventSource(EVENTS_URL); + source = created; + lastMessageAt = Date.now(); + opened = false; + created.addEventListener('open', () => { + opened = true; + lastMessageAt = Date.now(); + retryDelay = RETRY_MIN_MS; + reachability.alive(); + }); + created.addEventListener('error', () => { + if (source !== created) return; + const closed = created.readyState === EventSource.CLOSED; + reachability.failed(closed); + if (!closed) { + opened = false; + return; + } + const neverOpened = !opened; + close(); + if (neverOpened) checkSession().catch(() => {}); + scheduleReopen(); + }); + EVENT_NAMES.forEach((name) => created.addEventListener(name, (event) => { + lastMessageAt = Date.now(); + reachability.alive(); + const payload = parse(event); + if (payload && name !== 'ping') onEvent(name, payload); + })); + } + + document.addEventListener('visibilitychange', () => { + if (document.hidden) close(); + else open(); + }); + + window.addEventListener('pageshow', (event) => { + if (event.persisted && (!source || source.readyState === EventSource.CLOSED)) { + close(); + open(); + } + }); + + setInterval(() => { + if (source && Date.now() - lastMessageAt > SILENCE_LIMIT_MS) { + close(); + reachability.failed(true); + open(); + } + }, SILENCE_CHECK_MS); + + open(); +} diff --git a/src/main/resources/static/js/format.js b/src/main/resources/static/js/format.js new file mode 100644 index 0000000..4f38ece --- /dev/null +++ b/src/main/resources/static/js/format.js @@ -0,0 +1,69 @@ +const ISO_DURATION = /^PT(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?$/i; + +export function seconds(duration) { + if (typeof duration === 'number') return duration; + const [, hours = 0, minutes = 0, secs = 0] = ISO_DURATION.exec(duration ?? '') || []; + return Number(hours) * 3600 + Number(minutes) * 60 + Number(secs); +} + +export function toDuration(minutes) { + const total = Math.round(minutes * 60); + return total % 60 === 0 ? `PT${total / 60}M` : `PT${total}S`; +} + +export const MIN_INTERVAL_SECONDS = 900; +export const MAX_INTERVAL_SECONDS = 31536000; +export const INTERVAL_MESSAGE = 'Backup interval must be between 15 minutes and 365 days'; + +export function intervalProblem(hours) { + const total = Math.round(hours * 3600); + const valid = Number.isFinite(total) && total >= MIN_INTERVAL_SECONDS && total <= MAX_INTERVAL_SECONDS; + return valid ? null : INTERVAL_MESSAGE; +} + +export const MAX_PICKUP_MINUTES = 525600; +export const PICKUP_MESSAGE = 'Pickup interval must be between 1 minute and 365 days (525600 minutes)'; + +export function pickupProblem(minutes) { + const valid = Number.isFinite(minutes) && minutes >= 1 && minutes <= MAX_PICKUP_MINUTES; + return valid ? null : PICKUP_MESSAGE; +} + +export const toHours = (duration) => Number((seconds(duration) / 3600).toFixed(4)); + +export function formatInterval(duration) { + const total = seconds(duration); + if (!total) return '—'; + if (total < 60) return `${total}s`; + const hours = Math.floor(total / 3600); + const minutes = Math.floor((total % 3600) / 60); + return [hours && `${hours}h`, minutes && `${minutes}m`].filter(Boolean).join(' '); +} + +export function bytes(size) { + if (!size) return '0 B'; + const units = ['B', 'KB', 'MB', 'GB', 'TB']; + let unit = 0; + let value = size; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit++; + } + return `${value.toFixed(unit > 0 ? 1 : 0)} ${units[unit]}`; +} + +export function relativeTime(iso) { + const time = new Date(iso).getTime(); + if (!Number.isFinite(time)) return '—'; + const elapsed = Math.max(0, Math.floor((Date.now() - time) / 1000)); + if (elapsed < 60) return `${elapsed}s ago`; + const minutes = Math.floor(elapsed / 60); + if (minutes < 60) return `${minutes}m ago`; + const hours = Math.floor(minutes / 60); + if (hours < 24) return `${hours}h ago`; + return `${Math.floor(hours / 24)}d ago`; +} + +export function percent(written, total) { + return total > 0 ? Math.max(0, Math.min(100, Math.floor((written / total) * 100))) : 0; +} diff --git a/src/main/resources/static/js/main.js b/src/main/resources/static/js/main.js new file mode 100644 index 0000000..307ea51 --- /dev/null +++ b/src/main/resources/static/js/main.js @@ -0,0 +1,149 @@ +import { initAuth } from './auth.js'; +import { initBackups } from './backups.js'; +import { initConnection } from './connection.js'; +import { applyEvent, canLoadBackups, emptyState, needsPairing } from './dashboard-model.js'; +import { initEvents } from './events.js'; +import { api, loginRequired, onPairingRequired } from './api.js'; +import { createNotifier } from './notify.js'; +import { initPairing } from './pairing.js'; +import { initPickupInterval } from './pickup-interval.js'; +import { initServerConfig } from './server-config.js'; +import { initViews } from './views.js'; +import { initVersions } from './versions.js'; + +const DASHBOARD_REFRESH_MS = 60000; + +const notify = createNotifier(document.getElementById('banner')); +const pickupInterval = initPickupInterval(document.getElementById('pickupIntervalForm'), notify); +const auth = initAuth({ + root: document.getElementById('auth'), + logoutButton: document.querySelector('[data-logout]'), + background: document.querySelectorAll('.topbar, .page'), +}); +const pairing = initPairing(document.getElementById('pairing'), notify, { resync: () => resync() }); +const serverConfig = initServerConfig(document.querySelector('[data-view="config"]'), notify); +const versions = initVersions(document.getElementById('versions')); +const backups = initBackups({ + root: document.getElementById('backups'), + actions: document.getElementById('actions'), +}, notify); +const connection = initConnection({ + root: document.getElementById('connection'), + statusPanel: document.getElementById('serverStatus'), + badge: document.getElementById('connBadge'), +}, notify, { resync: () => resync() }); + +let state = emptyState(); +let pushes = 0; +let pickupLoad = 'idle'; +let snapshots = 0; +let backupsAvailable = false; + +function loadPickupInterval() { + if (pickupLoad !== 'idle') return; + pickupLoad = 'loading'; + api.status() + .then((status) => { + pickupInterval.show(status.pickupInterval); + pickupLoad = 'done'; + }) + .catch(() => { pickupLoad = 'idle'; }); +} + +function dispatch(name, payload) { + const { state: next, effects } = applyEvent(state, name, payload); + const unchanged = next === state; + if (unchanged && !effects.refreshBackups) return; + state = next; + if (!unchanged) { + connection.render(state); + pairing.render(state); + backups.setServerRunning(state.running === true); + syncBackupsAvailability(); + if (state.loaded) versions.render(state.versions); + } + if (effects.clearBackups) backups.reset(); + if (effects.serverChanged) serverConfig.serverChanged(); + if (effects.refreshBackups) backups.refresh(); + if (state.loaded && state.clientReachable) loadPickupInterval(); +} + +function syncBackupsAvailability() { + const available = canLoadBackups(state); + backups.setPairingNeeded(needsPairing(state) && state.activeServer !== null); + if (backupsAvailable && !available) { + if (needsPairing(state)) backups.reset(); + else backups.clear(); + } + backupsAvailable = available; + backups.setAvailable(available); +} + +async function resync() { + const startedAt = pushes; + const mine = ++snapshots; + try { + const snapshot = await api.dashboard(); + if (pushes === startedAt && mine === snapshots) dispatch('snapshot', snapshot); + } catch (error) { + if (error instanceof TypeError && pushes === startedAt && mine === snapshots) dispatch('client', { reachable: false }); + } +} + +onPairingRequired(() => resync()); + +async function checkSession() { + const status = await api.authStatus(); + if (status && status.authenticated === false) loginRequired(); +} + +function refreshBackupsIfUp() { + if (canLoadBackups(state)) backups.refresh(); +} + +document.addEventListener('click', (event) => { + const button = event.target.closest('button'); + if (!button) return; + button.classList.add('clicked'); + setTimeout(() => button.classList.remove('clicked'), 140); +}); + +function start() { + initEvents({ + onEvent: (name, payload) => { + pushes++; + dispatch(name, payload); + }, + onConnection: (reachable) => dispatch('client', { reachable }), + checkSession, + }); + + let viewShown = false; + initViews((view) => { + notify.clear(); + if (view === 'config') serverConfig.load(); + else if (viewShown) { + resync(); + refreshBackupsIfUp(); + } + viewShown = true; + }); + + loadPickupInterval(); + resync(); + + setInterval(() => { + if (document.hidden) return; + resync(); + if (location.hash === '#config') return; + backups.rerender(); + }, DASHBOARD_REFRESH_MS); + + document.addEventListener('visibilitychange', () => { + if (document.hidden) return; + resync(); + if (location.hash !== '#config') refreshBackupsIfUp(); + }); +} + +if (await auth.ensureSignedIn()) start(); diff --git a/src/main/resources/static/js/notify.js b/src/main/resources/static/js/notify.js new file mode 100644 index 0000000..b77b08f --- /dev/null +++ b/src/main/resources/static/js/notify.js @@ -0,0 +1,15 @@ +export function createNotifier(banner) { + function show(message, kind) { + banner.textContent = message; + banner.className = `banner visible ${kind}`; + banner.setAttribute('aria-live', kind === 'error' ? 'assertive' : 'polite'); + if (kind !== 'ok' && banner.scrollIntoView) banner.scrollIntoView({ block: 'nearest' }); + } + + return { + ok: (message) => show(message, 'ok'), + warn: (message) => show(message, 'warn'), + error: (error) => show(error.message || String(error), 'error'), + clear: () => { banner.className = 'banner'; }, + }; +} diff --git a/src/main/resources/static/js/pairing-model.js b/src/main/resources/static/js/pairing-model.js new file mode 100644 index 0000000..dd796d7 --- /dev/null +++ b/src/main/resources/static/js/pairing-model.js @@ -0,0 +1,31 @@ +import { needsPairing } from './dashboard-model.js'; + +function reachable(link) { + return link === 'LIVE' || link === 'DEGRADED'; +} + +export function pairingPanel(state) { + if (!state.loaded || !state.clientReachable || state.activeServer === null) return 'hidden'; + if (!reachable(state.link)) return 'hidden'; + return needsPairing(state) ? 'pair' : 'manage'; +} + +export function pairingNote(state) { + if (state.pairing === 'REJECTED') { + return 'The server no longer accepts this client. Enter a pairing code from a client that is still paired. The Pairing PIN (logged by the server) works only when no client is paired, or after MEDIAGARRD_OPEN_PAIRING.'; + } + return 'Enter the Pairing PIN (shown after Finish Setup and in the server logs), or a pairing code created by a client that is already paired.'; +} + +export function credentialProblem(value) { + return String(value ?? '').trim() ? null : 'Enter the PIN or pairing code.'; +} + +export function codeView(code, now) { + if (!code) return null; + const left = Math.max(0, Math.round((Date.parse(code.expiresAt) - now) / 1000)); + if (!Number.isFinite(left) || left <= 0) return { text: code.code, expires: 'Expired' }; + const minutes = Math.floor(left / 60); + const seconds = left % 60; + return { text: code.code, expires: `Expires in ${minutes}:${String(seconds).padStart(2, '0')}` }; +} diff --git a/src/main/resources/static/js/pairing.js b/src/main/resources/static/js/pairing.js new file mode 100644 index 0000000..64cd032 --- /dev/null +++ b/src/main/resources/static/js/pairing.js @@ -0,0 +1,94 @@ +import { api } from './api.js'; +import { withBusy } from './busy.js'; +import { codeView, credentialProblem, pairingNote, pairingPanel } from './pairing-model.js'; + +export function initPairing(root, notify, { resync }) { + const pairForm = root.querySelector('[data-pair-form]'); + const manage = root.querySelector('[data-manage]'); + const note = root.querySelector('[data-pair-note]'); + const codeBox = root.querySelector('[data-code-box]'); + const codeText = root.querySelector('[data-code]'); + const codeExpiry = root.querySelector('[data-code-expiry]'); + const createCode = root.querySelector('[data-create-code]'); + const unpair = root.querySelector('[data-unpair]'); + let code = null; + let timer = null; + + function renderCode() { + const view = codeView(code, Date.now()); + codeBox.hidden = !view; + if (!view) return; + codeText.textContent = view.text; + codeExpiry.textContent = view.expires; + } + + function forgetCode() { + code = null; + clearInterval(timer); + timer = null; + renderCode(); + } + + function render(state) { + const panel = pairingPanel(state); + root.hidden = panel === 'hidden'; + pairForm.hidden = panel !== 'pair'; + manage.hidden = panel !== 'manage'; + if (panel === 'pair') note.textContent = pairingNote(state); + if (panel !== 'manage') forgetCode(); + } + + pairForm.addEventListener('submit', async (event) => { + event.preventDefault(); + const field = pairForm.elements.pin; + const problem = credentialProblem(field.value); + if (problem) { + notify.error(problem); + return; + } + notify.clear(); + await withBusy(pairForm.querySelector('button'), async () => { + try { + const result = await api.pair(field.value.trim()); + field.value = ''; + if (result?.note) notify.warn(result.note); + else notify.ok('Paired with the server'); + await resync(); + } catch (error) { + notify.error(error); + } + }); + }); + + createCode.addEventListener('click', async () => { + notify.clear(); + await withBusy(createCode, async () => { + try { + code = await api.createPairingCode(); + renderCode(); + clearInterval(timer); + timer = setInterval(renderCode, 1000); + } catch (error) { + notify.error(error); + } + }); + }); + + unpair.addEventListener('click', async () => { + if (!confirm('Unpair this client from the server? It will need a new PIN or pairing code to connect again.')) return; + notify.clear(); + await withBusy(unpair, async () => { + try { + const result = await api.unpair(); + forgetCode(); + if (result?.serverRevoked) notify.ok('Unpaired. The server no longer accepts this client.'); + else notify.warn(result?.warning || 'Unpaired locally, but the server could not be told to revoke this client. It may still list this client as paired; remove it with DELETE /api/v1/clients/{id} on the server.'); + await resync(); + } catch (error) { + notify.error(error); + } + }); + }); + + return { render }; +} diff --git a/src/main/resources/static/js/pickup-interval.js b/src/main/resources/static/js/pickup-interval.js new file mode 100644 index 0000000..6ce52e0 --- /dev/null +++ b/src/main/resources/static/js/pickup-interval.js @@ -0,0 +1,35 @@ +import { api } from './api.js'; +import { pickupProblem, seconds, toDuration } from './format.js'; + +export function initPickupInterval(form, notify) { + const minutes = form.elements.minutes; + let edited = false; + + minutes.addEventListener('input', () => { edited = true; }); + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + notify.clear(); + const problem = pickupProblem(Number(minutes.value)); + if (problem) { + notify.error(new Error(problem)); + return; + } + try { + const status = await api.updatePickupInterval(toDuration(Number(minutes.value))); + edited = false; + show(status.pickupInterval); + notify.ok('Pickup interval saved'); + } catch (error) { + notify.error(error); + } + }); + + function show(interval) { + if (edited) return; + const value = Math.round(seconds(interval) / 60); + if (value) minutes.value = value; + } + + return { show }; +} diff --git a/src/main/resources/static/js/reachability.js b/src/main/resources/static/js/reachability.js new file mode 100644 index 0000000..ad6a55e --- /dev/null +++ b/src/main/resources/static/js/reachability.js @@ -0,0 +1,29 @@ +export function createReachability({ graceMs, onChange, setTimer = setTimeout, clearTimer = clearTimeout }) { + let timer = null; + + function cancel() { + if (timer === null) return; + clearTimer(timer); + timer = null; + } + + return { + cancel, + failed(closed) { + if (closed) { + cancel(); + onChange(false); + return; + } + if (timer !== null) return; + timer = setTimer(() => { + timer = null; + onChange(false); + }, graceMs); + }, + alive() { + cancel(); + onChange(true); + }, + }; +} diff --git a/src/main/resources/static/js/server-config.js b/src/main/resources/static/js/server-config.js new file mode 100644 index 0000000..027edda --- /dev/null +++ b/src/main/resources/static/js/server-config.js @@ -0,0 +1,42 @@ +import { api } from './api.js'; +import { initServices } from './services.js'; +import { initWebhook } from './webhook.js'; +import { initSettings } from './settings.js'; +import { configUnavailableMessage } from './view-model.js'; + +export function initServerConfig(root, notify) { + const content = root.querySelector('[data-config-content]'); + const unavailable = root.querySelector('[data-unavailable]'); + const settings = initSettings(root.querySelector('#settingsForm'), notify); + const webhook = initWebhook(root.querySelector('#webhookForm'), notify); + const services = initServices(root.querySelector('#services'), notify); + + let latestLoad = 0; + + async function load() { + const mine = ++latestLoad; + try { + const [config, list] = await Promise.all([api.serverConfig(), api.listServices()]); + if (mine !== latestLoad) return; + settings.show(config); + services.show(list); + webhook.load(); + content.hidden = false; + unavailable.hidden = true; + } catch (error) { + if (mine !== latestLoad) return; + content.hidden = true; + unavailable.hidden = false; + unavailable.querySelector('[data-reason]').textContent = configUnavailableMessage(error); + } + } + + return { + load, + serverChanged() { + services.resetForm(); + webhook.reset(); + if (!root.hidden) load(); + }, + }; +} diff --git a/src/main/resources/static/js/services.js b/src/main/resources/static/js/services.js new file mode 100644 index 0000000..ebfa8e5 --- /dev/null +++ b/src/main/resources/static/js/services.js @@ -0,0 +1,106 @@ +import { api } from './api.js'; + +export function initServices(root, notify) { + const form = root.querySelector('form'); + const title = root.querySelector('[data-form-title]'); + const paths = root.querySelector('[data-paths]'); + const cancel = root.querySelector('[data-cancel]'); + const rows = root.querySelector('tbody'); + const empty = root.querySelector('[data-empty]'); + const pathTemplate = root.querySelector('#pathTemplate'); + const rowTemplate = root.querySelector('#serviceTemplate'); + let editing = null; + + function addPathInput(value = '') { + const row = pathTemplate.content.firstElementChild.cloneNode(true); + row.querySelector('input').value = value; + row.querySelector('button').addEventListener('click', () => { + row.remove(); + if (!paths.children.length) addPathInput(); + }); + paths.append(row); + } + + function resetForm() { + editing = null; + form.reset(); + paths.replaceChildren(); + addPathInput(); + title.textContent = 'Add Service'; + cancel.hidden = true; + } + + function editService(service) { + editing = service.name; + form.elements.name.value = service.name; + paths.replaceChildren(); + service.paths.forEach((path) => addPathInput(path)); + title.textContent = `Edit ${service.name}`; + cancel.hidden = false; + form.elements.name.focus(); + } + + async function removeService(service) { + if (!confirm(`Remove ${service.name}? Existing backups are kept.`)) return; + notify.clear(); + try { + await api.removeService(service.name); + if (editing === service.name) resetForm(); + } catch (error) { + notify.error(error); + return; + } + await refreshThen(`Removed ${service.name}`); + } + + async function refreshThen(message) { + try { + await refresh(); + notify.ok(message); + } catch (error) { + notify.warn(`${message}, but the list could not be refreshed: ${error.message}`); + } + } + + function renderRow(service) { + const row = rowTemplate.content.firstElementChild.cloneNode(true); + row.querySelector('[data-name]').textContent = service.name; + row.querySelector('[data-paths]').textContent = service.paths.join('\n'); + row.querySelector('[data-edit]').addEventListener('click', () => editService(service)); + row.querySelector('[data-remove]').addEventListener('click', () => removeService(service)); + return row; + } + + function show(services) { + rows.replaceChildren(...services.map(renderRow)); + empty.hidden = services.length > 0; + } + + async function refresh() { + show(await api.listServices()); + } + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + notify.clear(); + const service = { + name: form.elements.name.value, + paths: [...paths.querySelectorAll('input')].map((input) => input.value), + }; + let saved; + try { + saved = editing ? await api.updateService(editing, service) : await api.addService(service); + resetForm(); + } catch (error) { + notify.error(error); + return; + } + await refreshThen(`Saved ${saved.name}`); + }); + + root.querySelector('[data-add-path]').addEventListener('click', () => addPathInput()); + cancel.addEventListener('click', resetForm); + + resetForm(); + return { show, resetForm }; +} diff --git a/src/main/resources/static/js/settings.js b/src/main/resources/static/js/settings.js new file mode 100644 index 0000000..7602b25 --- /dev/null +++ b/src/main/resources/static/js/settings.js @@ -0,0 +1,34 @@ +import { api } from './api.js'; +import { intervalProblem, toDuration, toHours } from './format.js'; + +export function initSettings(form, notify) { + const { backupLocation, intervalHours, retentionCount } = form.elements; + + function show(config) { + backupLocation.value = config.backupLocation; + intervalHours.value = toHours(config.backupInterval); + retentionCount.value = config.retentionCount; + } + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + notify.clear(); + const problem = intervalProblem(Number(intervalHours.value)); + if (problem) { + notify.error(new Error(problem)); + return; + } + try { + show(await api.updateServerConfig({ + backupLocation: backupLocation.value, + retentionCount: Number(retentionCount.value), + backupInterval: toDuration(Number(intervalHours.value) * 60), + })); + notify.ok('Backup settings saved'); + } catch (error) { + notify.error(error); + } + }); + + return { show }; +} diff --git a/src/main/resources/static/js/versions.js b/src/main/resources/static/js/versions.js new file mode 100644 index 0000000..202fc32 --- /dev/null +++ b/src/main/resources/static/js/versions.js @@ -0,0 +1,27 @@ +import { versionsView } from './view-model.js'; + +export function initVersions(root) { + const rows = { + server: root.querySelector('[data-row="server"]'), + client: root.querySelector('[data-row="client"]'), + }; + + function renderRow(row, view) { + const link = row.querySelector('[data-link]'); + row.classList.remove('current', 'outdated', 'unknown', 'checking'); + row.classList.add(view.kind); + row.querySelector('[data-version]').textContent = view.version; + row.querySelector('[data-state]').textContent = view.label; + link.hidden = !view.href; + if (view.href) link.href = view.href; + else link.removeAttribute('href'); + } + + return { + render(versions) { + const view = versionsView(versions); + renderRow(rows.server, view.server); + renderRow(rows.client, view.client); + }, + }; +} diff --git a/src/main/resources/static/js/view-model.js b/src/main/resources/static/js/view-model.js new file mode 100644 index 0000000..f7057cf --- /dev/null +++ b/src/main/resources/static/js/view-model.js @@ -0,0 +1,94 @@ +import { needsPairing } from './dashboard-model.js'; +import { formatInterval } from './format.js'; + +const RELEASE_URL = /^https?:\/\//; + +export function listingError(error, connected) { + const message = /[.!?]$/.test(error.message) ? error.message : `${error.message}.`; + return connected ? message : `${message} Connect to a server to view archives.`; +} + +export function configUnavailableMessage(error) { + if (error?.pairing === 'required') { + return 'Pair this client with the server on the Dashboard to manage its configuration.'; + } + const message = /[.!?]$/.test(error.message) ? error.message : `${error.message}.`; + return `${message} Connect to a MediaGarrd server that has finished setup on the Dashboard to manage its configuration.`; +} + +export function linkView(state) { + const none = { showDetails: false, url: '', interval: '—', retention: '—', running: false, degraded: false }; + if (!state.clientReachable) { + return { ...none, badge: { kind: 'down', label: 'Client unreachable' }, message: 'Client unreachable. Retrying…' }; + } + if (!state.loaded) { + return { ...none, badge: { kind: 'checking', label: 'Connecting…' }, message: 'Connecting…' }; + } + if (!state.activeServer) { + return { ...none, badge: { kind: '', label: 'Not Connected' }, message: 'No server connected.' }; + } + if (state.link === 'CONNECTING') { + return { ...none, badge: { kind: 'checking', label: 'Connecting…' }, message: `Connecting to ${state.activeServer}…` }; + } + if (state.link === 'DOWN') { + return { ...none, badge: { kind: 'down', label: 'Unreachable' }, message: `${state.activeServer} is not responding.` }; + } + if (needsPairing(state)) { + const message = state.pairing === 'REJECTED' + ? `${state.activeServer} rejected this client's token. Pair again to continue.` + : `This client is not paired with ${state.activeServer}.`; + return { ...none, badge: { kind: 'down', label: 'Pairing required' }, message }; + } + return { + badge: { kind: state.link === 'DEGRADED' ? 'degraded' : 'ok', label: state.activeServer.replace(/^https?:\/\//, '') }, + message: '', + showDetails: true, + url: state.activeServer, + interval: state.health ? formatInterval(state.health.backupInterval) : '—', + retention: state.health ? `${state.health.backupRetentionCount} archives` : '—', + running: state.running === true, + degraded: state.link === 'DEGRADED', + }; +} + +export function planKnown({ shown, knownServers, activeServer, selected, focused, switched }) { + const values = knownServers.length ? knownServers : ['']; + if (!switched) { + const unchanged = values.length === shown.length && values.every((value, index) => shown[index] === value); + if (unchanged) return { action: 'keep' }; + if (focused) return { action: 'defer' }; + } + const keep = !switched && knownServers.includes(selected); + return { action: 'render', values, selected: keep ? selected : activeServer }; +} + +export function classifyVersion(status) { + if (status?.updateAvailable) return 'outdated'; + if (status?.checkState === 'NOT_CHECKED') return 'checking'; + if (status?.checkState === 'OK' || status?.checkState === 'NO_RELEASES') return 'current'; + return 'unknown'; +} + +export function versionRowView(status, missingText) { + const kind = classifyVersion(status); + const label = { + current: 'Up-to-date', + outdated: `Update available: v${status?.latestVersion}`, + checking: 'Checking…', + unknown: status ? 'Unable to check' : missingText, + }[kind]; + const showLink = kind === 'outdated' && RELEASE_URL.test(status.releaseUrl || ''); + return { + kind, + label, + version: status?.currentVersion ? `v${status.currentVersion}` : '—', + href: showLink ? status.releaseUrl : null, + }; +} + +export function versionsView(versions) { + return { + server: versionRowView(versions?.server, versions ? 'No server connected' : 'Unable to check'), + client: versionRowView(versions?.client, 'Unable to check'), + }; +} diff --git a/src/main/resources/static/js/views.js b/src/main/resources/static/js/views.js new file mode 100644 index 0000000..18bd5db --- /dev/null +++ b/src/main/resources/static/js/views.js @@ -0,0 +1,17 @@ +export function initViews(onShow) { + const views = document.querySelectorAll('[data-view]'); + const links = document.querySelectorAll('[data-view-link]'); + + function show() { + const current = location.hash === '#config' ? 'config' : 'dashboard'; + views.forEach((view) => { view.hidden = view.dataset.view !== current; }); + links.forEach((link) => link.setAttribute('aria-pressed', String(link.dataset.viewLink === current))); + onShow(current); + } + + links.forEach((link) => link.addEventListener('click', () => { + location.hash = link.dataset.viewLink === 'config' ? 'config' : ''; + })); + window.addEventListener('hashchange', show); + show(); +} diff --git a/src/main/resources/static/js/webhook.js b/src/main/resources/static/js/webhook.js new file mode 100644 index 0000000..77fed6b --- /dev/null +++ b/src/main/resources/static/js/webhook.js @@ -0,0 +1,103 @@ +import { api } from './api.js'; +import { withBusy } from './busy.js'; + +export function describeStatus(status) { + return status && status.configured ? `Configured: ${status.target}` : 'Not configured'; +} + +export function describeTest(result) { + if (result && result.delivered) return { ok: true, message: 'Test message delivered' }; + const reason = result && result.error ? result.error : 'no reason given'; + return { ok: false, message: `Test message was not delivered: ${reason}` }; +} + +export function initWebhook(form, notify) { + const { url } = form.elements; + const label = form.querySelector('[data-webhook-status]'); + const testButton = form.querySelector('[data-webhook-test]'); + const clearButton = form.querySelector('[data-webhook-clear]'); + const saveButton = form.querySelector('button[type="submit"]'); + let latest = 0; + + function show(status) { + label.textContent = describeStatus(status); + url.value = ''; + } + + async function load() { + const mine = ++latest; + label.textContent = 'Checking…'; + try { + const status = await api.webhook(); + if (mine === latest) label.textContent = describeStatus(status); + } catch (error) { + if (mine === latest) label.textContent = `Unavailable: ${error.message}`; + } + } + + function reset() { + latest++; + url.value = ''; + label.textContent = 'Checking…'; + } + + async function save(value) { + const mine = latest; + const status = await api.updateWebhook(value); + if (mine === latest) show(status); + } + + async function exclusive(button, task) { + const others = [saveButton, testButton, clearButton].filter((other) => other !== button); + if (others.some((other) => other.disabled)) return; + others.forEach((other) => { other.disabled = true; }); + try { + await withBusy(button, task); + } finally { + others.forEach((other) => { other.disabled = false; }); + } + } + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + notify.clear(); + const value = url.value.trim(); + if (!value) { + notify.error(new Error('Enter a webhook URL, or use Clear to turn notifications off')); + return; + } + await exclusive(saveButton, async () => { + try { + await save(value); + notify.ok('Webhook saved'); + } catch (error) { + notify.error(error); + } + }); + }); + + clearButton.addEventListener('click', () => exclusive(clearButton, async () => { + notify.clear(); + try { + await save(''); + notify.ok('Webhook cleared'); + } catch (error) { + notify.error(error); + } + })); + + testButton.addEventListener('click', () => exclusive(testButton, async () => { + notify.clear(); + try { + const typed = url.value.trim(); + if (typed) await save(typed); + const outcome = describeTest(await api.testWebhook()); + if (outcome.ok) notify.ok(outcome.message); + else notify.error(new Error(outcome.message)); + } catch (error) { + notify.error(error); + } + })); + + return { load, reset, show }; +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandlerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandlerTest.java new file mode 100644 index 0000000..8ae3b77 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandlerTest.java @@ -0,0 +1,130 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import wellatleastitried.mediagarrdclient.service.ConflictException; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; +import wellatleastitried.mediagarrdclient.service.NotFoundException; +import wellatleastitried.mediagarrdclient.service.UpstreamResponseException; + +class ApiExceptionHandlerTest { + + private final ApiExceptionHandler handler = new ApiExceptionHandler(); + + @Test + void anUnexpectedFailureAnswersWithAGenericMessageInsteadOfItsDetails() { + var response = handler.failed(new IllegalStateException("Failed to save client state to /var/lib/mediagarrd/client/state.json")); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertEquals(Map.of("error", "Internal error"), response.getBody()); + } + + @Test + void aRejectedRequestKeepsItsMessage() { + var response = handler.invalid(new InvalidRequestException("PIN must be 6 digits")); + + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertEquals(Map.of("error", "PIN must be 6 digits"), response.getBody()); + } + + @Test + void anIllegalArgumentIsNotMistakenForARejectedRequest() { + var response = handler.failed(new IllegalArgumentException("/var/lib/mediagarrd is not a directory")); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertEquals(Map.of("error", "Internal error"), response.getBody()); + } + + @Test + void notFoundAndConflictKeepTheirMessagesAndStatuses() { + var missing = handler.notFound(new NotFoundException("Backup not found: b9")); + var conflict = handler.conflict(new ConflictException("A password is already set")); + + assertEquals(HttpStatus.NOT_FOUND, missing.getStatusCode()); + assertEquals(Map.of("error", "Backup not found: b9"), missing.getBody()); + assertEquals(HttpStatus.CONFLICT, conflict.getStatusCode()); + assertEquals(Map.of("error", "A password is already set"), conflict.getBody()); + } + + @Test + void aSpringErrorResponseKeepsItsClientStatusAndDetail() { + var response = handler.failed(new ResponseStatusException(HttpStatus.NOT_FOUND, "Pickup task not found: gone")); + + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertEquals(Map.of("error", "Pickup task not found: gone"), response.getBody()); + } + + @Test + void aSpringServerErrorResponseBecomesTheGenericBody() { + var response = handler.failed(new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "/etc/secret is missing")); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertEquals(Map.of("error", "Internal error"), response.getBody()); + } + + @Test + void aServerFailureIsNotReflectedBack() { + var response = handler.serverRejected(new org.springframework.web.client.HttpServerErrorException( + HttpStatus.INTERNAL_SERVER_ERROR, "Internal Server Error", "{\"error\":\"Disk /srv/backups is full\"}".getBytes(), java.nio.charset.StandardCharsets.UTF_8)); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertEquals(Map.of("error", "MediaGarrd server responded with 500"), response.getBody()); + } + + @Test + void anUnusableServerReplyIsABadGateway() { + var response = handler.upstreamInvalid(new UpstreamResponseException("The server did not return a token")); + + assertEquals(HttpStatus.BAD_GATEWAY, response.getStatusCode()); + assertEquals(Map.of("error", "The server did not return a token"), response.getBody()); + } + + private static org.springframework.web.client.HttpClientErrorException tooManyRequests(String retryAfter, String body) { + org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders(); + if (retryAfter != null) { + headers.add("Retry-After", retryAfter); + } + var e = org.springframework.web.client.HttpClientErrorException.create( + HttpStatus.TOO_MANY_REQUESTS, "Too Many Requests", headers, new byte[0], java.nio.charset.StandardCharsets.UTF_8); + e.setBodyConvertFunction(type -> new ApiExceptionHandler.ServerError(body)); + return e; + } + + @Test + void aProxiedTooManyRequestsKeepsItsRetryAfterAndMessage() { + var response = handler.serverRejected(tooManyRequests("7", "Wait 7 seconds before sending another test")); + + assertEquals(HttpStatus.TOO_MANY_REQUESTS, response.getStatusCode()); + assertEquals("7", response.getHeaders().getFirst("Retry-After")); + assertEquals(Map.of("error", "Wait 7 seconds before sending another test"), response.getBody()); + } + + @Test + void aProxiedTooManyRequestsWithoutAUsableRetryAfterHasNone() { + var missing = handler.serverRejected(tooManyRequests(null, "Slow down")); + var odd = handler.serverRejected(tooManyRequests("soon\r\nX-Evil: 1", "Slow down")); + + assertEquals(HttpStatus.TOO_MANY_REQUESTS, missing.getStatusCode()); + assertEquals(null, missing.getHeaders().getFirst("Retry-After")); + assertEquals(null, odd.getHeaders().getFirst("Retry-After")); + assertEquals(Map.of("error", "Slow down"), odd.getBody()); + } + + @Test + void otherProxiedRejectionsGetNoRetryAfter() { + var rejected = org.springframework.web.client.HttpClientErrorException.create( + HttpStatus.BAD_REQUEST, "Bad Request", new org.springframework.http.HttpHeaders(), new byte[0], java.nio.charset.StandardCharsets.UTF_8); + rejected.setBodyConvertFunction(type -> new ApiExceptionHandler.ServerError("Webhook URL must use http or https")); + var response = handler.serverRejected(rejected); + + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertEquals(null, response.getHeaders().getFirst("Retry-After")); + assertEquals(Map.of("error", "Webhook URL must use http or https"), response.getBody()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/AuthControllerConcurrencyTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/AuthControllerConcurrencyTest.java new file mode 100644 index 0000000..21fb808 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/AuthControllerConcurrencyTest.java @@ -0,0 +1,151 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +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.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockHttpServletRequest; + +import wellatleastitried.mediagarrdclient.dto.PasswordRequest; +import wellatleastitried.mediagarrdclient.service.LoginAttempts; +import wellatleastitried.mediagarrdclient.service.PasswordService; +import wellatleastitried.mediagarrdclient.service.SessionService; + +@Timeout(30) +class AuthControllerConcurrencyTest { + + private static MockHttpServletRequest from(String address) { + MockHttpServletRequest request = new MockHttpServletRequest("POST", "/api/auth/login"); + request.setRemoteAddr(address); + return request; + } + + @Test + void parallelWrongLoginsFromOneSourceReachThePasswordCheckAtMostOnce() throws Exception { + PasswordService passwords = mock(PasswordService.class); + when(passwords.isConfigured()).thenReturn(true); + AtomicInteger checks = new AtomicInteger(); + CountDownLatch inside = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(passwords.matches(any())).thenAnswer(call -> { + checks.incrementAndGet(); + inside.countDown(); + release.await(10, TimeUnit.SECONDS); + return false; + }); + AuthController controller = new AuthController(passwords, new SessionService(), new LoginAttempts()); + ExecutorService pool = Executors.newFixedThreadPool(8); + List> results = new ArrayList<>(); + CountDownLatch refused = new CountDownLatch(7); + for (int i = 0; i < 8; i++) { + results.add(pool.submit(() -> { + int status = controller.login(new PasswordRequest("guess"), from("10.2.0.1")).getStatusCode().value(); + if (status == 429) { + refused.countDown(); + } + return status; + })); + } + assertTrue(inside.await(10, TimeUnit.SECONDS)); + assertTrue(refused.await(10, TimeUnit.SECONDS)); + release.countDown(); + List statuses = new ArrayList<>(); + for (Future result : results) { + statuses.add(result.get(10, TimeUnit.SECONDS)); + } + pool.shutdownNow(); + + assertEquals(1, checks.get()); + assertEquals(1, statuses.stream().filter(status -> status == 401).count()); + assertEquals(7, statuses.stream().filter(status -> status == 429).count()); + } + + @Test + void onlyAFewPasswordChecksRunAtOnceAcrossSources() throws Exception { + PasswordService passwords = mock(PasswordService.class); + when(passwords.isConfigured()).thenReturn(true); + AtomicInteger running = new AtomicInteger(); + AtomicInteger peak = new AtomicInteger(); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch started = new CountDownLatch(3); + when(passwords.matches(any())).thenAnswer(call -> { + peak.accumulateAndGet(running.incrementAndGet(), Math::max); + started.countDown(); + release.await(10, TimeUnit.SECONDS); + running.decrementAndGet(); + return false; + }); + AuthController controller = new AuthController(passwords, new SessionService(), new LoginAttempts()); + ExecutorService pool = Executors.newFixedThreadPool(10); + List> results = new ArrayList<>(); + CountDownLatch refused = new CountDownLatch(7); + for (int i = 0; i < 10; i++) { + String source = "10.3.0." + i; + results.add(pool.submit(() -> { + int status = controller.login(new PasswordRequest("guess"), from(source)).getStatusCode().value(); + if (status == 429) { + refused.countDown(); + } + return status; + })); + } + assertTrue(started.await(10, TimeUnit.SECONDS)); + assertTrue(refused.await(10, TimeUnit.SECONDS)); + release.countDown(); + long refusedCount = 0; + for (Future result : results) { + if (result.get(10, TimeUnit.SECONDS) == 429) { + refusedCount++; + } + } + pool.shutdownNow(); + + assertEquals(3, peak.get()); + assertEquals(7, refusedCount); + } + + @Test + void anErrorFromThePasswordCheckReleasesTheSourceSoItCanTryAgain() { + PasswordService passwords = mock(PasswordService.class); + when(passwords.isConfigured()).thenReturn(true); + when(passwords.matches(any())).thenThrow(new StackOverflowError()).thenReturn(true); + AuthController controller = new AuthController(passwords, new SessionService(), new LoginAttempts()); + + assertThrows(StackOverflowError.class, () -> controller.login(new PasswordRequest("guess"), from("10.4.0.1"))); + + assertEquals(200, controller.login(new PasswordRequest("guess"), from("10.4.0.1")).getStatusCode().value()); + } + + @Test + void aFinishedLoginDoesNotReleaseTheReservationOfTheNextAttemptFromTheSameSource() { + PasswordService passwords = mock(PasswordService.class); + when(passwords.isConfigured()).thenReturn(true); + when(passwords.matches(any())).thenReturn(true); + LoginAttempts attempts = new LoginAttempts(); + SessionService sessions = mock(SessionService.class); + when(sessions.create()).thenAnswer(call -> { + assertTrue(attempts.tryBegin("10.4.0.2").isEmpty()); + return "token"; + }); + AuthController controller = new AuthController(passwords, sessions, attempts); + + assertEquals(200, controller.login(new PasswordRequest("guess"), from("10.4.0.2")).getStatusCode().value()); + + assertTrue(attempts.tryBegin("10.4.0.2").isPresent()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/AuthGateFullContextTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/AuthGateFullContextTest.java new file mode 100644 index 0000000..ee9937a --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/AuthGateFullContextTest.java @@ -0,0 +1,333 @@ +package wellatleastitried.mediagarrdclient.api; + +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.assertTrue; +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.request.MockMvcRequestBuilders.request; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; +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.net.URI; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +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.web.method.HandlerMethod; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import jakarta.servlet.http.Cookie; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; + +@SpringBootTest +@org.springframework.context.annotation.Import(wellatleastitried.mediagarrdclient.api.TestCsrfHeader.class) +@AutoConfigureMockMvc +class AuthGateFullContextTest { + + private static final String PASSWORD = "correct horse battery"; + + @TempDir + static Path dataDir; + + @Autowired + MockMvc mockMvc; + + @Autowired + MediaGarrdProperties configuration; + + @Autowired + @Qualifier("requestMappingHandlerMapping") + RequestMappingHandlerMapping mappings; + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) { + registry.add("mediagarrd.client.state-file", () -> dataDir.resolve("state.json").toString()); + registry.add("mediagarrd.client.download-directory", () -> dataDir.resolve("downloads").toString()); + registry.add("mediagarrd.client.preferred-server-ip", () -> ""); + registry.add("mediagarrd.client.github-api-base-url", () -> "http://127.0.0.1:1"); + registry.add("mediagarrd.client.password", () -> PASSWORD); + } + + private static String loginBody(String password) { + return "{\"password\":\"" + password + "\"}"; + } + + private MvcResult login(String source, String password) throws Exception { + return mockMvc.perform(post("/api/auth/login") + .with(request -> { + request.setRemoteAddr(source); + return request; + }) + .contentType(MediaType.APPLICATION_JSON) + .content(loginBody(password))) + .andReturn(); + } + + private Cookie signIn(String source) throws Exception { + MvcResult result = login(source, PASSWORD); + assertEquals(200, result.getResponse().getStatus()); + return result.getResponse().getCookie("mg_session"); + } + + @Test + void everyRegisteredHandlerRefusesARequestWithoutASessionExceptTheAuthEndpoints() throws Exception { + Set checkedPublic = new TreeSet<>(); + Set checkedProtected = new TreeSet<>(); + for (var entry : mappings.getHandlerMethods().entrySet()) { + RequestMappingInfo info = entry.getKey(); + HandlerMethod handler = entry.getValue(); + boolean open = handler.hasMethodAnnotation(PublicEndpoint.class); + Set methods = info.getMethodsCondition().getMethods(); + for (String pattern : info.getPathPatternsCondition().getPatternValues()) { + for (HttpMethod method : methods.isEmpty() ? List.of(HttpMethod.GET) : methods.stream().map(m -> HttpMethod.valueOf(m.name())).toList()) { + String path = pattern.replaceAll("\\{[^/}]+}", "x"); + MvcResult result = mockMvc.perform(request(method, URI.create(path)) + .contentType(MediaType.APPLICATION_JSON) + .content("{}")) + .andReturn(); + String label = method + " " + path; + if (open) { + assertFalse(result.getResponse().getContentAsString().contains("\"login\":\"required\""), label + " should be reachable without a session"); + checkedPublic.add(label); + } else { + assertEquals(401, result.getResponse().getStatus(), label + " should require a session"); + assertTrue(result.getResponse().getContentAsString().contains("\"login\":\"required\""), label); + checkedProtected.add(label); + } + } + } + } + + assertEquals(Set.of("GET /api/auth/status", "POST /api/auth/login", "POST /api/auth/set-password", "POST /api/auth/logout"), checkedPublic); + assertTrue(checkedProtected.contains("GET /api/client/events"), checkedProtected.toString()); + assertTrue(checkedProtected.contains("POST /api/client/pairing"), checkedProtected.toString()); + assertTrue(checkedProtected.contains("GET /api/client/dashboard"), checkedProtected.toString()); + assertTrue(checkedProtected.stream().noneMatch(label -> label.contains("/api/auth/")), checkedProtected.toString()); + } + + @Test + void pathVariantsOfAProtectedEndpointNeverBypassTheGate() throws Exception { + List variants = new ArrayList<>(List.of( + "/api/client/status;x", + "/api/client/status;jsessionid=1", + "/api/client/%73tatus", + "/api/client/status/", + "//api/client/status", + "///api/client/status", + "/api/client/./status", + "/api/client/%2e/status", + "/api/client/x/../status", + "/api/client/status%2f", + "/api/client/status%3bx", + "/API/CLIENT/STATUS", + "/api;x/client/status", + "/api/client;x/status", + "/api/client/status.json", + "/api/client/status?x=1")); + for (String variant : variants) { + MvcResult result = mockMvc.perform(get(URI.create(variant))).andReturn(); + int status = result.getResponse().getStatus(); + assertFalse(status / 100 == 2, variant + " answered " + status + " without a session"); + assertFalse(result.getResponse().getContentAsString().contains("activeServer"), variant); + } + } + + @Test + void aMatrixParameterVariantReachesTheHandlerSoTheGateReallyDecidedIt() throws Exception { + Cookie cookie = signIn("10.1.0.1"); + + mockMvc.perform(get(URI.create("/api/client/status;x")).cookie(cookie)).andExpect(status().isOk()); + mockMvc.perform(get(URI.create("/api/client/status;x"))).andExpect(status().isUnauthorized()); + } + + @Test + void theWebPageAndItsAssetsAreServedWithoutASession() throws Exception { + mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(forwardedUrl("index.html")); + mockMvc.perform(get("/index.html")).andExpect(status().isOk()); + mockMvc.perform(get("/js/main.js")).andExpect(status().isOk()); + mockMvc.perform(get("/js/auth.js")).andExpect(status().isOk()); + mockMvc.perform(get("/css/mediagarrd.css")) + .andExpect(status().isOk()) + .andExpect(header().string("Cache-Control", "no-store")); + } + + @Test + void bindsTheBackupRunTimeoutDefault() { + assertEquals(Duration.ofHours(6), configuration.getBackupRunTimeout()); + } + + @Test + void reportsStatusWithoutAServer() throws Exception { + mockMvc.perform(get("/api/client/status").cookie(signIn("10.1.0.21"))) + .andExpect(status().isOk()) + .andExpect(content().json("{\"activeServer\":null,\"knownServers\":[]}")); + } + + @Test + void reportsTheDashboardWithTheClientVersionAndNoServer() throws Exception { + mockMvc.perform(get("/api/client/dashboard").cookie(signIn("10.1.0.22"))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.link").value("DOWN")) + .andExpect(jsonPath("$.activeServer").doesNotExist()) + .andExpect(jsonPath("$.versions.client.checkState").exists()) + .andExpect(jsonPath("$.versions.server").doesNotExist()) + .andExpect(jsonPath("$.pairing").value("NONE")); + } + + @Test + void reportsWhetherThePasswordIsSetAndWhoComesFromTheEnvironment() throws Exception { + mockMvc.perform(get("/api/auth/status")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.passwordSet").value(true)) + .andExpect(jsonPath("$.passwordFromEnvironment").value(true)) + .andExpect(jsonPath("$.authenticated").value(false)); + mockMvc.perform(get("/api/auth/status").cookie(signIn("10.1.0.2"))) + .andExpect(jsonPath("$.authenticated").value(true)); + } + + @Test + void aWrongPasswordIsRefusedWithoutTheLoginRequiredMarker() throws Exception { + MvcResult result = login("10.1.0.3", "wrong password"); + + assertEquals(401, result.getResponse().getStatus()); + assertEquals("{\"error\":\"Incorrect password\"}", result.getResponse().getContentAsString()); + assertEquals(null, result.getResponse().getCookie("mg_session")); + } + + @Test + void theSessionCookieIsHttpOnlySameSiteStrictAndSecureOnlyOverHttps() throws Exception { + String plain = login("10.1.0.4", PASSWORD).getResponse().getHeader("Set-Cookie"); + String forwarded = mockMvc.perform(post("/api/auth/login") + .with(request -> { + request.setRemoteAddr("10.1.0.5"); + return request; + }) + .header("X-Forwarded-Proto", "https") + .contentType(MediaType.APPLICATION_JSON) + .content(loginBody(PASSWORD))) + .andReturn().getResponse().getHeader("Set-Cookie"); + String direct = mockMvc.perform(post("/api/auth/login") + .with(request -> { + request.setRemoteAddr("10.1.0.6"); + request.setSecure(true); + return request; + }) + .contentType(MediaType.APPLICATION_JSON) + .content(loginBody(PASSWORD))) + .andReturn().getResponse().getHeader("Set-Cookie"); + + assertNotNull(plain); + assertTrue(plain.contains("HttpOnly") && plain.contains("SameSite=Strict") && plain.contains("Path=/"), plain); + assertFalse(plain.contains("Secure"), plain); + assertTrue(forwarded.contains("Secure") && forwarded.contains("HttpOnly") && forwarded.contains("SameSite=Strict"), forwarded); + assertTrue(direct.contains("Secure"), direct); + } + + @Test + void repeatedFailuresLockTheSourceOutWithA429EvenForTheRightPassword() throws Exception { + for (int i = 0; i < 4; i++) { + assertEquals(401, login("10.1.0.7", "wrong password " + i).getResponse().getStatus()); + } + + MvcResult locked = login("10.1.0.7", PASSWORD); + + assertEquals(429, locked.getResponse().getStatus()); + assertNotNull(locked.getResponse().getHeader("Retry-After")); + assertTrue(locked.getResponse().getContentAsString().contains("\"error\"")); + assertEquals(200, login("10.1.0.8", PASSWORD).getResponse().getStatus()); + } + + @Test + void aPasswordCannotBeSetWhileClientPasswordIsConfigured() throws Exception { + mockMvc.perform(post("/api/auth/set-password").contentType(MediaType.APPLICATION_JSON).content(loginBody("another password"))) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error").exists()); + } + + @Test + void loggingOutEndsTheSession() throws Exception { + Cookie cookie = signIn("10.1.0.9"); + mockMvc.perform(get("/api/client/status").cookie(cookie)).andExpect(status().isOk()); + + MvcResult logout = mockMvc.perform(post("/api/auth/logout").cookie(cookie)).andExpect(status().isNoContent()).andReturn(); + + assertTrue(logout.getResponse().getHeader("Set-Cookie").contains("Max-Age=0")); + mockMvc.perform(get("/api/client/status").cookie(cookie)).andExpect(status().isUnauthorized()); + } + + @Test + void crossSiteWritesAreRefusedEvenWithAValidSession() throws Exception { + Cookie cookie = signIn("10.1.0.10"); + + mockMvc.perform(put("/api/client/pickup-interval").cookie(cookie).header("Origin", "http://evil.example.com").header("Host", "client.local:8081") + .contentType(MediaType.APPLICATION_JSON).content("{\"interval\":\"PT1H\"}")) + .andExpect(status().isForbidden()); + mockMvc.perform(post("/api/client/pairing").cookie(cookie).header("Sec-Fetch-Site", "cross-site") + .contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"123456\"}")) + .andExpect(status().isForbidden()); + mockMvc.perform(post("/api/auth/login").header("Origin", "http://evil.example.com").header("Host", "client.local:8081") + .contentType(MediaType.APPLICATION_JSON).content(loginBody(PASSWORD))) + .andExpect(status().isForbidden()); + } + + @Test + void aWriteWithNeitherBrowserHeadersNorTheCustomHeaderIsRefused() throws Exception { + Cookie cookie = signIn("10.1.0.12"); + + mockMvc.perform(post("/api/client/pairing").cookie(cookie) + .with(request -> { + request.removeHeader("X-MediaGarrd-Request"); + return request; + }) + .contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"\"}")) + .andExpect(status().isForbidden()); + } + + @Test + void sameOriginWritesAreAccepted() throws Exception { + Cookie cookie = signIn("10.1.0.11"); + + mockMvc.perform(post("/api/client/pairing").cookie(cookie).header("Origin", "http://client.local:8081").header("Host", "client.local:8081") + .contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").exists()); + } + + @Test + void everyResponseForbidsFraming() throws Exception { + for (String path : List.of("/", "/index.html", "/api/auth/status", "/api/client/status", "/no-such-page.html")) { + mockMvc.perform(get(path)) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header().string("X-Frame-Options", "DENY")) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header().string("Content-Security-Policy", SecurityHeadersFilter.CONTENT_SECURITY_POLICY)) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header().string("X-Content-Type-Options", "nosniff")) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header().string("Referrer-Policy", "no-referrer")); + } + for (String path : List.of("/api/auth/status", "/api/client/status")) { + mockMvc.perform(get(path)) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header().string("Cache-Control", "no-store")); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientApiGoldenTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientApiGoldenTest.java new file mode 100644 index 0000000..88e0b2e --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientApiGoldenTest.java @@ -0,0 +1,251 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +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 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.context.annotation.Import; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.json.JsonCompareMode; +import org.springframework.test.web.servlet.MockMvc; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; + +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.DashboardState; +import wellatleastitried.mediagarrdclient.dto.HealthSummary; +import wellatleastitried.mediagarrdclient.dto.LinkState; +import wellatleastitried.mediagarrdclient.dto.PairingCodeDto; +import wellatleastitried.mediagarrdclient.dto.PairingResultDto; +import wellatleastitried.mediagarrdclient.dto.PairingState; +import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; +import wellatleastitried.mediagarrdclient.dto.PickupStartDto; +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.dto.UnpairResultDto; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; +import wellatleastitried.mediagarrdclient.dto.VersionsDto; +import wellatleastitried.mediagarrdclient.dto.WebhookStatusDto; +import wellatleastitried.mediagarrdclient.dto.WebhookTestDto; +import wellatleastitried.mediagarrdclient.golden.Fixtures; +import wellatleastitried.mediagarrdclient.service.BackupPickupService; +import wellatleastitried.mediagarrdclient.service.ClientPairingService; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.DashboardService; +import wellatleastitried.mediagarrdclient.service.LoginAttempts; +import wellatleastitried.mediagarrdclient.service.PasswordService; +import wellatleastitried.mediagarrdclient.service.ServerApiService; +import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; +import wellatleastitried.mediagarrdclient.service.ServerSelectionService; + +@WebMvcTest(controllers = {ClientController.class, PairingController.class, ServerConfigController.class, WebhookController.class, AuthController.class}) +@Import({TestSession.class, ServerSelectionService.class}) +class ClientApiGoldenTest { + + private static final String SERVER = "http://192.168.1.20:38471"; + private static final Instant INSTANT = Instant.parse("2026-11-20T10:15:30.123456Z"); + + @Autowired + MockMvc mockMvc; + + @MockitoBean + ClientStateService stateService; + + @MockitoBean + ServerDiscoveryService discoveryService; + + @MockitoBean + ServerApiService serverApiService; + + @MockitoBean + BackupPickupService backupPickupService; + + @MockitoBean + DashboardService dashboardService; + + @MockitoBean + ClientPairingService pairing; + + @MockitoBean + PasswordService passwords; + + @MockitoBean + LoginAttempts attempts; + + @Test + void statusJson() throws Exception { + when(stateService.getActiveServer()).thenReturn(SERVER); + when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(90)); + when(stateService.getKnownServers()).thenReturn(List.of(SERVER, "https://backup.example.net:38471")); + + mockMvc.perform(get("/api/client/status")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/status.json"), JsonCompareMode.STRICT)); + } + + @Test + void dashboardJson() throws Exception { + VersionStatusDto client = new VersionStatusDto("0.1.0", "0.1.0", "https://github.com/MediaGarrd/Client/releases/tag/v0.1.0", false, CheckState.OK, INSTANT, null); + when(dashboardService.state()).thenReturn(new DashboardState(SERVER, List.of(SERVER), LinkState.LIVE, false, + new HealthSummary(Duration.ofHours(6), 7), new VersionsDto(client, null), PairingState.PAIRED)); + + mockMvc.perform(get("/api/client/dashboard")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/dashboard.json"), JsonCompareMode.STRICT)); + } + + @Test + void backupsJson() throws Exception { + when(stateService.requireActiveServer()).thenReturn(SERVER); + when(serverApiService.listBackups(SERVER)).thenReturn(List.of(new BackupDto("backup-2026-11-20", "mediagarrd-2026-11-20.zip", 1048576L, INSTANT))); + + mockMvc.perform(get("/api/client/backups")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/backups.json"), JsonCompareMode.STRICT)); + } + + @Test + void serverConfigJson() throws Exception { + when(stateService.requireActiveServer()).thenReturn(SERVER); + when(serverApiService.serverConfig(SERVER)).thenReturn(new ServerConfigDto("/var/backups/mediagarrd", 7, Duration.ofHours(6))); + + mockMvc.perform(get("/api/client/server-config")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/server-config.json"), JsonCompareMode.STRICT)); + } + + @Test + void webhookJson() throws Exception { + when(stateService.requireActiveServer()).thenReturn(SERVER); + when(serverApiService.webhook(SERVER)).thenReturn(new WebhookStatusDto(true, "https://discord.com")); + when(serverApiService.updateWebhook(SERVER, "")).thenReturn(new WebhookStatusDto(false, null)); + when(serverApiService.testWebhook(SERVER)).thenReturn(new WebhookTestDto(false, 404, "Webhook answered 404")); + + mockMvc.perform(get("/api/client/notifications/webhook")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/webhook-status.json"), JsonCompareMode.STRICT)); + mockMvc.perform(put("/api/client/notifications/webhook").contentType(MediaType.APPLICATION_JSON).content("{\"url\":\"\"}")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/webhook-unset.json"), JsonCompareMode.STRICT)); + mockMvc.perform(post("/api/client/notifications/webhook/test")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/webhook-test.json"), JsonCompareMode.STRICT)); + } + + @Test + void serverConfigUpdateParsesADurationString() throws Exception { + when(stateService.requireActiveServer()).thenReturn(SERVER); + when(serverApiService.updateServerConfig(SERVER, "/b", 3)).thenReturn(new ServerConfigDto("/b", 3, Duration.ofHours(6))); + when(serverApiService.updateServerSchedule(SERVER, Duration.ofHours(2))).thenReturn(new ServerStatusDto(true, false, 3, Duration.ofHours(2))); + + mockMvc.perform(put("/api/client/server-config").contentType(MediaType.APPLICATION_JSON) + .content("{\"backupLocation\":\"/b\",\"retentionCount\":3,\"backupInterval\":\"PT2H\"}")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"backupLocation\":\"/b\",\"retentionCount\":3,\"backupInterval\":\"PT2H\"}", JsonCompareMode.STRICT)); + } + + @Test + void servicesJson() throws Exception { + when(stateService.requireActiveServer()).thenReturn(SERVER); + when(serverApiService.listServices(SERVER)).thenReturn(List.of(new ServiceDto("jellyfin", List.of("/srv/jellyfin/config")))); + + mockMvc.perform(get("/api/client/services")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/services.json"), JsonCompareMode.STRICT)); + } + + @Test + void pickupJson() throws Exception { + when(backupPickupService.startPickupLatestTask()).thenReturn(new PickupStartDto("task-1", "backup-2026-11-20", "mediagarrd-2026-11-20.zip", 1048576L)); + when(backupPickupService.pickupProgress("task-1")).thenReturn(new PickupProgressDto("task-1", "RUNNING", "backup-2026-11-20", "mediagarrd-2026-11-20.zip", 512L, 1048576L, null, null)); + + mockMvc.perform(post("/api/client/pickup")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/pickup-start.json"), JsonCompareMode.STRICT)); + mockMvc.perform(get("/api/client/pickup/progress/task-1")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/pickup-progress.json"), JsonCompareMode.STRICT)); + } + + @Test + void pickupIntervalRequestParsesADurationString() throws Exception { + when(stateService.getActiveServer()).thenReturn(SERVER); + when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(90)); + when(stateService.getKnownServers()).thenReturn(List.of(SERVER, "https://backup.example.net:38471")); + + mockMvc.perform(put("/api/client/pickup-interval").contentType(MediaType.APPLICATION_JSON).content("{\"interval\":\"PT1H30M\"}")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/status.json"), JsonCompareMode.STRICT)); + verify(backupPickupService).updatePickupInterval(Duration.ofMinutes(90)); + } + + @Test + void pairingJson() throws Exception { + when(pairing.pair(eq("123456"), any())).thenReturn(new PairingResultDto(true, "Golden Laptop", null)); + when(pairing.createCode()).thenReturn(new PairingCodeDto("482913", Instant.parse("2026-11-20T10:25:30.500Z"))); + when(pairing.unpair()).thenReturn(new UnpairResultDto(true, null)); + + mockMvc.perform(post("/api/client/pairing").contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"123456\",\"name\":\"Golden Laptop\"}")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/pairing-result.json"), JsonCompareMode.STRICT)); + mockMvc.perform(post("/api/client/pairing/code")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/pairing-code.json"), JsonCompareMode.STRICT)); + mockMvc.perform(delete("/api/client/pairing")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/unpair-result.json"), JsonCompareMode.STRICT)); + } + + @Test + void deferredPairingJson() throws Exception { + when(pairing.pair(eq("123456"), any())).thenReturn(new PairingResultDto(true, "Golden Laptop", "Paired. The server could not be reached to confirm it yet.")); + + mockMvc.perform(post("/api/client/pairing").contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"123456\"}")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/pairing-result-deferred.json"), JsonCompareMode.STRICT)); + } + + @Test + void requestBodiesWithUnknownOrMissingFieldsAreAccepted() throws Exception { + when(pairing.pair(eq("123456"), eq(null))).thenReturn(new PairingResultDto(true, null, null)); + + mockMvc.perform(post("/api/client/pairing").contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"123456\",\"somethingNew\":1}")) + .andExpect(status().isOk()); + } + + @Test + void authStatusJson() throws Exception { + when(passwords.isConfigured()).thenReturn(true); + when(passwords.isFromEnvironment()).thenReturn(false); + + mockMvc.perform(get("/api/auth/status")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/auth-status.json"), JsonCompareMode.STRICT)); + } + + @Test + void errorJson() throws Exception { + when(stateService.requireActiveServer()).thenThrow(new InvalidRequestException("No active MediaGarrd server selected")); + + mockMvc.perform(get("/api/client/backups")) + .andExpect(status().isBadRequest()) + .andExpect(content().json(Fixtures.read("client/error-4xx.json"), JsonCompareMode.STRICT)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java new file mode 100644 index 0000000..b398819 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java @@ -0,0 +1,235 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +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 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.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.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpStatus; +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.request.MockHttpServletRequestBuilder; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; +import wellatleastitried.mediagarrdclient.service.NotFoundException; + +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.DashboardState; +import wellatleastitried.mediagarrdclient.dto.HealthSummary; +import wellatleastitried.mediagarrdclient.dto.LinkState; +import wellatleastitried.mediagarrdclient.dto.PairingState; +import wellatleastitried.mediagarrdclient.dto.PickupStartDto; +import wellatleastitried.mediagarrdclient.dto.VersionsDto; +import wellatleastitried.mediagarrdclient.service.BackupPickupService; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.DashboardService; +import wellatleastitried.mediagarrdclient.service.BackupRunFailedException; +import wellatleastitried.mediagarrdclient.service.BackupRunTimeoutException; +import wellatleastitried.mediagarrdclient.service.ServerApiService; +import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; +import wellatleastitried.mediagarrdclient.service.ServerSelectionService; + +@WebMvcTest(controllers = ClientController.class) +@Import({TestSession.class, ServerSelectionService.class}) +class ClientControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockitoBean + ClientStateService stateService; + + @MockitoBean + ServerDiscoveryService discoveryService; + + @MockitoBean + ServerApiService serverApiService; + + @MockitoBean + BackupPickupService backupPickupService; + + @MockitoBean + DashboardService dashboardService; + + @Test + void mapsABackupRunTimeoutToAGatewayTimeoutWithAnErrorBody() throws Exception { + when(stateService.requireActiveServer()).thenReturn("http://server:8080"); + doThrow(new BackupRunTimeoutException("The backup is probably still running on the server.", null)) + .when(serverApiService).triggerBackup("http://server:8080"); + + mockMvc.perform(post("/api/client/backups/run")) + .andExpect(status().isGatewayTimeout()) + .andExpect(jsonPath("$.error").value("The backup is probably still running on the server.")); + } + + @Test + void mapsAFailedBackupRunToAnInternalErrorWithTheReason() throws Exception { + when(stateService.requireActiveServer()).thenReturn("http://server:8080"); + doThrow(new BackupRunFailedException("Backup of radarr failed: disk is full", null)) + .when(serverApiService).triggerBackup("http://server:8080"); + + mockMvc.perform(post("/api/client/backups/run")) + .andExpect(status().isInternalServerError()) + .andExpect(jsonPath("$.error").value("Backup of radarr failed: disk is full")); + } + + @Test + void discoverEndpointReturnsOnlyTheServersFoundByTheScan() throws Exception { + when(discoveryService.discover()).thenReturn(List.of("http://server:8080")); + when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080", "http://active:38471")); + + mockMvc.perform(post("/api/client/discover")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.length()").value(1)) + .andExpect(jsonPath("$[0]").value("http://server:8080")); + + verify(stateService).updateKnownServers(List.of("http://server:8080")); + } + + @Test + void statusHasNoNetworkSideEffect() throws Exception { + mockMvc.perform(get("/api/client/status")).andExpect(status().isOk()); + + verifyNoInteractions(discoveryService, serverApiService); + } + + @Test + void dashboardEndpointReturnsTheStoredStateWithoutContactingTheServer() throws Exception { + when(dashboardService.state()).thenReturn(new DashboardState( + "http://server:8080", + List.of("http://server:8080"), + LinkState.DEGRADED, + true, + new HealthSummary(Duration.ofHours(6), 5), + new VersionsDto(null, null), + PairingState.PAIRED)); + + mockMvc.perform(get("/api/client/dashboard")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.activeServer").value("http://server:8080")) + .andExpect(jsonPath("$.knownServers[0]").value("http://server:8080")) + .andExpect(jsonPath("$.link").value("DEGRADED")) + .andExpect(jsonPath("$.running").value(true)) + .andExpect(jsonPath("$.health.backupRetentionCount").value(5)) + .andExpect(jsonPath("$.versions.server").doesNotExist()); + + verifyNoInteractions(serverApiService, discoveryService); + } + + @Test + void normalizesSelectedServerUrls() throws Exception { + when(discoveryService.isMediaGarrdServer("http://server:8080")).thenReturn(true); + mockMvc.perform(json(put("/api/client/server"), "{\"serverUrl\":\" http://server:8080/ \"}")) + .andExpect(status().isOk()); + + verify(stateService).setActiveServer("http://server:8080"); + } + + @Test + void refusesAServerUrlThatIsNotAMediaGarrdServer() throws Exception { + when(discoveryService.isMediaGarrdServer("http://intranet-printer:631")).thenReturn(false); + + mockMvc.perform(json(put("/api/client/server"), "{\"serverUrl\":\"http://intranet-printer:631\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("No MediaGarrd server found at http://intranet-printer:631")); + + verify(stateService, never()).setActiveServer(any()); + } + + @Test + void doesNotProbeAServerThatIsAlreadyKnown() throws Exception { + when(stateService.isKnownServer("http://server:8080")).thenReturn(true); + + mockMvc.perform(json(put("/api/client/server"), "{\"serverUrl\":\"http://server:8080\"}")) + .andExpect(status().isOk()); + + verify(stateService).setActiveServer("http://server:8080"); + verify(discoveryService, never()).isMediaGarrdServer(any(String.class)); + } + + @Test + void rejectsInvalidServerSelections() throws Exception { + mockMvc.perform(json(put("/api/client/server"), "{\"serverUrl\":\"ftp://server\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("serverUrl must be an http:// or https:// URL: ftp://server")); + mockMvc.perform(json(put("/api/client/server"), "{\"serverIp\":\"10.0.0.2\",\"serverPort\":70000}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("serverPort must be between 1 and 65535")); + mockMvc.perform(json(put("/api/client/server"), "{}")) + .andExpect(status().isBadRequest()); + mockMvc.perform(json(put("/api/client/server"), "not json")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Request body is missing or malformed")); + + verify(stateService, never()).setActiveServer(any()); + } + + @Test + void reportsWhenNoServerAnswersAtTheGivenAddress() throws Exception { + when(discoveryService.resolveServerByIp("10.0.0.2", null)).thenReturn(Optional.empty()); + + mockMvc.perform(json(put("/api/client/server"), "{\"serverIp\":\"10.0.0.2\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("No MediaGarrd server found at 10.0.0.2")); + } + + @Test + void rejectsInvalidPickupIntervals() throws Exception { + when(backupPickupService.updatePickupInterval(Duration.ZERO)).thenThrow(new InvalidRequestException("Pickup interval must be a positive duration")); + + mockMvc.perform(json(put("/api/client/pickup-interval"), "{\"interval\":\"PT0S\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Pickup interval must be a positive duration")); + } + + @Test + void pickingUpASpecificBackupStartsATaskForThatId() throws Exception { + when(backupPickupService.startPickupByIdTask("b1")).thenReturn(new PickupStartDto("task-1", "b1", "b1-media-backup.zip", 10L)); + + mockMvc.perform(post("/api/client/pickup/b1")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.taskId").value("task-1")) + .andExpect(jsonPath("$.backupId").value("b1")) + .andExpect(jsonPath("$.fileName").value("b1-media-backup.zip")); + + verify(backupPickupService).startPickupByIdTask("b1"); + verify(backupPickupService, never()).startPickupLatestTask(); + } + + @Test + void pickingUpAnUnknownBackupIsNotFound() throws Exception { + when(backupPickupService.startPickupByIdTask("gone")).thenThrow(new NotFoundException("Backup not found: gone")); + + mockMvc.perform(post("/api/client/pickup/gone")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Backup not found: gone")); + } + + @Test + void unknownPickupTasksAreNotFound() throws Exception { + when(backupPickupService.pickupProgress("gone")).thenThrow(new NotFoundException("Pickup task not found: gone")); + + mockMvc.perform(get("/api/client/pickup/progress/gone")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Pickup task not found: gone")); + } + + private static MockHttpServletRequestBuilder json(MockHttpServletRequestBuilder request, String body) { + return request.contentType(MediaType.APPLICATION_JSON).content(body); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcasterTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcasterTest.java new file mode 100644 index 0000000..670ef83 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcasterTest.java @@ -0,0 +1,239 @@ +package wellatleastitried.mediagarrdclient.api; + +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.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.function.LongFunction; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import wellatleastitried.mediagarrdclient.service.ClientEvent; + +@Timeout(30) +class ClientEventBroadcasterTest { + + private static final Duration LONG_PING = Duration.ofMinutes(10); + + static class FailingEmitter extends RecordingEmitter { + + FailingEmitter(Long timeout) { + super(timeout); + } + + @Override + public void send(SseEventBuilder builder) throws IOException { + throw new IOException("client went away"); + } + } + + static class StuckEmitter extends RecordingEmitter { + + final CountDownLatch entered = new CountDownLatch(1); + final CountDownLatch release = new CountDownLatch(1); + + StuckEmitter(Long timeout) { + super(timeout); + } + + @Override + public synchronized void send(SseEventBuilder builder) throws IOException { + entered.countDown(); + try { + release.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + + private final List writers = new CopyOnWriteArrayList<>(); + private final ThreadFactory threadFactory = runnable -> { + Thread thread = new Thread(runnable); + thread.setDaemon(true); + writers.add(thread); + return thread; + }; + private final List broadcasters = new ArrayList<>(); + + @AfterEach + void tearDown() throws InterruptedException { + broadcasters.forEach(ClientEventBroadcaster::shutdown); + for (Thread writer : writers) { + writer.join(5000); + } + } + + private ClientEventBroadcaster broadcaster(Duration ping, int max, int queue, LongFunction factory) { + return broadcaster(ping, max, queue, Duration.ofMinutes(10), factory); + } + + private ClientEventBroadcaster broadcaster(Duration ping, int max, int queue, Duration lifetime, LongFunction factory) { + ClientEventBroadcaster broadcaster = new ClientEventBroadcaster(ping, max, queue, lifetime, Duration.ofMinutes(5), threadFactory, factory); + broadcasters.add(broadcaster); + return broadcaster; + } + + private ClientEventBroadcaster broadcaster() { + return broadcaster(LONG_PING, 32, 64, RecordingEmitter::new); + } + + private static final List SNAPSHOT = List.of(new ClientEvent("snapshot", "{\"link\":\"DOWN\"}")); + + private static RecordingEmitter subscribe(ClientEventBroadcaster broadcaster) { + return (RecordingEmitter) broadcaster.subscribe(SNAPSHOT).orElseThrow(); + } + + @Test + void endingASessionClosesOnlyItsSubscribers() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(); + RecordingEmitter ending = (RecordingEmitter) broadcaster.subscribe("session-a", SNAPSHOT).orElseThrow(); + RecordingEmitter staying = (RecordingEmitter) broadcaster.subscribe("session-b", SNAPSHOT).orElseThrow(); + ending.next(); + staying.next(); + + broadcaster.endSession("session-a"); + + assertTrue(ending.completed.await(5, TimeUnit.SECONDS)); + assertEquals(1, broadcaster.subscriberCount()); + broadcaster.publish("state", "{}"); + assertTrue(staying.next().contains("event:state")); + } + + @Test + void aSubscriberWhoseSessionExpiredIsClosedAtTheNextPing() throws Exception { + java.util.concurrent.atomic.AtomicBoolean active = new java.util.concurrent.atomic.AtomicBoolean(true); + ClientEventBroadcaster broadcaster = new ClientEventBroadcaster(Duration.ofMillis(20), 32, 64, Duration.ofMinutes(10), Duration.ofMinutes(5), threadFactory, + RecordingEmitter::new, key -> active.get()); + broadcasters.add(broadcaster); + RecordingEmitter emitter = (RecordingEmitter) broadcaster.subscribe("session-a", SNAPSHOT).orElseThrow(); + emitter.next(); + + active.set(false); + + assertTrue(emitter.completed.await(5, TimeUnit.SECONDS)); + } + + @Test + void sendsTheInitialEventsFirstAndTellsTheBrowserHowLongToWaitBeforeReconnecting() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(); + + RecordingEmitter emitter = subscribe(broadcaster); + + assertEquals("retry:5000\nevent:snapshot\ndata:{\"link\":\"DOWN\"}\n\n", emitter.next()); + assertNull(emitter.sent.poll(200, TimeUnit.MILLISECONDS)); + } + + @Test + void publishesAreOrderedAfterTheInitialEventsForALateSubscriber() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(); + broadcaster.publish("link", "{\"state\":\"LIVE\"}"); + RecordingEmitter emitter = subscribe(broadcaster); + broadcaster.publish("state", "{\"running\":true}"); + + assertTrue(emitter.next().contains("event:snapshot")); + assertTrue(emitter.next().contains("event:state")); + assertNull(emitter.sent.poll(200, TimeUnit.MILLISECONDS)); + } + + @Test + void fansEventsOutToEverySubscriberInOrder() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(); + RecordingEmitter first = subscribe(broadcaster); + RecordingEmitter second = subscribe(broadcaster); + first.next(); + second.next(); + + broadcaster.publish("run-started", "{\"running\":true}"); + broadcaster.publish("run-finished", "{\"running\":false,\"status\":\"FAILED\"}"); + + for (RecordingEmitter emitter : List.of(first, second)) { + assertEquals("event:run-started\ndata:{\"running\":true}\n\n", emitter.next()); + assertEquals("event:run-finished\ndata:{\"running\":false,\"status\":\"FAILED\"}\n\n", emitter.next()); + } + } + + @Test + void sendsNamedPingsWhenIdle() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(Duration.ofMillis(20), 32, 64, RecordingEmitter::new); + RecordingEmitter emitter = subscribe(broadcaster); + + emitter.nextContaining("event:ping\ndata:{}\n\n"); + } + + @Test + void rejectsSubscribersBeyondTheCap() { + ClientEventBroadcaster broadcaster = broadcaster(LONG_PING, 2, 64, RecordingEmitter::new); + subscribe(broadcaster); + subscribe(broadcaster); + + assertTrue(broadcaster.subscribe(SNAPSHOT).isEmpty()); + assertEquals(2, broadcaster.subscriberCount()); + } + + @Test + void forgetsASubscriberWhoseWriteFailsAndFreesItsSlot() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(LONG_PING, 1, 64, FailingEmitter::new); + + broadcaster.subscribe(SNAPSHOT); + writers.get(0).join(5000); + + assertEquals(0, broadcaster.subscriberCount()); + assertTrue(broadcaster.subscribe(SNAPSHOT).isPresent()); + } + + @Test + void shutdownCompletesEverySubscriber() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(); + RecordingEmitter emitter = subscribe(broadcaster); + emitter.next(); + + broadcaster.shutdown(); + + assertTrue(emitter.completed.await(5, TimeUnit.SECONDS)); + assertEquals(0, broadcaster.subscriberCount()); + assertTrue(broadcaster.subscribe(SNAPSHOT).isEmpty()); + } + + @Test + void publishingNeverBlocksOnAStuckSubscriberAndOnlyItsWriterCompletesIt() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(LONG_PING, 4, 1, StuckEmitter::new); + StuckEmitter stuck = (StuckEmitter) broadcaster.subscribe(SNAPSHOT).orElseThrow(); + assertTrue(stuck.entered.await(5, TimeUnit.SECONDS)); + + assertTimeoutPreemptively(Duration.ofSeconds(2), () -> { + for (int i = 0; i < 5; i++) { + broadcaster.publish("run-started", "{\"running\":true}"); + } + broadcaster.publish("link", "{}"); + }); + + assertEquals(0, broadcaster.subscriberCount()); + assertFalse(stuck.completed.await(200, TimeUnit.MILLISECONDS)); + stuck.release.countDown(); + assertTrue(stuck.completed.await(5, TimeUnit.SECONDS)); + } + + @Test + void theWriterEndsAStreamItselfOnceItsLifetimeIsUp() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(LONG_PING, 4, 64, Duration.ofMillis(100), RecordingEmitter::new); + + RecordingEmitter emitter = subscribe(broadcaster); + + assertTrue(emitter.completed.await(5, TimeUnit.SECONDS)); + assertEquals(0, broadcaster.subscriberCount()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java new file mode 100644 index 0000000..2097831 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java @@ -0,0 +1,88 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +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.request; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +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.web.servlet.mvc.method.annotation.SseEmitter; + +import wellatleastitried.mediagarrdclient.service.ClientEvent; +import wellatleastitried.mediagarrdclient.service.DashboardService; + +@WebMvcTest(controllers = ClientEventsController.class) +@Import(TestSession.class) +@Timeout(20) +class ClientEventsControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockitoBean + DashboardService dashboard; + + @MockitoBean + ClientEventBroadcaster broadcaster; + + @BeforeEach + void dashboardRegistersTheSubscriber() { + when(dashboard.subscribe(any())).thenAnswer(invocation -> invocation., Optional>>getArgument(0).apply(List.of())); + } + + @Test + void opensAnUnbufferedEventStream() throws Exception { + SseEmitter emitter = new SseEmitter(60_000L); + emitter.send(SseEmitter.event().name("link").data("{}")); + when(broadcaster.subscribe(any(), any())).thenReturn(Optional.of(emitter)); + + mockMvc.perform(get("/api/client/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(request().asyncStarted()) + .andExpect(status().isOk()) + .andExpect(header().string("X-Accel-Buffering", "no")) + .andExpect(content().string("event:link\ndata:{}\n\n")); + + emitter.complete(); + } + + @Test + void answers503WhenTooManyBrowsersAreSubscribed() throws Exception { + when(broadcaster.subscribe(any(), any())).thenReturn(Optional.empty()); + + mockMvc.perform(get("/api/client/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(status().isServiceUnavailable()) + .andExpect(content().string("")); + } + + @Test + void aBrowserThatWentAwayEndsTheStreamWithoutAnError() throws Exception { + SseEmitter emitter = new SseEmitter(60_000L); + emitter.send(SseEmitter.event().name("link").data("{}")); + when(broadcaster.subscribe(any(), any())).thenReturn(Optional.of(emitter)); + MvcResult started = mockMvc.perform(get("/api/client/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(request().asyncStarted()) + .andReturn(); + + emitter.completeWithError(new IOException("Broken pipe")); + + mockMvc.perform(asyncDispatch(started)).andExpect(status().isOk()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/CsrfCheckTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/CsrfCheckTest.java new file mode 100644 index 0000000..ab0b189 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/CsrfCheckTest.java @@ -0,0 +1,94 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; + +class CsrfCheckTest { + + private static MockHttpServletRequest post() { + MockHttpServletRequest request = new MockHttpServletRequest("POST", "/api/client/backups/run"); + request.addHeader("Host", "192.168.1.5:8081"); + return request; + } + + @Test + void safeMethodsAreAlwaysAllowed() { + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/client/status"); + request.addHeader("Origin", "http://evil.example.com"); + request.addHeader("Sec-Fetch-Site", "cross-site"); + + assertTrue(CsrfCheck.allows(request)); + } + + @Test + void aSameOriginFetchMetadataHeaderIsAccepted() { + MockHttpServletRequest request = post(); + request.addHeader("Sec-Fetch-Site", "same-origin"); + + assertTrue(CsrfCheck.allows(request)); + } + + @Test + void anyOtherFetchMetadataValueIsRefusedEvenWithAMatchingOrigin() { + for (String site : new String[] {"same-site", "cross-site", "none"}) { + MockHttpServletRequest request = post(); + request.addHeader("Sec-Fetch-Site", site); + request.addHeader("Origin", "http://192.168.1.5:8081"); + + assertFalse(CsrfCheck.allows(request), site); + } + } + + @Test + void anOriginMatchingTheHostIsAcceptedWithoutFetchMetadata() { + MockHttpServletRequest request = post(); + request.addHeader("Origin", "http://192.168.1.5:8081"); + + assertTrue(CsrfCheck.allows(request)); + } + + @Test + void anotherPortOnTheSameHostIsAnotherOrigin() { + MockHttpServletRequest request = post(); + request.addHeader("Origin", "http://192.168.1.5:8096"); + + assertFalse(CsrfCheck.allows(request)); + } + + @Test + void aForeignOriginAndTheNullOriginAreRefused() { + MockHttpServletRequest foreign = post(); + foreign.addHeader("Origin", "https://evil.example.com"); + MockHttpServletRequest opaque = post(); + opaque.addHeader("Origin", "null"); + + assertFalse(CsrfCheck.allows(foreign)); + assertFalse(CsrfCheck.allows(opaque)); + } + + @Test + void aProxyThatKeepsTheOriginalHostInAForwardedHeaderIsSupported() { + MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/api/client/server"); + request.addHeader("Host", "client:8081"); + request.addHeader("X-Forwarded-Host", "garrd.example.com"); + request.addHeader("Origin", "https://garrd.example.com"); + + assertTrue(CsrfCheck.allows(request)); + } + + @Test + void requestsWithoutBrowserHeadersNeedTheCustomHeader() { + MockHttpServletRequest without = post(); + MockHttpServletRequest with = post(); + with.addHeader("X-MediaGarrd-Request", "1"); + MockHttpServletRequest wrong = post(); + wrong.addHeader("X-MediaGarrd-Request", "0"); + + assertFalse(CsrfCheck.allows(without)); + assertTrue(CsrfCheck.allows(with)); + assertFalse(CsrfCheck.allows(wrong)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/FirstVisitPasswordFullContextTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/FirstVisitPasswordFullContextTest.java new file mode 100644 index 0000000..e7fadbe --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/FirstVisitPasswordFullContextTest.java @@ -0,0 +1,108 @@ +package wellatleastitried.mediagarrdclient.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 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.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; + +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.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +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 jakarta.servlet.http.Cookie; + +@SpringBootTest +@org.springframework.context.annotation.Import(wellatleastitried.mediagarrdclient.api.TestCsrfHeader.class) +@AutoConfigureMockMvc +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class FirstVisitPasswordFullContextTest { + + @TempDir + static Path dataDir; + + @Autowired + MockMvc mockMvc; + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) { + registry.add("mediagarrd.client.state-file", () -> dataDir.resolve("state.json").toString()); + registry.add("mediagarrd.client.download-directory", () -> dataDir.resolve("downloads").toString()); + registry.add("mediagarrd.client.preferred-server-ip", () -> ""); + registry.add("mediagarrd.client.github-api-base-url", () -> "http://127.0.0.1:1"); + registry.add("mediagarrd.client.password", () -> ""); + } + + private static String body(String password) { + return "{\"password\":\"" + password + "\"}"; + } + + @Test + @Order(1) + void withoutAPasswordTheDashboardOffersToSetOneAndLoginIsRefused() throws Exception { + mockMvc.perform(get("/api/auth/status")) + .andExpect(jsonPath("$.passwordSet").value(false)) + .andExpect(jsonPath("$.passwordFromEnvironment").value(false)) + .andExpect(jsonPath("$.authenticated").value(false)); + mockMvc.perform(get("/api/client/status")).andExpect(status().isUnauthorized()); + mockMvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON).content(body("anything at all"))) + .andExpect(status().isConflict()); + } + + @Test + @Order(2) + void aCrossSiteRequestCannotSetThePasswordAndAShortOneIsRefused() throws Exception { + mockMvc.perform(post("/api/auth/set-password").header("Origin", "http://evil.example.com").header("Host", "client.local:8081") + .contentType(MediaType.APPLICATION_JSON).content(body("long enough password"))) + .andExpect(status().isForbidden()); + mockMvc.perform(post("/api/auth/set-password").contentType(MediaType.APPLICATION_JSON).content(body("short"))) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").exists()); + mockMvc.perform(get("/api/auth/status")).andExpect(jsonPath("$.passwordSet").value(false)); + } + + @Test + @Order(3) + void theFirstVisitorSetsThePasswordAndIsSignedIn() throws Exception { + MvcResult result = mockMvc.perform(post("/api/auth/set-password").contentType(MediaType.APPLICATION_JSON).content(body("my first password"))) + .andExpect(status().isOk()) + .andReturn(); + Cookie cookie = result.getResponse().getCookie("mg_session"); + + mockMvc.perform(get("/api/client/status").cookie(cookie)).andExpect(status().isOk()); + Path file = dataDir.resolve("password.json"); + assertTrue(Files.exists(file)); + assertFalse(Files.readString(file).contains("my first password")); + if (Files.getFileStore(file).supportsFileAttributeView("posix")) { + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(file))); + } + } + + @Test + @Order(4) + void theSecondVisitorCannotReplaceThePasswordButCanLogInWithIt() throws Exception { + mockMvc.perform(post("/api/auth/set-password").contentType(MediaType.APPLICATION_JSON).content(body("an attacker password"))) + .andExpect(status().isConflict()); + mockMvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON).content(body("an attacker password"))) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON).content(body("my first password"))) + .andExpect(status().isOk()); + mockMvc.perform(get("/api/auth/status")).andExpect(jsonPath("$.passwordSet").value(true)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/PairingControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/PairingControllerTest.java new file mode 100644 index 0000000..efca189 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/PairingControllerTest.java @@ -0,0 +1,76 @@ +package wellatleastitried.mediagarrdclient.api; + +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.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.Instant; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; + +import wellatleastitried.mediagarrdclient.dto.PairingCodeDto; +import wellatleastitried.mediagarrdclient.dto.PairingResultDto; +import wellatleastitried.mediagarrdclient.dto.UnpairResultDto; +import wellatleastitried.mediagarrdclient.service.ClientPairingService; +import wellatleastitried.mediagarrdclient.service.PairingRequiredException; + +@WebMvcTest(controllers = PairingController.class) +@Import(TestSession.class) +class PairingControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockitoBean + ClientPairingService pairing; + + @Test + void pairsAndNeverReturnsAToken() throws Exception { + when(pairing.pair("123456", null)).thenReturn(new PairingResultDto(true, "MediaGarrd Client", null)); + + mockMvc.perform(post("/api/client/pairing").contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"123456\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.paired").value(true)) + .andExpect(jsonPath("$.name").value("MediaGarrd Client")) + .andExpect(jsonPath("$.token").doesNotExist()); + } + + @Test + void passesOnWhyTheServerRefusedThePairing() throws Exception { + when(pairing.pair("000000", null)).thenThrow(new InvalidRequestException("Invalid PIN")); + + mockMvc.perform(post("/api/client/pairing").contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"000000\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Invalid PIN")); + } + + @Test + void aRejectedTokenIsABadGatewayWithThePairingMarker() throws Exception { + when(pairing.createCode()).thenThrow(new PairingRequiredException("The server rejected this client's token, pair it again")); + + mockMvc.perform(post("/api/client/pairing/code")) + .andExpect(status().isBadGateway()) + .andExpect(jsonPath("$.pairing").value("required")) + .andExpect(jsonPath("$.error").exists()); + } + + @Test + void unpairsAndSaysWhetherTheServerWasTold() throws Exception { + when(pairing.unpair()).thenReturn(new UnpairResultDto(false, "The server could not be told")); + + mockMvc.perform(delete("/api/client/pairing")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.serverRevoked").value(false)) + .andExpect(jsonPath("$.warning").value("The server could not be told")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/RecordingEmitter.java b/src/test/java/wellatleastitried/mediagarrdclient/api/RecordingEmitter.java new file mode 100644 index 0000000..e4f3144 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/RecordingEmitter.java @@ -0,0 +1,52 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +public class RecordingEmitter extends SseEmitter { + + public final BlockingQueue sent = new LinkedBlockingQueue<>(); + public final CountDownLatch completed = new CountDownLatch(1); + + public RecordingEmitter(Long timeout) { + super(timeout); + } + + @Override + public void send(SseEventBuilder builder) throws IOException { + StringBuilder text = new StringBuilder(); + for (ResponseBodyEmitter.DataWithMediaType part : builder.build()) { + text.append(part.getData()); + } + sent.add(text.toString()); + } + + @Override + public void complete() { + completed.countDown(); + super.complete(); + } + + public String next() throws InterruptedException { + String event = sent.poll(5, TimeUnit.SECONDS); + assertNotNull(event, "timed out waiting for an event"); + return event; + } + + public String nextContaining(String marker) throws InterruptedException { + while (true) { + String event = next(); + if (event.contains(marker)) { + return event; + } + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/RunningServerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/RunningServerTest.java new file mode 100644 index 0000000..8314d0e --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/RunningServerTest.java @@ -0,0 +1,163 @@ +package wellatleastitried.mediagarrdclient.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.InputStream; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Duration; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Timeout(60) +class RunningServerTest { + + @TempDir + static Path dataDir; + + @LocalServerPort + int port; + + private final HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).connectTimeout(Duration.ofSeconds(5)).build(); + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) { + registry.add("mediagarrd.client.state-file", () -> dataDir.resolve("state.json").toString()); + registry.add("mediagarrd.client.download-directory", () -> dataDir.resolve("downloads").toString()); + registry.add("mediagarrd.client.preferred-server-ip", () -> ""); + registry.add("mediagarrd.client.github-api-base-url", () -> "http://127.0.0.1:1"); + registry.add("mediagarrd.client.password", () -> ""); + } + + private URI uri(String path) { + return URI.create("http://127.0.0.1:" + port + path); + } + + private HttpRequest.Builder request(String path) { + return HttpRequest.newBuilder(uri(path)).header("X-MediaGarrd-Request", "1").timeout(Duration.ofSeconds(20)); + } + + private HttpResponse send(HttpRequest request) throws Exception { + return client.send(request, HttpResponse.BodyHandlers.ofString()); + } + + private String signIn() throws Exception { + String body = "{\"password\":\"a long enough password\"}"; + HttpResponse response = send(request("/api/auth/set-password").header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(body)).build()); + if (response.statusCode() == 409) { + response = send(request("/api/auth/login").header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(body)).build()); + } + assertEquals(200, response.statusCode()); + String cookie = response.headers().firstValue("Set-Cookie").orElseThrow(); + return cookie.substring(0, cookie.indexOf(';')); + } + + @Test + void servesSecurityHeadersOnPagesAndApiResponses() throws Exception { + for (String path : new String[] {"/", "/index.html", "/js/main.js", "/api/auth/status", "/api/client/status", "/nothing-here"}) { + HttpResponse response = send(request(path).GET().build()); + + assertEquals(SecurityHeadersFilter.CONTENT_SECURITY_POLICY, response.headers().firstValue("Content-Security-Policy").orElse(null), path); + assertEquals("nosniff", response.headers().firstValue("X-Content-Type-Options").orElse(null), path); + assertEquals("no-referrer", response.headers().firstValue("Referrer-Policy").orElse(null), path); + assertEquals("DENY", response.headers().firstValue("X-Frame-Options").orElse(null), path); + if (path.startsWith("/api/")) { + assertEquals(java.util.List.of("no-store"), response.headers().allValues("Cache-Control"), path); + } + } + } + + @Test + void anUnknownApiPathAnswersWithTheErrorShape() throws Exception { + String cookie = signIn(); + + HttpResponse response = send(request("/api/client/no-such-endpoint").header("Cookie", cookie).GET().build()); + + assertTrue(response.statusCode() >= 400 && response.statusCode() < 500); + assertTrue(response.body().contains("\"error\"")); + } + + @Test + void refusesARequestBodyOverTheCapWhetherItIsDeclaredOrChunked() throws Exception { + byte[] oversized = ("{\"password\":\"" + "x".repeat((int) BodyLimitFilter.MAX_BODY_BYTES + 10) + "\"}").getBytes(StandardCharsets.UTF_8); + + HttpResponse declared = send(request("/api/auth/login").header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofByteArray(oversized)).build()); + HttpResponse chunked = send(request("/api/auth/login").header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(oversized))).build()); + + assertEquals(413, declared.statusCode()); + assertEquals("{\"error\":\"Request body is too large\"}", declared.body()); + assertEquals(413, chunked.statusCode()); + assertEquals("{\"error\":\"Request body is too large\"}", chunked.body()); + } + + @Test + void aChunkedBodyWithinTheCapStillWorks() throws Exception { + signIn(); + byte[] small = "{\"password\":\"wrong password\"}".getBytes(StandardCharsets.UTF_8); + + HttpResponse response = send(request("/api/auth/login").header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(small))).build()); + + assertEquals(401, response.statusCode()); + assertEquals("{\"error\":\"Incorrect password\"}", response.body()); + } + + @Test + void theEventStreamNeedsASessionDeliversASnapshotAndEndsWhenTheSessionDoes() throws Exception { + assertEquals(401, send(request("/api/client/events").header("Accept", "text/event-stream").GET().build()).statusCode()); + String cookie = signIn(); + + HttpResponse stream = client.send(request("/api/client/events").header("Cookie", cookie).header("Accept", "text/event-stream").GET().build(), + HttpResponse.BodyHandlers.ofInputStream()); + + assertEquals(200, stream.statusCode()); + assertTrue(stream.headers().firstValue("Content-Type").orElse("").startsWith("text/event-stream")); + assertEquals(java.util.List.of("no-store"), stream.headers().allValues("Cache-Control")); + BufferedReader reader = new BufferedReader(new InputStreamReader(stream.body(), StandardCharsets.UTF_8)); + String line; + String event = null; + while ((line = reader.readLine()) != null && event == null) { + if (line.startsWith("event:")) { + event = line; + } + } + assertEquals("event:snapshot", event); + + CompletableFuture ended = CompletableFuture.supplyAsync(() -> { + try { + while (reader.readLine() != null) { + continue; + } + return true; + } catch (java.io.IOException e) { + return true; + } + }); + HttpResponse logout = send(request("/api/auth/logout").header("Cookie", cookie).POST(HttpRequest.BodyPublishers.noBody()).build()); + assertEquals(204, logout.statusCode()); + + assertTrue(ended.get(10, TimeUnit.SECONDS)); + assertNotNull(logout.headers().firstValue("Set-Cookie").orElse(null)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java new file mode 100644 index 0000000..7f8e313 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java @@ -0,0 +1,167 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +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 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 org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpStatus; +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.request.MockHttpServletRequestBuilder; +import org.springframework.web.client.ResourceAccessException; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; + +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.ServerApiService; + +@WebMvcTest(controllers = ServerConfigController.class) +@Import(TestSession.class) +class ServerConfigControllerTest { + + private static final String SERVER = "http://server:8080"; + private static final ServiceDto RADARR = new ServiceDto("radarr", List.of("/srv/radarr")); + private static final String RADARR_JSON = """ + {"name": "radarr", "paths": ["/srv/radarr"]} + """; + + @Autowired + MockMvc mockMvc; + + @MockitoBean + ClientStateService stateService; + + @MockitoBean + ServerApiService serverApiService; + + @BeforeEach + void setUp() { + when(stateService.requireActiveServer()).thenReturn(SERVER); + } + + @Test + void leavesScheduleAloneWhenIntervalIsOmitted() throws Exception { + when(serverApiService.updateServerConfig(SERVER, null, 5)).thenReturn(new ServerConfigDto("/backups", 5, Duration.ofHours(6))); + + mockMvc.perform(json(put("/api/client/server-config"), "{\"retentionCount\": 5}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.backupInterval").value("PT6H")); + + verify(serverApiService, never()).updateServerSchedule(anyString(), any()); + } + + @Test + void refusesAnOutOfRangeIntervalBeforeChangingAnything() throws Exception { + for (String interval : List.of("\"PT14M59S\"", "\"PT0S\"", "\"-PT1H\"", "\"PT8761H\"", "899", "31536001")) { + mockMvc.perform(json(put("/api/client/server-config"), + "{\"backupLocation\": \"/backups\", \"retentionCount\": 5, \"backupInterval\": " + interval + "}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Backup interval must be between 15 minutes and 365 days")); + } + + verify(serverApiService, never()).updateServerConfig(anyString(), any(), any()); + verify(serverApiService, never()).updateServerSchedule(anyString(), any()); + } + + @Test + void acceptsTheIntervalBounds() throws Exception { + when(serverApiService.updateServerConfig(SERVER, "/backups", 5)).thenReturn(new ServerConfigDto("/backups", 5, Duration.ofHours(6))); + for (String interval : List.of("\"PT15M\"", "\"PT8760H\"", "900", "31536000")) { + when(serverApiService.updateServerSchedule(anyString(), any())).thenReturn(new ServerStatusDto(true, false, 5, Duration.ofMinutes(15))); + mockMvc.perform(json(put("/api/client/server-config"), + "{\"backupLocation\": \"/backups\", \"retentionCount\": 5, \"backupInterval\": " + interval + "}")) + .andExpect(status().isOk()); + } + } + + @Test + void forwardsServiceChanges() throws Exception { + when(serverApiService.listServices(SERVER)).thenReturn(List.of(RADARR)); + when(serverApiService.addService(SERVER, RADARR)).thenReturn(RADARR); + when(serverApiService.updateService(SERVER, "radarr-4k", RADARR)).thenReturn(RADARR); + + mockMvc.perform(get("/api/client/services")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].name").value("radarr")) + .andExpect(jsonPath("$[0].paths[0]").value("/srv/radarr")); + mockMvc.perform(json(post("/api/client/services"), RADARR_JSON)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.name").value("radarr")); + mockMvc.perform(json(put("/api/client/services/radarr-4k"), RADARR_JSON)) + .andExpect(status().isOk()); + mockMvc.perform(delete("/api/client/services/radarr")) + .andExpect(status().isNoContent()); + + verify(serverApiService).removeService(SERVER, "radarr"); + } + + @Test + void refusesServiceNamesThatCouldChangeThePath() throws Exception { + mockMvc.perform(json(put("/api/client/services/%2E%2E"), RADARR_JSON)) + .andExpect(status().isBadRequest()); + mockMvc.perform(json(put("/api/client/services/a%2Fb"), RADARR_JSON)) + .andExpect(status().isBadRequest()); + mockMvc.perform(delete("/api/client/services/..%5Cetc")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").exists()); + + verify(serverApiService, never()).updateService(anyString(), anyString(), any()); + verify(serverApiService, never()).removeService(anyString(), anyString()); + } + + @Test + void routineReadsDoNotLogAtInfoButWritesDo() throws Exception { + ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + ch.qos.logback.core.read.ListAppender logs = new ch.qos.logback.core.read.ListAppender<>(); + logs.start(); + root.addAppender(logs); + try { + when(serverApiService.serverConfig(SERVER)).thenReturn(new ServerConfigDto("/backups", 5, Duration.ofHours(6))); + when(serverApiService.listServices(SERVER)).thenReturn(List.of(RADARR)); + mockMvc.perform(get("/api/client/server-config")).andExpect(status().isOk()); + mockMvc.perform(get("/api/client/services")).andExpect(status().isOk()); + long infoAfterReads = logs.list.stream().filter(event -> event.getLevel().toInt() >= ch.qos.logback.classic.Level.INFO_INT && event.getLoggerName().endsWith("ServerConfigController")).count(); + + when(serverApiService.addService(SERVER, RADARR)).thenReturn(RADARR); + mockMvc.perform(json(post("/api/client/services"), RADARR_JSON)).andExpect(status().isCreated()); + long infoAfterWrite = logs.list.stream().filter(event -> event.getLevel().toInt() >= ch.qos.logback.classic.Level.INFO_INT && event.getLoggerName().endsWith("ServerConfigController")).count(); + + org.junit.jupiter.api.Assertions.assertEquals(0, infoAfterReads); + org.junit.jupiter.api.Assertions.assertEquals(1, infoAfterWrite); + } finally { + root.detachAppender(logs); + } + } + + @Test + void reportsAnUnreachableServer() throws Exception { + when(serverApiService.serverConfig(SERVER)).thenThrow(new ResourceAccessException("Connection refused")); + + mockMvc.perform(get("/api/client/server-config")) + .andExpect(status().isBadGateway()) + .andExpect(jsonPath("$.error").value("MediaGarrd server is unreachable")); + } + + private static MockHttpServletRequestBuilder json(MockHttpServletRequestBuilder request, String body) { + return request.contentType(MediaType.APPLICATION_JSON).content(body); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/TestCsrfHeader.java b/src/test/java/wellatleastitried/mediagarrdclient/api/TestCsrfHeader.java new file mode 100644 index 0000000..800ae18 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/TestCsrfHeader.java @@ -0,0 +1,16 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.webmvc.test.autoconfigure.MockMvcBuilderCustomizer; +import org.springframework.context.annotation.Bean; + +@TestConfiguration +public class TestCsrfHeader { + + @Bean + MockMvcBuilderCustomizer csrfHeader() { + return builder -> builder.defaultRequest(get("/").header(CsrfCheck.HEADER, "1")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/TestSession.java b/src/test/java/wellatleastitried/mediagarrdclient/api/TestSession.java new file mode 100644 index 0000000..d82922e --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/TestSession.java @@ -0,0 +1,25 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.webmvc.test.autoconfigure.MockMvcBuilderCustomizer; +import org.springframework.context.annotation.Bean; + +import jakarta.servlet.http.Cookie; +import wellatleastitried.mediagarrdclient.service.SessionService; + +@TestConfiguration +public class TestSession { + + @Bean + SessionService sessionService() { + return new SessionService(); + } + + @Bean + MockMvcBuilderCustomizer signedInRequests(SessionService sessions) { + Cookie cookie = new Cookie(SessionGate.COOKIE, sessions.create()); + return builder -> builder.defaultRequest(get("/").cookie(cookie).header(CsrfCheck.HEADER, "1")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/WebhookControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/WebhookControllerTest.java new file mode 100644 index 0000000..e37e6d0 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/WebhookControllerTest.java @@ -0,0 +1,128 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.ResourceAccessException; + +import wellatleastitried.mediagarrdclient.dto.WebhookStatusDto; +import wellatleastitried.mediagarrdclient.dto.WebhookTestDto; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.PairingRequiredException; +import wellatleastitried.mediagarrdclient.service.ServerApiService; + +@WebMvcTest(controllers = WebhookController.class) +@Import(TestSession.class) +class WebhookControllerTest { + + private static final String SERVER = "http://server:8080"; + + @Autowired + MockMvc mockMvc; + + @MockitoBean + ClientStateService stateService; + + @MockitoBean + ServerApiService serverApiService; + + @BeforeEach + void setUp() { + when(stateService.requireActiveServer()).thenReturn(SERVER); + } + + @Test + void forwardsTheStatusReadToTheActiveServer() throws Exception { + when(serverApiService.webhook(SERVER)).thenReturn(new WebhookStatusDto(true, "https://hooks.slack.com")); + + mockMvc.perform(get("/api/client/notifications/webhook")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.configured").value(true)) + .andExpect(jsonPath("$.target").value("https://hooks.slack.com")); + } + + @Test + void forwardsASetAndAClear() throws Exception { + when(serverApiService.updateWebhook(SERVER, "https://hooks.slack.com/services/T/B/X")).thenReturn(new WebhookStatusDto(true, "https://hooks.slack.com")); + when(serverApiService.updateWebhook(SERVER, "")).thenReturn(new WebhookStatusDto(false, null)); + + mockMvc.perform(put("/api/client/notifications/webhook").contentType(MediaType.APPLICATION_JSON).content("{\"url\":\"https://hooks.slack.com/services/T/B/X\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.configured").value(true)); + mockMvc.perform(put("/api/client/notifications/webhook").contentType(MediaType.APPLICATION_JSON).content("{\"url\":\"\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.configured").value(false)); + } + + @Test + void forwardsTheTestAndItsResult() throws Exception { + when(serverApiService.testWebhook(SERVER)).thenReturn(new WebhookTestDto(true, 204, null)); + + mockMvc.perform(post("/api/client/notifications/webhook/test")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.delivered").value(true)) + .andExpect(jsonPath("$.status").value(204)); + } + + @Test + void passesTheServersValidationMessageThrough() throws Exception { + when(serverApiService.updateWebhook(SERVER, "ftp://x")).thenThrow(rejected(HttpStatus.BAD_REQUEST, new HttpHeaders(), "Webhook URL must use http or https")); + + mockMvc.perform(put("/api/client/notifications/webhook").contentType(MediaType.APPLICATION_JSON).content("{\"url\":\"ftp://x\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Webhook URL must use http or https")); + } + + @Test + void passesTheTestCooldownAndItsRetryAfterThrough() throws Exception { + HttpHeaders headers = new HttpHeaders(); + headers.add(HttpHeaders.RETRY_AFTER, "8"); + when(serverApiService.testWebhook(SERVER)).thenThrow(rejected(HttpStatus.TOO_MANY_REQUESTS, headers, "Wait 8 seconds before sending another test")); + + mockMvc.perform(post("/api/client/notifications/webhook/test")) + .andExpect(status().isTooManyRequests()) + .andExpect(header().string(HttpHeaders.RETRY_AFTER, "8")) + .andExpect(jsonPath("$.error").value("Wait 8 seconds before sending another test")); + } + + @Test + void reportsAnUnreachableServerAndAMissingPairing() throws Exception { + when(serverApiService.webhook(SERVER)).thenThrow(new ResourceAccessException("Connection refused")); + when(serverApiService.testWebhook(SERVER)).thenThrow(new PairingRequiredException("Pair with the server first")); + + mockMvc.perform(get("/api/client/notifications/webhook")) + .andExpect(status().isBadGateway()) + .andExpect(jsonPath("$.error").value("MediaGarrd server is unreachable")); + mockMvc.perform(post("/api/client/notifications/webhook/test")) + .andExpect(status().isBadGateway()) + .andExpect(jsonPath("$.pairing").value("required")); + } + + @Test + void theUpdateRequestDoesNotPrintTheUrl() { + org.junit.jupiter.api.Assertions.assertFalse( + new wellatleastitried.mediagarrdclient.dto.WebhookUpdateRequest("https://discord.com/api/webhooks/1/SECRETTOKEN").toString().contains("SECRETTOKEN")); + } + + private static HttpClientErrorException rejected(HttpStatus status, HttpHeaders headers, String message) { + HttpClientErrorException e = HttpClientErrorException.create(status, status.getReasonPhrase(), headers, new byte[0], java.nio.charset.StandardCharsets.UTF_8); + e.setBodyConvertFunction(type -> new ApiExceptionHandler.ServerError(message)); + return e; + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/golden/Fixtures.java b/src/test/java/wellatleastitried/mediagarrdclient/golden/Fixtures.java new file mode 100644 index 0000000..0efa996 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/golden/Fixtures.java @@ -0,0 +1,23 @@ +package wellatleastitried.mediagarrdclient.golden; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; + +public final class Fixtures { + + private Fixtures() { + } + + public static String read(String name) { + try (InputStream in = Fixtures.class.getResourceAsStream("/golden/" + name)) { + if (in == null) { + throw new IllegalArgumentException("Missing fixture " + name); + } + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java new file mode 100644 index 0000000..916225c --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java @@ -0,0 +1,288 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; +import wellatleastitried.mediagarrdclient.dto.PickupStartDto; + +class BackupPickupServiceTest { + + private static final String SERVER = "http://server:8080"; + private static final BackupDto LATEST = new BackupDto("b2", "b2-media-backup.zip", 4, Instant.EPOCH); + private static final BackupDto OLDER = new BackupDto("b1", "b1-media-backup.zip", 4, Instant.EPOCH); + + @TempDir + Path downloads; + + private final ClientStateService state = mock(ClientStateService.class); + private final ServerApiService api = mock(ServerApiService.class); + private final MutableClock clock = new MutableClock(); + private BackupPickupService pickup; + + @BeforeEach + void setUp() { + MediaGarrdProperties configuration = new MediaGarrdProperties(); + configuration.setDownloadDirectory(downloads.toString()); + when(state.requireActiveServer()).thenReturn(SERVER); + when(state.getActiveServer()).thenReturn(SERVER); + when(state.hasPairing(SERVER)).thenReturn(true); + when(state.getPickupInterval()).thenReturn(Duration.ofHours(1)); + when(api.listBackups(SERVER)).thenReturn(List.of(LATEST, OLDER)); + pickup = new BackupPickupService(configuration, state, api, clock); + } + + @AfterEach + void tearDown() { + pickup.shutdown(); + } + + @Test + void downloadsTheLatestBackup() throws Exception { + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> invocation.getArgument(2)); + + PickupStartDto started = pickup.startPickupLatestTask(); + PickupProgressDto progress = awaitFinished(started.taskId()); + + assertEquals("COMPLETED", progress.status()); + assertEquals(downloads.resolve("b2-media-backup.zip").toString(), progress.savedPath()); + } + + @Test + void reusesTheRunningTaskForTheSameBackup() throws Exception { + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + release.await(5, TimeUnit.SECONDS); + return invocation.getArgument(2); + }); + + PickupStartDto first = pickup.startPickupLatestTask(); + PickupStartDto second = pickup.startPickupByIdTask("b2"); + release.countDown(); + awaitFinished(first.taskId()); + + assertEquals(first.taskId(), second.taskId()); + verify(api, times(1)).downloadById(anyString(), anyString(), any(), any()); + } + + @Test + void reusesAnExistingDownload() throws Exception { + Files.write(downloads.resolve("b1-media-backup.zip"), new byte[4]); + + PickupProgressDto progress = pickup.pickupProgress(pickup.startPickupByIdTask("b1").taskId()); + + assertEquals("COMPLETED", progress.status()); + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + } + + @Test + void reportsDownloadFailures() throws Exception { + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenThrow(new DownloadFailedException("disk full")); + + PickupProgressDto progress = awaitFinished(pickup.startPickupLatestTask().taskId()); + + assertEquals("FAILED", progress.status()); + assertEquals("disk full", progress.error()); + } + + @Test + void forgetsFinishedTasksAfterTheRetentionPeriod() throws Exception { + Files.write(downloads.resolve("b1-media-backup.zip"), new byte[4]); + String taskId = pickup.startPickupByIdTask("b1").taskId(); + + clock.advance(BackupPickupService.FINISHED_TASK_RETENTION.plusSeconds(1)); + pickup.startPickupByIdTask("b1"); + + assertThrows(NotFoundException.class, () -> pickup.pickupProgress(taskId)); + } + + @Test + void rejectsUnknownBackupsAndTasks() { + assertThrows(NotFoundException.class, () -> pickup.startPickupByIdTask("missing")); + assertThrows(NotFoundException.class, () -> pickup.pickupProgress("missing")); + when(api.listBackups(SERVER)).thenReturn(List.of()); + assertThrows(NotFoundException.class, () -> pickup.startPickupLatestTask()); + } + + @Test + void refusesFileNamesThatLeaveTheDownloadDirectory() { + when(api.listBackups(SERVER)).thenReturn(List.of(new BackupDto("evil", "../evil.zip", 4, Instant.EPOCH))); + + assertThrows(InvalidRequestException.class, () -> pickup.startPickupLatestTask()); + } + + @Test + void aRefusedFileNameLeavesNoStuckTaskBehind() { + when(api.listBackups(SERVER)).thenReturn(List.of(new BackupDto("evil", "../evil.zip", 4, Instant.EPOCH))); + + assertThrows(InvalidRequestException.class, () -> pickup.startPickupByIdTask("evil")); + assertThrows(InvalidRequestException.class, () -> pickup.startPickupByIdTask("evil")); + + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + } + + @Test + void aFailedDownloadReportsAGenericMessageInsteadOfItsDetails() throws Exception { + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenThrow(new IllegalStateException("cannot write /var/lib/mediagarrd/downloads/b2.part")); + + PickupProgressDto progress = awaitFinished(pickup.startPickupLatestTask().taskId()); + + assertEquals("FAILED", progress.status()); + assertEquals(BackupPickupService.GENERIC_FAILURE, progress.error()); + } + + @Test + void scheduledPickupDoesNotBlockTheSchedulerThread() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + AtomicBoolean downloadFinished = new AtomicBoolean(); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(10, TimeUnit.SECONDS); + downloadFinished.set(true); + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + clock.advance(Duration.ofHours(2)); + + pickup.scheduledPickup(); + boolean returnedWhileDownloading = !downloadFinished.get(); + assertTrue(started.await(5, TimeUnit.SECONDS)); + pickup.scheduledPickup(); + clock.advance(Duration.ofHours(2)); + pickup.scheduledPickup(); + release.countDown(); + + assertTrue(returnedWhileDownloading, "the scheduler thread waited for the download"); + verify(api, timeout(5000).times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + } + + @Test + void scheduledPickupNeverDeletesAUsersCopyOfTheLatestArchive() throws IOException { + Files.write(downloads.resolve("b2-media-backup.zip"), new byte[4]); + + clock.advance(Duration.ofHours(2)); + pickup.runScheduledPickup(); + + assertEquals(List.of("b2-media-backup.zip"), fileNames()); + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + } + + @Test + void scheduledPickupKeepsOnlyTheLatestAutomaticDownload() throws IOException { + Files.write(downloads.resolve("b1-media-backup-AD.zip"), new byte[4]); + Files.write(downloads.resolve("b2-media-backup.zip"), new byte[3]); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + + clock.advance(Duration.ofHours(2)); + pickup.runScheduledPickup(); + + assertEquals(List.of("b2-media-backup-AD.zip", "b2-media-backup.zip"), fileNames()); + } + + @Test + void scheduledPickupRemovesOnlyOlderListedAutomaticDownloads() throws IOException { + BackupDto older = new BackupDto("b0", "b0-media-backup.zip", 4, Instant.EPOCH); + BackupDto newer = new BackupDto("b3", "b3-media-backup.zip", 4, Instant.EPOCH); + when(api.listBackups(SERVER)).thenReturn(List.of(LATEST, OLDER, older)); + Files.write(downloads.resolve("b1-media-backup-AD.zip"), new byte[4]); + Files.write(downloads.resolve("b0-media-backup-AD.zip"), new byte[4]); + Files.write(downloads.resolve("b3-media-backup-AD.zip"), new byte[4]); + Files.write(downloads.resolve("other-server-media-backup-AD.zip"), new byte[4]); + Files.write(downloads.resolve("notes-AD.zip"), new byte[4]); + Files.write(downloads.resolve("b1-media-backup.zip"), new byte[4]); + Files.createDirectory(downloads.resolve("b0-media-backup-AD.zip.dir")); + Path outside = Files.write(downloads.resolve("outside.bin"), new byte[4]); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + + clock.advance(Duration.ofHours(2)); + pickup.runScheduledPickup(); + + assertEquals(List.of("b0-media-backup-AD.zip.dir", "b1-media-backup.zip", "b2-media-backup-AD.zip", "b3-media-backup-AD.zip", + "notes-AD.zip", "other-server-media-backup-AD.zip", "outside.bin"), fileNames()); + assertTrue(Files.exists(outside)); + } + + @Test + void scheduledPickupDoesNotFollowSymlinksWhenRemovingSupersededDownloads() throws IOException { + Path target = Files.write(downloads.resolve("target.bin"), new byte[4]); + Files.createSymbolicLink(downloads.resolve("b1-media-backup-AD.zip"), target); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + Path destination = invocation.getArgument(2); + Files.write(destination, new byte[4]); + return destination; + }); + + clock.advance(Duration.ofHours(2)); + pickup.runScheduledPickup(); + + assertTrue(Files.isSymbolicLink(downloads.resolve("b1-media-backup-AD.zip"))); + assertTrue(Files.exists(target)); + } + + @Test + void refusesArchiveNamesThatAreNotZipFilesBeforeDownloading() { + for (String name : List.of("evil.part", "evil.tar", "evil.zip.part", "evil")) { + when(api.listBackups(SERVER)).thenReturn(List.of(new BackupDto("evil", name, 4, Instant.EPOCH))); + + assertThrows(InvalidRequestException.class, () -> pickup.startPickupLatestTask()); + assertThrows(InvalidRequestException.class, () -> pickup.startPickupByIdTask("evil")); + pickup.runScheduledPickup(); + } + + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + } + + private PickupProgressDto awaitFinished(String taskId) throws InterruptedException { + for (int attempt = 0; attempt < 200; attempt++) { + PickupProgressDto progress = pickup.pickupProgress(taskId); + if (progress.status().equals("COMPLETED") || progress.status().equals("FAILED")) { + return progress; + } + Thread.sleep(10); + } + throw new AssertionError("Pickup task " + taskId + " did not finish"); + } + + private List fileNames() throws IOException { + try (var files = Files.list(downloads)) { + return files.map(path -> path.getFileName().toString()).sorted().toList(); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientPairingServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientPairingServiceTest.java new file mode 100644 index 0000000..a37aaf6 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientPairingServiceTest.java @@ -0,0 +1,360 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +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 org.springframework.web.client.ResourceAccessException; + +import tools.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.dto.UnpairResultDto; + +class ClientPairingServiceTest { + + private static final String SERVER = "http://server:38471"; + + @TempDir + Path tempDir; + + private ClientStateService state; + private ServerApiService api; + private ClientPairingService pairing; + private final List pauses = new ArrayList<>(); + + @BeforeEach + void setUp() { + MediaGarrdProperties configuration = new MediaGarrdProperties(); + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(Duration.ofHours(12)); + state = new ClientStateService(configuration, JsonMapper.builder().build()); + state.setActiveServer(SERVER); + api = mock(ServerApiService.class); + pauses.clear(); + pairing = new ClientPairingService(state, api, pauses::add); + } + + @Test + void storesTheTokenForTheActiveServerAndReturnsNoToken() { + when(api.pair(SERVER, "123456", "MediaGarrd Client")).thenReturn(new StoredPairing("tok", "id1", "MediaGarrd Client")); + + var result = pairing.pair(" 123456 ", null); + + assertTrue(result.paired()); + assertEquals("tok", state.tokenFor(SERVER).orElseThrow()); + assertFalse(result.toString().contains("tok")); + } + + @Test + void refusesABlankCredentialWithoutCallingTheServer() { + assertThrows(InvalidRequestException.class, () -> pairing.pair(" ", null)); + verify(api, never()).pair(anyString(), anyString(), anyString()); + } + + @Test + void refusesAnOverlongCredentialOrNameWithoutCallingTheServer() { + assertThrows(InvalidRequestException.class, () -> pairing.pair("1".repeat(ClientPairingService.MAX_CREDENTIAL_LENGTH + 1), null)); + assertThrows(InvalidRequestException.class, () -> pairing.pair("123456", "n".repeat(ClientPairingService.MAX_NAME_LENGTH + 1))); + verify(api, never()).pair(anyString(), anyString(), anyString()); + } + + @Test + void refusesToPairAgainWhileTheStoredTokenStillWorks() { + state.storePairing(SERVER, new StoredPairing("old-tok", "old-id", "Home")); + + ConflictException e = assertThrows(ConflictException.class, () -> pairing.pair("123456", "Home")); + + assertEquals(ClientPairingService.ALREADY_PAIRED_MESSAGE, e.getMessage()); + verify(api).confirmPairing(SERVER, "old-tok"); + verify(api, never()).pair(anyString(), anyString(), anyString()); + assertEquals("old-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void pairsAgainWhenTheServerRefusesTheStoredToken() { + state.storePairing(SERVER, new StoredPairing("old-tok", "old-id", "Home")); + doThrow(new InvalidRequestException("no")).when(api).confirmPairing(SERVER, "old-tok"); + when(api.pair(SERVER, "123456", "Home")).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + + var result = pairing.pair("123456", "Home"); + + assertTrue(result.paired()); + assertNull(result.note()); + assertEquals("new-tok", state.tokenFor(SERVER).orElseThrow()); + verify(api, never()).revokeClient(anyString(), anyString()); + } + + @Test + void refusesToPairWhenTheStoredTokenCannotBeProbed() { + state.storePairing(SERVER, new StoredPairing("old-tok", "old-id", "Home")); + doThrow(new ResourceAccessException("down")).when(api).confirmPairing(SERVER, "old-tok"); + + assertThrows(ResourceAccessException.class, () -> pairing.pair("123456", "Home")); + + verify(api, never()).pair(anyString(), anyString(), anyString()); + assertEquals("old-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void aFailedNewPairingKeepsTheDeadStoredToken() { + state.storePairing(SERVER, new StoredPairing("old-tok", "old-id", "Home")); + doThrow(new InvalidRequestException("no")).when(api).confirmPairing(SERVER, "old-tok"); + when(api.pair(anyString(), anyString(), anyString())).thenThrow(new InvalidRequestException("Invalid PIN")); + + assertThrows(InvalidRequestException.class, () -> pairing.pair("000000", "Home")); + + assertEquals("old-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void unpairingWithoutAStoredIdOrPairingExplainsWhy() { + assertEquals(ClientPairingService.NOT_PAIRED_WARNING, pairing.unpair().warning()); + state.storePairing(SERVER, new StoredPairing("tok", null, "Home")); + + UnpairResultDto result = pairing.unpair(); + + assertFalse(result.serverRevoked()); + assertEquals(ClientPairingService.NO_ID_WARNING, result.warning()); + } + + @Test + void aFailedPairingStoresNothing() { + when(api.pair(anyString(), anyString(), anyString())).thenThrow(new ResourceAccessException("down")); + + assertThrows(ResourceAccessException.class, () -> pairing.pair("123456", "Home")); + + assertFalse(state.hasPairing(SERVER)); + } + + @Test + void unpairingRevokesOnTheServerAndForgetsTheToken() { + state.storePairing(SERVER, new StoredPairing("tok", "id1", "Home")); + + UnpairResultDto result = pairing.unpair(); + + assertTrue(result.serverRevoked()); + assertNull(result.warning()); + verify(api).revokeClient(SERVER, "id1"); + assertFalse(state.hasPairing(SERVER)); + } + + @Test + void unpairingForgetsTheTokenEvenWhenTheServerIsUnreachable() { + state.storePairing(SERVER, new StoredPairing("tok", "id1", "Home")); + doThrow(new ResourceAccessException("down")).when(api).revokeClient(SERVER, "id1"); + + UnpairResultDto result = pairing.unpair(); + + assertFalse(result.serverRevoked()); + assertEquals(ClientPairingService.UNREVOKED_WARNING, result.warning()); + assertFalse(state.hasPairing(SERVER)); + } + + @Test + void unpairingForgetsTheTokenEvenWhenTheServerRejectsIt() { + state.storePairing(SERVER, new StoredPairing("tok", "id1", "Home")); + doThrow(new PairingRequiredException("rejected")).when(api).revokeClient(SERVER, "id1"); + + assertFalse(pairing.unpair().serverRevoked()); + assertFalse(state.hasPairing(SERVER)); + } + + @Test + void storesThePairingBeforeConfirmingIt() { + when(api.pair(SERVER, "123456", "MediaGarrd Client")).thenReturn(new StoredPairing("tok", "id1", "MediaGarrd Client")); + doAnswer(call -> { + assertEquals("tok", state.tokenFor(SERVER).orElseThrow()); + return null; + }).when(api).confirmPairing(SERVER, "tok"); + + var result = pairing.pair("123456", null); + + assertTrue(result.paired()); + assertNull(result.note()); + verify(api).confirmPairing(SERVER, "tok"); + assertEquals("tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void aRefusedConfirmationForgetsTheNewPairing() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new InvalidRequestException("The server did not accept this pairing")).when(api).confirmPairing(SERVER, "new-tok"); + + assertThrows(InvalidRequestException.class, () -> pairing.pair("123456", "Home")); + + assertFalse(state.hasPairing(SERVER)); + verify(api, times(1)).confirmPairing(SERVER, "new-tok"); + assertTrue(pauses.isEmpty()); + } + + @Test + void aPublicOnlyConfirmationForgetsTheNewPairing() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new ConfirmationRefusedException("not a confirmation")).when(api).confirmPairing(SERVER, "new-tok"); + + assertThrows(ConfirmationRefusedException.class, () -> pairing.pair("123456", "Home")); + + assertFalse(state.hasPairing(SERVER)); + } + + @Test + void aRefusedConfirmationDoesNotForgetANewerPairingStoredMeanwhile() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doAnswer(call -> { + state.storePairing(SERVER, new StoredPairing("newer-tok", "newer-id", "Home")); + throw new InvalidRequestException("no"); + }).when(api).confirmPairing(SERVER, "new-tok"); + + assertThrows(InvalidRequestException.class, () -> pairing.pair("123456", "Home")); + + assertEquals("newer-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void aServerErrorOnConfirmationKeepsTheTokenAndReturnsTheNote() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new UpstreamResponseException("status 500")).when(api).confirmPairing(SERVER, "new-tok"); + + var result = pairing.pair("123456", "Home"); + + assertTrue(result.paired()); + assertEquals(ClientPairingService.DEFERRED_CONFIRMATION_NOTE, result.note()); + assertEquals("new-tok", state.tokenFor(SERVER).orElseThrow()); + verify(api, times(1)).confirmPairing(SERVER, "new-tok"); + } + + @Test + void aRedirectOrAnInterruptedRetryOnConfirmationKeepsTheToken() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new ServerRedirectException(302, "http://elsewhere")).when(api).confirmPairing(SERVER, "new-tok"); + + assertEquals(ClientPairingService.DEFERRED_CONFIRMATION_NOTE, pairing.pair("123456", "Home").note()); + assertEquals("new-tok", state.tokenFor(SERVER).orElseThrow()); + + state.forgetPairing(SERVER); + doThrow(new ResourceAccessException("down")).when(api).confirmPairing(SERVER, "new-tok"); + ClientPairingService interrupted = new ClientPairingService(state, api, millis -> { + throw new UpstreamResponseException("interrupted"); + }); + + assertEquals(ClientPairingService.DEFERRED_CONFIRMATION_NOTE, interrupted.pair("123456", "Home").note()); + assertEquals("new-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void retriesTheConfirmationAfterAGatewayErrorAndStoresTheToken() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new ConfirmationUnavailableException("status 502")).doThrow(new ConfirmationUnavailableException("status 504")).doNothing() + .when(api).confirmPairing(SERVER, "new-tok"); + + var result = pairing.pair("123456", "Home"); + + assertNull(result.note()); + verify(api, times(3)).confirmPairing(SERVER, "new-tok"); + assertEquals(List.of(250L, 500L), pauses); + assertEquals("new-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void retriesTheConfirmationAfterANetworkErrorWithBackoff() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new ResourceAccessException("reset")).doThrow(new ResourceAccessException("reset")).doNothing() + .when(api).confirmPairing(SERVER, "new-tok"); + + assertNull(pairing.pair("123456", "Home").note()); + + verify(api, times(3)).confirmPairing(SERVER, "new-tok"); + assertEquals(List.of(250L, 500L), pauses); + assertEquals("new-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void givesUpOnTheConfirmationAfterThreeRetriesButKeepsTheTokenAndReturnsTheNote() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new ResourceAccessException("down")).when(api).confirmPairing(SERVER, "new-tok"); + + var result = pairing.pair("123456", "Home"); + + assertTrue(result.paired()); + assertEquals(ClientPairingService.DEFERRED_CONFIRMATION_NOTE, result.note()); + verify(api, times(4)).confirmPairing(SERVER, "new-tok"); + assertEquals(List.of(250L, 500L, 1000L), pauses); + assertEquals("new-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void aDeferredPairingSurvivesARestartOfTheState() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new ResourceAccessException("down")).when(api).confirmPairing(SERVER, "new-tok"); + pairing.pair("123456", "Home"); + + MediaGarrdProperties configuration = new MediaGarrdProperties(); + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(Duration.ofHours(12)); + ClientStateService reloaded = new ClientStateService(configuration, JsonMapper.builder().build()); + + assertEquals("new-tok", reloaded.tokenFor(SERVER).orElseThrow()); + } + + @Test + void concurrentPairingsRunOneAfterTheOther() throws Exception { + AtomicInteger inside = new AtomicInteger(); + AtomicInteger overlaps = new AtomicInteger(); + when(api.pair(anyString(), anyString(), anyString())).thenAnswer(call -> { + if (inside.incrementAndGet() > 1) { + overlaps.incrementAndGet(); + } + Thread.sleep(100); + inside.decrementAndGet(); + return new StoredPairing("tok", "id", "Home"); + }); + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + Future first = pool.submit(() -> pairing.pair("123456", "Home")); + Future second = pool.submit(() -> pairing.pair("123456", "Home")); + int successes = 0; + int conflicts = 0; + for (Future f : List.of(first, second)) { + try { + f.get(10, TimeUnit.SECONDS); + successes++; + } catch (ExecutionException e) { + assertTrue(e.getCause() instanceof ConflictException, e.getCause().toString()); + conflicts++; + } + } + assertEquals(1, successes); + assertEquals(1, conflicts); + } finally { + pool.shutdownNow(); + } + + assertEquals(0, overlaps.get()); + verify(api, times(1)).pair(anyString(), anyString(), anyString()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java new file mode 100644 index 0000000..a7b33f0 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java @@ -0,0 +1,449 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +import tools.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; + +class ClientStateServiceTest { + + private static final JsonMapper MAPPER = JsonMapper.builder().build(); + + @TempDir + Path tempDir; + + private final MediaGarrdProperties configuration = new MediaGarrdProperties(); + + @BeforeEach + void setUp() { + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(Duration.ofHours(12)); + } + + @Test + void persistsAndLoadsState() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.updateKnownServers(List.of("http://a:8080", "http://b:8080")); + state.setActiveServer("http://b:8080"); + state.setPickupInterval(Duration.ofMinutes(30)); + + ClientStateService reloaded = new ClientStateService(configuration, MAPPER); + assertEquals("http://b:8080", reloaded.getActiveServer()); + assertEquals(Duration.ofMinutes(30), reloaded.getPickupInterval()); + assertEquals(List.of("http://a:8080", "http://b:8080"), reloaded.getKnownServers()); + assertEquals(List.of("state.json"), fileNames()); + } + + @Test + void aCorruptStateFileIsMovedAsideInsteadOfBeingOverwritten() throws IOException { + Path file = tempDir.resolve("state.json"); + Files.writeString(file, "{\"activeServer\": \"http://a:8080\", \"pairings\": {broken"); + + ClientStateService state = new ClientStateService(configuration, MAPPER); + assertNull(state.getActiveServer()); + assertEquals(Duration.ofHours(12), state.getPickupInterval()); + state.setActiveServer("http://b:8080"); + + List moved = fileNames().stream().filter(name -> name.startsWith("state.json.corrupt-")).toList(); + assertEquals(1, moved.size()); + assertEquals("{\"activeServer\": \"http://a:8080\", \"pairings\": {broken", Files.readString(tempDir.resolve(moved.getFirst()))); + assertEquals("http://b:8080", new ClientStateService(configuration, MAPPER).getActiveServer()); + } + + @Test + void aStateFileThatHoldsNullIsMovedAsideToo() throws IOException { + Files.writeString(tempDir.resolve("state.json"), "null"); + + ClientStateService state = new ClientStateService(configuration, MAPPER); + + assertNull(state.getActiveServer()); + assertTrue(fileNames().stream().anyMatch(name -> name.startsWith("state.json.corrupt-"))); + assertFalse(Files.exists(tempDir.resolve("state.json"))); + } + + @Test + void aFailedSaveLeavesTheStateInMemoryUnchanged() throws IOException { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.setActiveServer("http://a:8080"); + state.storePairing("http://a:8080", new StoredPairing("tok", "id1", "Laptop")); + Path blocker = tempDir.resolve("blocked"); + Files.writeString(blocker, "not a directory"); + Path file = tempDir.resolve("blocked").resolve("state.json"); + configuration.setStateFile(file.toString()); + ClientStateService failing = new ClientStateService(configuration, MAPPER); + + assertThrows(IllegalStateException.class, () -> failing.setPickupInterval(Duration.ofMinutes(5))); + assertThrows(IllegalStateException.class, () -> failing.setActiveServer("http://b:8080")); + assertThrows(IllegalStateException.class, () -> failing.storePairing("http://b:8080", new StoredPairing("t2", "id2", "x"))); + assertThrows(IllegalStateException.class, () -> failing.updateKnownServers(List.of("http://c:8080"))); + + assertEquals(Duration.ofHours(12), failing.getPickupInterval()); + assertNull(failing.getActiveServer()); + assertFalse(failing.hasPairing("http://b:8080")); + assertEquals(List.of(), failing.getKnownServers()); + } + + @Test + void aFailedSaveKeepsAStoredPairing() throws IOException { + configuration.setStateFile(tempDir.resolve("state.json").toString()); + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.storePairing("http://a:8080", new StoredPairing("tok", "id1", "Laptop")); + Files.delete(tempDir.resolve("state.json")); + Files.createDirectory(tempDir.resolve("state.json")); + Files.writeString(tempDir.resolve("state.json").resolve("x"), "x"); + + assertThrows(IllegalStateException.class, () -> state.forgetPairing("http://a:8080")); + + assertTrue(state.hasPairing("http://a:8080")); + } + + @Test + void knowsWhichServersWereAlreadySelected() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.setActiveServer("http://a:8080"); + + assertTrue(state.isKnownServer("http://a:8080/")); + assertFalse(state.isKnownServer("http://z:8080")); + } + + @Test + void setsTheActiveServerOnlyWhileNoneIsSelected() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + List notified = new ArrayList<>(); + state.addActiveServerListener(notified::add); + + state.setActiveServerIfBlank("http://a:8080"); + state.setActiveServerIfBlank("http://b:8080"); + state.setActiveServerIfBlank(" "); + + assertEquals("http://a:8080", state.getActiveServer()); + assertEquals(List.of("http://a:8080"), state.getKnownServers()); + assertEquals(List.of("http://a:8080"), notified); + assertEquals("http://a:8080", new ClientStateService(configuration, MAPPER).getActiveServer()); + } + + @Test + void keepsTheActiveServerWhenARescanDoesNotFindIt() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.setActiveServer("http://a:8080"); + + state.updateKnownServers(List.of("http://b:8080")); + + assertEquals("http://a:8080", state.getActiveServer()); + assertEquals(List.of("http://a:8080", "http://b:8080"), state.getKnownServers()); + } + + @Test + void aScanMergesFoundServersIntoTheKnownOnesWithoutDroppingAny() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.updateKnownServers(List.of("http://a:8080", "https://garrd.example.com")); + state.setActiveServer("http://a:8080"); + + state.updateKnownServers(List.of("http://c:8080", "http://a:8080")); + + assertEquals("http://a:8080", state.getActiveServer()); + assertEquals(List.of("http://a:8080", "https://garrd.example.com", "http://c:8080"), state.getKnownServers()); + assertEquals(state.getKnownServers(), new ClientStateService(configuration, MAPPER).getKnownServers()); + } + + @Test + void anEmptyScanKeepsTheKnownServers() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.updateKnownServers(List.of("http://a:8080", "http://b:8080")); + + state.updateKnownServers(List.of()); + + assertEquals(List.of("http://a:8080", "http://b:8080"), state.getKnownServers()); + assertEquals("http://a:8080", state.getActiveServer()); + } + + @Test + void selectsTheFirstDiscoveredServerWhenNoneIsActive() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + + state.updateKnownServers(List.of("http://b:8080", "http://b:8080", "http://c:8080")); + + assertEquals("http://b:8080", state.getActiveServer()); + assertEquals(List.of("http://b:8080", "http://c:8080"), state.getKnownServers()); + } + + @Test + void rejectsNonPositivePickupIntervals() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + + assertThrows(InvalidRequestException.class, () -> state.setPickupInterval(Duration.ZERO)); + assertThrows(InvalidRequestException.class, () -> state.setPickupInterval(null)); + assertEquals(Duration.ofHours(12), state.getPickupInterval()); + } + + @Test + void rejectsPickupIntervalsAboveOneYear() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + + state.setPickupInterval(Duration.ofDays(365)); + InvalidRequestException tooLong = assertThrows(InvalidRequestException.class, () -> state.setPickupInterval(Duration.ofDays(365).plusSeconds(1))); + + assertTrue(tooLong.getMessage().contains("365 days"), tooLong.getMessage()); + assertEquals(Duration.ofDays(365), state.getPickupInterval()); + } + + @Test + void anOutOfRangeStoredOrConfiguredIntervalFallsBackToTheDefault() throws IOException { + Files.writeString(tempDir.resolve("state.json"), "{\"activeServer\":\"http://a:8080\",\"pickupIntervalSeconds\":999999999,\"knownServers\":[\"http://a:8080\"]}"); + + ClientStateService stored = new ClientStateService(configuration, MAPPER); + assertEquals(Duration.ofHours(12), stored.getPickupInterval()); + assertEquals("http://a:8080", stored.getActiveServer()); + + configuration.setPickupInterval(Duration.ofDays(4000)); + Files.delete(tempDir.resolve("state.json")); + assertEquals(Duration.ofHours(12), new ClientStateService(configuration, MAPPER).getPickupInterval()); + } + + @Test + void anUnreadableStateFileFailsStartupAndIsLeftInPlace() throws IOException { + Path file = tempDir.resolve("state.json"); + String content = "{\"activeServer\":\"http://a:8080\",\"pickupIntervalSeconds\":60,\"knownServers\":[\"http://a:8080\"]}"; + Files.writeString(file, content); + Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("---------")); + org.junit.jupiter.api.Assumptions.assumeFalse(Files.isReadable(file), "the tests run as a user that ignores file permissions"); + try { + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> new ClientStateService(configuration, MAPPER)); + + assertTrue(failure.getMessage().contains(file.toString()), failure.getMessage()); + assertTrue(failure.getMessage().contains("UID"), failure.getMessage()); + assertEquals(List.of("state.json"), fileNames()); + } finally { + Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("rw-------")); + } + assertEquals(content, Files.readString(file)); + } + + @Test + void aStateFileThatFailsWithAnIoErrorFailsStartupInsteadOfBeingMovedAside() throws IOException { + Path file = tempDir.resolve("state.json"); + Files.createDirectory(file); + + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> new ClientStateService(configuration, MAPPER)); + + assertTrue(failure.getMessage().contains(file.toString()), failure.getMessage()); + assertTrue(Files.isDirectory(file)); + assertEquals(List.of("state.json"), fileNames()); + } + + @Test + void requiresAnActiveServer() { + assertThrows(InvalidRequestException.class, () -> new ClientStateService(configuration, MAPPER).requireActiveServer()); + } + + private List fileNames() { + try (var files = Files.list(tempDir)) { + return files.map(path -> path.getFileName().toString()).sorted().toList(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + @Test + void notifiesListenersOnlyWhenTheActiveServerChanges() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + List notified = new ArrayList<>(); + state.addActiveServerListener(notified::add); + + state.setActiveServer("http://a:8080"); + state.setActiveServer("http://a:8080"); + state.updateKnownServers(List.of("http://b:8080")); + state.setActiveServer("http://b:8080"); + state.setActiveServer(""); + + assertEquals(List.of("http://a:8080", "http://b:8080", ""), notified); + } + + @Test + void notifiesListenersWhenARescanPicksTheFirstActiveServer() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + List notified = new ArrayList<>(); + state.addActiveServerListener(notified::add); + + state.updateKnownServers(List.of("http://a:8080", "http://b:8080")); + state.updateKnownServers(List.of("http://b:8080")); + + assertEquals(List.of("http://a:8080"), notified); + } + + @Test + @Timeout(10) + void notifiesListenersWithoutHoldingTheStateLock() throws InterruptedException { + ClientStateService state = new ClientStateService(configuration, MAPPER); + AtomicReference seenByOtherThread = new AtomicReference<>(); + state.addActiveServerListener(url -> { + Thread reader = new Thread(() -> seenByOtherThread.set(state.getActiveServer())); + reader.start(); + try { + reader.join(5000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + + state.setActiveServer("http://a:8080"); + + assertEquals("http://a:8080", seenByOtherThread.get()); + } + + @Test + void keepsNotifyingWhenAListenerFails() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + List notified = new ArrayList<>(); + state.addActiveServerListener(url -> { + throw new IllegalStateException("boom"); + }); + state.addActiveServerListener(notified::add); + + state.setActiveServer("http://a:8080"); + + assertTrue(notified.contains("http://a:8080")); + } + + @Test + void notifiesKnownServersListenersOnlyWhenTheListChanges() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + int[] calls = {0}; + state.addKnownServersListener(() -> calls[0]++); + + state.updateKnownServers(List.of("http://a:8080", "http://b:8080")); + assertEquals(1, calls[0]); + state.updateKnownServers(List.of("http://a:8080", "http://b:8080")); + assertEquals(1, calls[0]); + state.setActiveServer("http://a:8080"); + assertEquals(1, calls[0]); + state.setActiveServer("http://c:8080"); + assertEquals(2, calls[0]); + state.setActiveServer("http://c:8080"); + assertEquals(2, calls[0]); + state.updateKnownServers(List.of("http://d:8080")); + assertEquals(3, calls[0]); + } + + @Test + @Timeout(10) + void notifiesKnownServersListenersWithoutHoldingTheStateLock() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + AtomicReference> seenByOtherThread = new AtomicReference<>(); + state.addKnownServersListener(() -> { + Thread reader = new Thread(() -> seenByOtherThread.set(state.getKnownServers())); + reader.start(); + try { + reader.join(5000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + + state.updateKnownServers(List.of("http://a:8080")); + + assertEquals(List.of("http://a:8080"), seenByOtherThread.get()); + } + + @Test + void keepsTokensPerNormalizedServerUrlAndReloadsThem() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.storePairing("HTTPS://Garrd.Example.com:443/", new StoredPairing("tok-1", "id-1", "Home")); + state.storePairing("http://10.0.0.5:38471", new StoredPairing("tok-2", "id-2", "Home")); + + ClientStateService reloaded = new ClientStateService(configuration, MAPPER); + + assertEquals("tok-1", reloaded.tokenFor("https://garrd.example.com").orElseThrow()); + assertEquals("tok-1", reloaded.tokenFor("https://garrd.example.com/").orElseThrow()); + assertEquals("tok-2", reloaded.tokenFor("http://10.0.0.5:38471").orElseThrow()); + assertTrue(reloaded.tokenFor("http://10.0.0.5").isEmpty()); + assertTrue(reloaded.tokenFor("https://garrd.example.com:8443").isEmpty()); + assertEquals("id-1", reloaded.pairingFor("https://garrd.example.com").orElseThrow().id()); + } + + @Test + void forgettingAPairingRemovesItFromDiskAndNotifiesListeners() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + List notified = new ArrayList<>(); + state.addPairingListener(notified::add); + state.storePairing("http://a:8080", new StoredPairing("tok", "id", "Home")); + + assertTrue(state.forgetPairing("http://a:8080")); + assertFalse(state.forgetPairing("http://a:8080")); + + assertEquals(List.of("http://a:8080", "http://a:8080"), notified); + assertFalse(new ClientStateService(configuration, MAPPER).hasPairing("http://a:8080")); + assertFalse(readState().contains("tok")); + } + + @Test + void writesTheStateFileReadableByTheOwnerOnly() throws IOException { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.storePairing("http://a:8080", new StoredPairing("tok", "id", "Home")); + state.setPickupInterval(Duration.ofMinutes(5)); + + Path file = tempDir.resolve("state.json"); + if (Files.getFileStore(file).supportsFileAttributeView("posix")) { + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(file))); + } + assertEquals(List.of("state.json"), fileNames()); + } + + @Test + void neverPrintsATokenInTextualForms() { + StoredPairing pairing = new StoredPairing("super-secret-token", "id-1", "Home"); + + assertFalse(pairing.toString().contains("super-secret-token")); + assertFalse(new ClientStateService.ClientState("http://a", 60, null, List.of(), java.util.Map.of("http://a", pairing)).toString().contains("super-secret-token")); + } + + @Test + void migratesStoredServerUrlsToTheirNormalizedForm() throws IOException { + Files.writeString(tempDir.resolve("state.json"), + "{\"activeServer\":\"HTTP://Server:80/\",\"pickupIntervalSeconds\":60,\"knownServers\":[\"http://server\",\"http://other:8080/\"]," + + "\"pairings\":{\"HTTP://Server:80/\":{\"token\":\"tok\",\"id\":\"i\",\"name\":\"n\"}}}"); + + ClientStateService state = new ClientStateService(configuration, MAPPER); + + assertEquals("http://server", state.getActiveServer()); + assertEquals(List.of("http://server", "http://other:8080"), state.getKnownServers()); + assertEquals("tok", state.tokenFor("http://server").orElseThrow()); + } + + @Test + void readsAStateFileWrittenBeforePairingExisted() throws IOException { + Files.writeString(tempDir.resolve("state.json"), "{\"activeServer\":\"http://a:8080\",\"pickupIntervalSeconds\":60,\"knownServers\":[\"http://a:8080\"]}"); + + ClientStateService state = new ClientStateService(configuration, MAPPER); + + assertEquals("http://a:8080", state.getActiveServer()); + assertFalse(state.hasPairing("http://a:8080")); + } + + private String readState() { + try { + return Files.readString(tempDir.resolve("state.json")); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/DashboardServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/DashboardServiceTest.java new file mode 100644 index 0000000..4860911 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/DashboardServiceTest.java @@ -0,0 +1,847 @@ +package wellatleastitried.mediagarrdclient.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.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; +import org.springframework.web.client.ResourceAccessException; + +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.cfg.DateTimeFeature; +import tools.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.DashboardState; +import wellatleastitried.mediagarrdclient.dto.LinkState; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; + +@Timeout(30) +class DashboardServiceTest { + + private static final ObjectMapper MAPPER = JsonMapper.builder() + .findAndAddModules() + .disable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS, DateTimeFeature.WRITE_DURATIONS_AS_TIMESTAMPS) + .build(); + private static final Instant START = Instant.parse("2026-11-12T10:00:00Z"); + private static final String A = "http://a:38471"; + private static final String B = "http://b:38471"; + private static final ServerStatusDto IDLE = new ServerStatusDto(true, false, 5, Duration.ofHours(6)); + private static final ServerStatusDto BUSY = new ServerStatusDto(true, true, 5, Duration.ofHours(6)); + private static final VersionStatusDto SERVER_VERSION = new VersionStatusDto("0.1.0", "0.2.0", "https://example.test/r", true, CheckState.OK, START, null); + private static final VersionStatusDto CLIENT_VERSION = new VersionStatusDto("0.1.0", "0.1.0", null, false, CheckState.OK, START, null); + + @TempDir + Path tempDir; + + private final MutableClock clock = new MutableClock(START); + private final Queue queued = new ArrayDeque<>(); + private final ServerApiService serverApi = mock(ServerApiService.class); + private final UpdateCheckService updateCheck = mock(UpdateCheckService.class); + private ClientStateService state; + private RecordingPublisher publisher; + private DashboardService dashboard; + + @BeforeEach + void setUp() { + MediaGarrdProperties configuration = new MediaGarrdProperties(); + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(Duration.ofHours(12)); + state = new ClientStateService(configuration, MAPPER); + state.storePairing(A, new StoredPairing("token-a", "id-a", "Test")); + state.storePairing(B, new StoredPairing("token-b", "id-b", "Test")); + when(updateCheck.status()).thenReturn(CLIENT_VERSION); + when(serverApi.health(anyString())).thenReturn(IDLE); + when(serverApi.serverVersion(anyString())).thenReturn(SERVER_VERSION); + } + + private void create(Executor executor) { + publisher = new RecordingPublisher(); + dashboard = new DashboardService(state, publisher, serverApi, new VersionService(updateCheck, serverApi, clock), updateCheck, MAPPER, executor, clock); + dashboard.start(); + } + + private void create() { + create(Runnable::run); + } + + private RecordingPublisher subscribe() { + return dashboard.subscribe(publisher::subscribe).orElseThrow(); + } + + private static List drain(RecordingPublisher emitter) throws InterruptedException { + List events = new ArrayList<>(); + String next; + while ((next = emitter.sent.poll(150, TimeUnit.MILLISECONDS)) != null) { + events.add(next); + } + return events; + } + + private static List strings(JsonNode array) { + List values = new ArrayList<>(); + array.forEach(node -> values.add(node.asString())); + return values; + } + + private static String nameOf(String event) { + for (String line : event.split("\n")) { + if (line.startsWith("event:")) { + return line.substring("event:".length()); + } + } + return ""; + } + + private static List names(List events) { + return events.stream().map(DashboardServiceTest::nameOf).toList(); + } + + private void advance(Duration duration) { + clock.advance(duration); + } + + @Test + void startsDownWithNothingKnownAndNoServer() { + create(); + + DashboardState result = dashboard.state(); + + assertEquals(null, result.activeServer()); + assertEquals(List.of(), result.knownServers()); + assertEquals(LinkState.DOWN, result.link()); + assertEquals(null, result.running()); + assertEquals(null, result.health()); + assertEquals(null, result.versions().server()); + assertEquals(CLIENT_VERSION, result.versions().client()); + verify(serverApi, never()).health(anyString()); + } + + @Test + void aFirstSubscriberGetsOneFullSnapshotThatReflectsEverythingTheModelHolds() throws Exception { + state.setActiveServer(A); + create(); + + RecordingPublisher browser = subscribe(); + + String snapshot = browser.next(); + assertEquals("snapshot", nameOf(snapshot)); + JsonNode data = RecordingPublisher.data(snapshot); + assertEquals(A, data.path("activeServer").asString()); + assertEquals(List.of(A), strings(data.path("knownServers"))); + assertEquals("DEGRADED", data.path("link").asString()); + assertTrue(data.path("running").isBoolean() && !data.path("running").asBoolean()); + assertEquals("PT6H", data.path("health").path("backupInterval").asString()); + assertEquals(5, data.path("health").path("backupRetentionCount").asInt()); + assertTrue(data.path("versions").path("server").isObject()); + assertEquals("0.2.0", data.path("versions").path("server").path("latestVersion").asString()); + assertTrue(drain(browser).isEmpty()); + } + + @Test + void aLateSubscriberGetsTheLatestSnapshotFollowedByGranularEvents() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + dashboard.runEvent(A, "run-started", "{\"running\":true,\"startedAt\":\"t\"}", true); + + RecordingPublisher browser = subscribe(); + dashboard.runEvent(A, "run-finished", "{\"running\":false,\"status\":\"COMPLETED\"}", false); + + List events = drain(browser); + assertEquals(List.of("snapshot", "run-finished"), names(events)); + JsonNode snapshot = RecordingPublisher.data(events.get(0)); + assertEquals("LIVE", snapshot.path("link").asString()); + assertTrue(snapshot.path("running").asBoolean()); + assertEquals("event:run-finished\ndata:{\"running\":false,\"status\":\"COMPLETED\"}\n\n", events.get(1)); + } + + @Test + void theLinkIsLiveWhileTheStreamIsUpDegradedWhenOnlyHealthAnswersAndDownOtherwise() throws Exception { + state.setActiveServer(A); + doThrow(new ResourceAccessException("refused")).when(serverApi).health(A); + create(); + assertEquals(LinkState.DOWN, dashboard.state().link()); + + doReturn(IDLE).when(serverApi).health(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + assertEquals(LinkState.DEGRADED, dashboard.state().link()); + + dashboard.streamUp(A); + assertEquals(LinkState.LIVE, dashboard.state().link()); + + dashboard.streamDown(A); + assertEquals(LinkState.DEGRADED, dashboard.state().link()); + + doThrow(new ResourceAccessException("refused")).when(serverApi).health(A); + dashboard.runEvent(A, "state", "{\"running\":true}", true); + dashboard.streamUp(A); + dashboard.streamDown(A); + DashboardState down = dashboard.state(); + assertEquals(LinkState.DOWN, down.link()); + assertEquals(null, down.running()); + } + + @Test + void linkChangesArePushedOnlyWhenTheStateChanges() throws Exception { + state.setActiveServer(A); + create(); + RecordingPublisher browser = subscribe(); + browser.next(); + + dashboard.streamUp(A); + dashboard.streamUp(A); + dashboard.streamDown(A); + + List links = drain(browser).stream().filter(event -> nameOf(event).equals("link")).toList(); + assertEquals(3, links.size()); + assertEquals("LIVE", RecordingPublisher.data(links.get(0)).path("state").asString()); + assertEquals(A, RecordingPublisher.data(links.get(0)).path("server").asString()); + assertEquals("CONNECTING", RecordingPublisher.data(links.get(1)).path("state").asString()); + assertEquals("DEGRADED", RecordingPublisher.data(links.get(2)).path("state").asString()); + } + + @Test + void pollsHealthEverySevenToEightSecondsWhileNotLiveAndFeedsTheState() throws Exception { + state.setActiveServer(A); + create(); + RecordingPublisher browser = subscribe(); + browser.next(); + clearInvocations(serverApi); + + advance(Duration.ofSeconds(3)); + dashboard.tick(); + verify(serverApi, never()).health(anyString()); + + doReturn(BUSY).when(serverApi).health(A); + advance(Duration.ofSeconds(5)); + dashboard.tick(); + verify(serverApi, times(1)).health(A); + assertEquals(true, dashboard.state().running()); + assertEquals(List.of("state"), names(drain(browser))); + + doReturn(IDLE).when(serverApi).health(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + List events = drain(browser); + assertEquals(List.of("state"), names(events)); + assertFalse(RecordingPublisher.data(events.get(0)).path("running").asBoolean(true)); + assertEquals(false, dashboard.state().running()); + + advance(Duration.ofSeconds(8)); + dashboard.tick(); + assertTrue(drain(browser).isEmpty()); + } + + @Test + void aFailedPollMakesTheLinkDownAndASuccessfulOneRecoversIt() throws Exception { + state.setActiveServer(A); + create(); + RecordingPublisher browser = subscribe(); + browser.next(); + + doThrow(new ResourceAccessException("refused")).when(serverApi).health(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + assertEquals(LinkState.DOWN, dashboard.state().link()); + assertEquals(null, dashboard.state().running()); + + doReturn(BUSY).when(serverApi).health(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + + assertEquals(LinkState.DEGRADED, dashboard.state().link()); + assertEquals(true, dashboard.state().running()); + assertEquals(List.of("link", "link", "state"), names(drain(browser))); + } + + @Test + void doesNotPollEverySevenSecondsOnceTheLinkIsLiveButKeepsAOneMinuteCatchAll() { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + clearInvocations(serverApi); + + advance(Duration.ofSeconds(30)); + dashboard.tick(); + advance(Duration.ofSeconds(20)); + dashboard.tick(); + verify(serverApi, never()).health(anyString()); + + advance(Duration.ofSeconds(15)); + dashboard.tick(); + verify(serverApi, times(1)).health(A); + } + + @Test + void aLiveLinkIgnoresPollResultsForLinkAndRunningButKeepsTheHealthSummary() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + dashboard.runEvent(A, "state", "{\"running\":false}", false); + RecordingPublisher browser = subscribe(); + browser.next(); + + doReturn(new ServerStatusDto(true, true, 9, Duration.ofHours(1))).when(serverApi).health(A); + advance(Duration.ofSeconds(61)); + dashboard.tick(); + + DashboardState result = dashboard.state(); + assertEquals(LinkState.LIVE, result.link()); + assertEquals(false, result.running()); + assertEquals(9, result.health().backupRetentionCount()); + assertEquals(List.of("config"), names(drain(browser))); + } + + @Test + void streamEventsAreForwardedAndKeepRunningInStep() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + RecordingPublisher browser = subscribe(); + browser.next(); + + dashboard.runEvent(A, "state", "{\"running\":false,\"at\":\"t\"}", false); + dashboard.runEvent(A, "run-started", "{\"running\":true,\"startedAt\":\"t\"}", true); + assertEquals(true, dashboard.state().running()); + dashboard.backupsChanged(A, "{\"at\":\"t2\"}"); + dashboard.runEvent(A, "run-finished", "{\"running\":false,\"status\":\"FAILED\"}", false); + assertEquals(false, dashboard.state().running()); + + List events = drain(browser); + assertEquals(List.of("state", "run-started", "backups-changed", "run-finished"), names(events)); + assertEquals("event:backups-changed\ndata:{\"at\":\"t2\"}\n\n", events.get(2)); + } + + @Test + void aConfigChangedEventRefetchesHealthOnceAndPushesTheSummaryOnlyWhenItChanged() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + RecordingPublisher browser = subscribe(); + browser.next(); + clearInvocations(serverApi); + + dashboard.configChanged(A); + assertTrue(drain(browser).isEmpty()); + verify(serverApi, times(1)).health(A); + + doReturn(new ServerStatusDto(true, false, 7, Duration.ofHours(2))).when(serverApi).health(A); + dashboard.configChanged(A); + + List events = drain(browser); + assertEquals(List.of("config"), names(events)); + assertEquals("event:config\ndata:{\"backupInterval\":\"PT2H\",\"backupRetentionCount\":7}\n\n", events.get(0)); + verify(serverApi, times(2)).health(A); + } + + @Test + void eventsFromAServerThatIsNoLongerActiveAreIgnored() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + state.setActiveServer(B); + dashboard.sync(); + RecordingPublisher browser = subscribe(); + browser.next(); + clearInvocations(serverApi); + + dashboard.streamUp(A); + dashboard.runEvent(A, "run-started", "{\"running\":true}", true); + dashboard.backupsChanged(A, "{}"); + dashboard.configChanged(A); + dashboard.streamDown(A); + + assertTrue(drain(browser).isEmpty()); + assertEquals(false, dashboard.state().running()); + verify(serverApi, never()).health(anyString()); + } + + @Test + void switchingServersPushesASnapshotThatClearsEverythingAboutTheOldOne() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + dashboard.runEvent(A, "state", "{\"running\":true}", true); + RecordingPublisher browser = subscribe(); + browser.next(); + doThrow(new ResourceAccessException("refused")).when(serverApi).health(B); + + state.setActiveServer(B); + dashboard.sync(); + + List events = drain(browser); + assertEquals(List.of("snapshot", "link", "versions"), names(events)); + String snapshot = events.get(0); + JsonNode data = RecordingPublisher.data(snapshot); + assertEquals(B, data.path("activeServer").asString()); + assertEquals(List.of(A, B), strings(data.path("knownServers"))); + assertEquals("CONNECTING", data.path("link").asString()); + assertTrue(data.path("running").isNull()); + assertTrue(data.path("health").isNull()); + assertTrue(data.path("versions").path("server").path("currentVersion").isNull()); + assertEquals("NOT_CHECKED", data.path("versions").path("server").path("checkState").asString()); + } + + @Test + void aHealthAnswerThatArrivesAfterASwitchIsDiscarded() { + state.setActiveServer(A); + when(serverApi.health(A)).thenAnswer(call -> { + state.setActiveServer(B); + dashboard.sync(); + return BUSY; + }); + doThrow(new ResourceAccessException("refused")).when(serverApi).health(B); + + create(); + + DashboardState result = dashboard.state(); + assertEquals(B, result.activeServer()); + assertEquals(LinkState.DOWN, result.link()); + assertEquals(null, result.running()); + assertEquals(null, result.health()); + verify(serverApi, times(1)).health(A); + verify(serverApi, times(1)).health(B); + } + + @Test + void clearingTheActiveServerGoesDownWithoutPolling() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + RecordingPublisher browser = subscribe(); + browser.next(); + clearInvocations(serverApi); + + state.setActiveServer(""); + dashboard.sync(); + advance(Duration.ofSeconds(30)); + dashboard.tick(); + + List events = drain(browser); + assertEquals(List.of("snapshot"), names(events)); + assertTrue(RecordingPublisher.data(events.get(0)).path("activeServer").isNull()); + assertEquals("DOWN", RecordingPublisher.data(events.get(0)).path("link").asString()); + verify(serverApi, never()).health(anyString()); + } + + @Test + void knownServerChangesArePushedOnceAndWithoutASnapshotWhenTheActiveServerStaysTheSame() throws Exception { + state.setActiveServer(A); + create(); + RecordingPublisher browser = subscribe(); + browser.next(); + + state.updateKnownServers(List.of(A, B)); + + List events = drain(browser); + assertEquals(List.of("servers"), names(events)); + assertEquals("event:servers\ndata:{\"knownServers\":[\"" + A + "\",\"" + B + "\"],\"activeServer\":\"" + A + "\"}\n\n", events.get(0)); + } + + @Test + void aDiscoveryThatPicksTheFirstActiveServerPushesOneSnapshot() throws Exception { + when(serverApi.health(anyString())).thenThrow(new ResourceAccessException("refused")); + create(); + RecordingPublisher browser = subscribe(); + browser.next(); + + state.updateKnownServers(List.of(A, B)); + + assertEquals(List.of("snapshot", "link", "versions"), names(drain(browser))); + assertEquals(A, dashboard.state().activeServer()); + } + + @Test + void theServerVersionIsFetchedOnLinkUpAndAServerSwitchNotOnEveryRead() throws Exception { + state.setActiveServer(A); + create(); + verify(serverApi, times(1)).serverVersion(A); + + dashboard.state(); + dashboard.subscribe(publisher::subscribe); + dashboard.state(); + verify(serverApi, times(1)).serverVersion(A); + + dashboard.streamUp(A); + verify(serverApi, times(1)).serverVersion(A); + + advance(Duration.ofMinutes(6)); + dashboard.streamDown(A); + verify(serverApi, times(2)).serverVersion(A); + + doThrow(new ResourceAccessException("refused")).when(serverApi).health(B); + state.setActiveServer(B); + dashboard.sync(); + verify(serverApi, never()).serverVersion(B); + doReturn(IDLE).when(serverApi).health(B); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + verify(serverApi, times(1)).serverVersion(B); + } + + @Test + void theServerVersionIsRefetchedAtMostHourlyAndPushedWhenItChanges() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + RecordingPublisher browser = subscribe(); + browser.next(); + clearInvocations(serverApi); + + advance(Duration.ofMinutes(59)); + dashboard.tick(); + verify(serverApi, never()).serverVersion(anyString()); + + doReturn(new VersionStatusDto("0.2.0", "0.2.0", null, false, CheckState.OK, START, null)).when(serverApi).serverVersion(A); + advance(Duration.ofMinutes(2)); + dashboard.tick(); + + verify(serverApi, times(1)).serverVersion(A); + List events = drain(browser).stream().filter(event -> nameOf(event).equals("versions")).toList(); + assertEquals(1, events.size()); + assertEquals("0.2.0", RecordingPublisher.data(events.get(0)).path("server").path("currentVersion").asString()); + } + + @Test + @SuppressWarnings("unchecked") + void theClientsOwnUpdateCheckIsPushedAsAVersionsEvent() throws Exception { + state.setActiveServer(A); + create(); + ArgumentCaptor> listener = ArgumentCaptor.forClass(Consumer.class); + verify(updateCheck).addStatusListener(listener.capture()); + RecordingPublisher browser = subscribe(); + browser.next(); + VersionStatusDto updated = new VersionStatusDto("0.1.0", "0.3.0", "https://example.test/c", true, CheckState.OK, START, null); + when(updateCheck.status()).thenReturn(updated); + + listener.getValue().accept(updated); + + List events = drain(browser); + assertEquals(List.of("versions"), names(events)); + JsonNode versions = RecordingPublisher.data(events.get(0)); + assertEquals("0.3.0", versions.path("client").path("latestVersion").asString()); + assertTrue(versions.path("client").path("updateAvailable").asBoolean()); + assertTrue(versions.path("server").isObject()); + } + + @Test + void retriesAnUnavailableServerVersionAfterTenMinutes() { + state.setActiveServer(A); + doThrow(new ResourceAccessException("refused")).when(serverApi).serverVersion(A); + create(); + dashboard.streamUp(A); + clearInvocations(serverApi); + + advance(Duration.ofMinutes(9)); + dashboard.tick(); + verify(serverApi, never()).serverVersion(anyString()); + + advance(Duration.ofMinutes(1)); + dashboard.tick(); + verify(serverApi, times(1)).serverVersion(A); + } + + @Test + void healthRequestsThatPileUpWhileOneIsRunningAreCoalesced() { + state.setActiveServer(A); + create(queued::add); + assertEquals(1, queued.size()); + + dashboard.streamUp(A); + dashboard.configChanged(A); + dashboard.configChanged(A); + + assertEquals(2, queued.size()); + queued.forEach(Runnable::run); + verify(serverApi, times(2)).health(A); + assertFalse(queued.isEmpty()); + } + + @Test + void aServerIsConnectingUntilItsFirstAnswerAndOnlyThenDownWithAnUnavailableVersion() throws Exception { + state.setActiveServer(A); + doThrow(new ResourceAccessException("refused")).when(serverApi).health(A); + create(queued::add); + RecordingPublisher browser = subscribe(); + browser.next(); + + DashboardState before = dashboard.state(); + assertEquals(LinkState.CONNECTING, before.link()); + assertEquals(CheckState.NOT_CHECKED, before.versions().server().checkState()); + + queued.poll().run(); + + DashboardState after = dashboard.state(); + assertEquals(LinkState.DOWN, after.link()); + assertEquals(CheckState.UNAVAILABLE, after.versions().server().checkState()); + assertEquals(List.of("link", "versions"), names(drain(browser))); + } + + @Test + void aStreamDropGoesBackToConnectingNotStraightToDown() { + state.setActiveServer(A); + create(queued::add); + queued.poll().run(); + dashboard.streamUp(A); + + dashboard.streamDown(A); + + assertEquals(LinkState.CONNECTING, dashboard.state().link()); + assertEquals(null, dashboard.state().running()); + } + + @Test + void aServerVersionThatWasNotCheckedYetIsFetchedAgainWithinHalfAMinute() throws Exception { + state.setActiveServer(A); + VersionStatusDto notChecked = new VersionStatusDto("0.1.0", null, null, false, CheckState.NOT_CHECKED, null, null); + doReturn(notChecked).doReturn(notChecked).doReturn(SERVER_VERSION).when(serverApi).serverVersion(A); + create(); + dashboard.streamUp(A); + RecordingPublisher browser = subscribe(); + browser.next(); + clearInvocations(serverApi); + + advance(Duration.ofSeconds(20)); + dashboard.tick(); + verify(serverApi, never()).serverVersion(anyString()); + + advance(Duration.ofSeconds(12)); + dashboard.tick(); + + verify(serverApi, times(1)).serverVersion(A); + assertEquals(CheckState.OK, dashboard.state().versions().server().checkState()); + List events = drain(browser).stream().filter(event -> nameOf(event).equals("versions")).toList(); + assertEquals(1, events.size()); + assertEquals("OK", RecordingPublisher.data(events.get(0)).path("server").path("checkState").asString()); + } + + @Test + void aFlappingLinkDoesNotRefetchTheServerVersionWithinFiveMinutes() { + state.setActiveServer(A); + create(); + clearInvocations(serverApi); + + dashboard.streamUp(A); + dashboard.streamDown(A); + dashboard.streamUp(A); + + verify(serverApi, never()).serverVersion(anyString()); + } + + @Test + void whileDegradedTheClientChecksTheArchiveListOncePerMinuteAndPushesBackupsChanged() throws Exception { + state.setActiveServer(A); + List one = List.of(new BackupDto("a", "a.zip", 1L, START)); + List two = List.of(new BackupDto("a", "a.zip", 1L, START), new BackupDto("b", "b.zip", 2L, START)); + doReturn(one).when(serverApi).listBackups(A); + create(); + RecordingPublisher browser = subscribe(); + browser.next(); + + advance(Duration.ofSeconds(8)); + dashboard.tick(); + verify(serverApi, times(1)).listBackups(A); + assertTrue(names(drain(browser)).stream().noneMatch("backups-changed"::equals)); + + advance(Duration.ofSeconds(30)); + dashboard.tick(); + verify(serverApi, times(1)).listBackups(A); + + doReturn(two).when(serverApi).listBackups(A); + advance(Duration.ofSeconds(31)); + dashboard.tick(); + verify(serverApi, times(2)).listBackups(A); + List events = drain(browser).stream().filter(event -> nameOf(event).equals("backups-changed")).toList(); + assertEquals(1, events.size()); + assertEquals("2026-11-12T10:01:09Z", RecordingPublisher.data(events.get(0)).path("at").asString()); + + advance(Duration.ofSeconds(61)); + dashboard.tick(); + assertTrue(drain(browser).stream().noneMatch(event -> nameOf(event).equals("backups-changed"))); + } + + @Test + void aLiveLinkNeverChecksTheArchiveListItself() { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + clearInvocations(serverApi); + + advance(Duration.ofMinutes(5)); + dashboard.tick(); + + verify(serverApi, never()).listBackups(anyString()); + } + + @Test + void aRunThatFinishesWhileDegradedRebaselinesTheArchiveListInsteadOfAnnouncingIt() throws Exception { + state.setActiveServer(A); + List one = List.of(new BackupDto("a", "a.zip", 1L, START)); + List two = List.of(new BackupDto("a", "a.zip", 1L, START), new BackupDto("b", "b.zip", 2L, START)); + doReturn(one).when(serverApi).listBackups(A); + doReturn(BUSY).when(serverApi).health(A); + create(); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + RecordingPublisher browser = subscribe(); + browser.next(); + + doReturn(IDLE).when(serverApi).health(A); + doReturn(two).when(serverApi).listBackups(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + advance(Duration.ofSeconds(61)); + dashboard.tick(); + advance(Duration.ofSeconds(61)); + dashboard.tick(); + + List names = names(drain(browser)); + assertTrue(names.contains("state")); + assertFalse(names.contains("backups-changed")); + } + + @Test + void aServerThatCameBackAfterBeingDownIsAskedForItsVersionAgainAtOnce() { + state.setActiveServer(A); + create(); + verify(serverApi, times(1)).serverVersion(A); + + doThrow(new ResourceAccessException("refused")).when(serverApi).health(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + assertEquals(LinkState.DOWN, dashboard.state().link()); + clearInvocations(serverApi); + + doReturn(IDLE).when(serverApi).health(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + + assertEquals(LinkState.DEGRADED, dashboard.state().link()); + verify(serverApi, times(1)).serverVersion(A); + } + + @Test + void aFailingArchiveListingIsRetriedOnlyOncePerMinute() { + state.setActiveServer(A); + doThrow(new ResourceAccessException("timed out")).when(serverApi).listBackups(A); + create(); + + advance(Duration.ofSeconds(8)); + dashboard.tick(); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + verify(serverApi, times(1)).listBackups(A); + + advance(Duration.ofSeconds(60)); + dashboard.tick(); + verify(serverApi, times(2)).listBackups(A); + } + + @Test + void aServerWithoutAStoredTokenRequiresPairingAndShowsNoDetails() { + state.forgetPairing(A); + create(); + state.setActiveServer(A); + + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.REQUIRED, dashboard.state().pairing()); + assertEquals(null, dashboard.state().health()); + } + + @Test + void aRejectedTokenOnTheHealthCheckMarksPairingRejectedAndKeepsTheServerReachable() { + create(); + doThrow(new PairingRequiredException("rejected")).when(serverApi).health(A); + state.setActiveServer(A); + + DashboardState result = dashboard.state(); + + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.REJECTED, result.pairing()); + assertEquals(wellatleastitried.mediagarrdclient.dto.LinkState.DEGRADED, result.link()); + } + + @Test + void aDeferredPairingWhoseHealthCheckLaterGetsA401BecomesRejected() { + create(); + state.forgetPairing(A); + state.setActiveServer(A); + doThrow(new PairingRequiredException("rejected")).when(serverApi).health(A); + state.storePairing(A, new StoredPairing("deferred-token", "id-d", "Test")); + + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.REJECTED, dashboard.state().pairing()); + } + + @Test + void pairingAgainClearsTheRejection() { + create(); + doThrow(new PairingRequiredException("rejected")).when(serverApi).health(A); + state.setActiveServer(A); + doReturn(IDLE).when(serverApi).health(A); + + state.storePairing(A, new StoredPairing("new-token", "id-new", "Test")); + + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.PAIRED, dashboard.state().pairing()); + } + + @Test + void aHealthCheckThatClearsTheRejectionTellsListenersSoTheStreamCanRestart() { + create(); + doThrow(new PairingRequiredException("rejected")).when(serverApi).health(A); + state.setActiveServer(A); + List recovered = new ArrayList<>(); + dashboard.addRecoveryListener(recovered::add); + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.REJECTED, dashboard.state().pairing()); + + doReturn(IDLE).when(serverApi).health(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.PAIRED, dashboard.state().pairing()); + assertEquals(List.of(A), recovered); + } + + @Test + void aTokenRejectionSeenByAnyServerCallMarksThePairingRejectedAtOnce() { + create(); + state.setActiveServer(A); + org.mockito.ArgumentCaptor> listener = org.mockito.ArgumentCaptor.forClass(java.util.function.Consumer.class); + verify(serverApi).addTokenRejectedListener(listener.capture()); + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.PAIRED, dashboard.state().pairing()); + + listener.getValue().accept(A); + + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.REJECTED, dashboard.state().pairing()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/LoginAttemptsTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/LoginAttemptsTest.java new file mode 100644 index 0000000..1c718e6 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/LoginAttemptsTest.java @@ -0,0 +1,191 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Duration; +import java.time.Instant; + +import org.junit.jupiter.api.Test; + +class LoginAttemptsTest { + + private final MutableClock clock = new MutableClock(Instant.parse("2026-11-19T12:00:00Z")); + private final LoginAttempts attempts = new LoginAttempts(clock, 3); + + @Test + void allowsAFewFailuresThenLocksWithAGrowingDelay() { + for (int i = 0; i < LoginAttempts.FREE_FAILURES; i++) { + attempts.failed("10.0.0.1"); + assertTrue(attempts.lockedFor("10.0.0.1").isEmpty()); + } + + attempts.failed("10.0.0.1"); + assertEquals(Duration.ofSeconds(5), attempts.lockedFor("10.0.0.1").orElseThrow()); + + clock.advance(Duration.ofSeconds(5)); + assertTrue(attempts.lockedFor("10.0.0.1").isEmpty()); + attempts.failed("10.0.0.1"); + assertEquals(Duration.ofSeconds(10), attempts.lockedFor("10.0.0.1").orElseThrow()); + } + + @Test + void capsTheDelay() { + for (int i = 0; i < 40; i++) { + attempts.failed("10.0.0.1"); + clock.advance(LoginAttempts.MAX_LOCK); + } + + attempts.failed("10.0.0.1"); + + assertEquals(LoginAttempts.MAX_LOCK, attempts.lockedFor("10.0.0.1").orElseThrow()); + } + + @Test + void trackSourcesSeparatelyAndForgetAfterASuccess() { + for (int i = 0; i < 5; i++) { + attempts.failed("10.0.0.1"); + } + + assertTrue(attempts.lockedFor("10.0.0.1").isPresent()); + assertTrue(attempts.lockedFor("10.0.0.2").isEmpty()); + attempts.succeeded("10.0.0.1"); + assertTrue(attempts.lockedFor("10.0.0.1").isEmpty()); + } + + @Test + void forgetsOldFailures() { + for (int i = 0; i < 5; i++) { + attempts.failed("10.0.0.1"); + } + + clock.advance(LoginAttempts.FORGET_AFTER); + + assertTrue(attempts.lockedFor("10.0.0.1").isEmpty()); + attempts.failed("10.0.0.1"); + assertTrue(attempts.lockedFor("10.0.0.1").isEmpty()); + } + + @Test + void keepsAtMostTheConfiguredNumberOfSources() { + for (int i = 0; i < 4; i++) { + for (int n = 0; n < 5; n++) { + attempts.failed("10.0.0." + i); + } + } + + assertTrue(attempts.lockedFor("10.0.0.0").isEmpty()); + assertTrue(attempts.lockedFor("10.0.0.3").isPresent()); + } + + @Test + void refusesASecondAttemptFromASourceWhileOneIsInFlight() { + assertTrue(attempts.tryBegin("10.0.0.1").isEmpty()); + assertTrue(attempts.tryBegin("10.0.0.1").isPresent()); + assertTrue(attempts.tryBegin("10.0.0.2").isEmpty()); + + attempts.failed("10.0.0.1"); + + assertTrue(attempts.tryBegin("10.0.0.1").isEmpty()); + attempts.abandon("10.0.0.1"); + assertTrue(attempts.tryBegin("10.0.0.1").isEmpty()); + } + + @Test + void lockoutFromFailuresIsHonouredByTryBegin() { + for (int i = 0; i < LoginAttempts.FREE_FAILURES + 1; i++) { + attempts.tryBegin("10.0.0.1"); + attempts.failed("10.0.0.1"); + } + + assertEquals(Duration.ofSeconds(5), attempts.tryBegin("10.0.0.1").orElseThrow()); + } + + private void drainBucket() { + for (int i = 0; i < LoginAttempts.BUCKET_CAPACITY; i++) { + assertTrue(attempts.tryBegin("10.9.0." + i).isEmpty()); + } + } + + @Test + void anEmptyBucketRefusesEverySourceWithTheTimeToTheNextTokenInsteadOfLockingAnyone() { + drainBucket(); + + assertEquals(Duration.ofSeconds(2), attempts.tryBegin("10.8.0.1").orElseThrow()); + clock.advance(Duration.ofSeconds(1)); + assertEquals(Duration.ofSeconds(1), attempts.tryBegin("10.8.0.1").orElseThrow()); + clock.advance(Duration.ofSeconds(1)); + assertTrue(attempts.tryBegin("10.8.0.1").isEmpty()); + assertTrue(attempts.tryBegin("10.8.0.2").isPresent()); + } + + @Test + void aRefusedAttemptDoesNotLeaveASourceReserved() { + drainBucket(); + + assertTrue(attempts.tryBegin("10.8.0.1").isPresent()); + clock.advance(Duration.ofSeconds(2)); + + assertTrue(attempts.tryBegin("10.8.0.1").isEmpty()); + } + + @Test + void aSuccessfulLoginGivesItsTokenBackButNeverBeyondTheCapacity() { + assertTrue(attempts.tryBegin("10.7.0.1").isEmpty()); + attempts.succeeded("10.7.0.1"); + attempts.succeeded("10.7.0.1"); + attempts.succeeded("10.7.0.2"); + for (int i = 0; i < LoginAttempts.BUCKET_CAPACITY; i++) { + assertTrue(attempts.tryBegin("10.6.0." + i).isEmpty(), "attempt " + i); + } + + assertTrue(attempts.tryBegin("10.6.1.1").isPresent()); + } + + @Test + void anAbandonedAttemptGivesItsTokenBack() { + drainBucket(); + clock.advance(Duration.ofSeconds(2)); + assertTrue(attempts.tryBegin("10.5.0.1").isEmpty()); + assertTrue(attempts.tryBegin("10.5.0.2").isPresent()); + + attempts.abandon("10.5.0.1"); + + assertTrue(attempts.tryBegin("10.5.0.2").isEmpty()); + } + + @Test + void aFailureKeepsItsTokenSpent() { + assertTrue(attempts.tryBegin("10.4.0.1").isEmpty()); + attempts.failed("10.4.0.1"); + for (int i = 0; i < LoginAttempts.BUCKET_CAPACITY - 1; i++) { + assertTrue(attempts.tryBegin("10.3.0." + i).isEmpty(), "attempt " + i); + } + + assertTrue(attempts.tryBegin("10.3.1.1").isPresent()); + } + + @Test + void aRefusalWhileBusyDoesNotSpendAToken() { + assertTrue(attempts.tryBegin("10.2.0.1").isEmpty()); + for (int i = 0; i < 100; i++) { + assertEquals(LoginAttempts.BUSY_RETRY, attempts.tryBegin("10.2.0.1").orElseThrow()); + } + attempts.failed("10.2.0.1"); + for (int i = 0; i < LoginAttempts.BUCKET_CAPACITY - 1; i++) { + assertTrue(attempts.tryBegin("10.1.0." + i).isEmpty(), "attempt " + i); + } + + assertTrue(attempts.tryBegin("10.1.1.1").isPresent()); + } + + @Test + void aSucceededCallWithoutAReservationDoesNotRefund() { + drainBucket(); + + attempts.succeeded("10.0.9.9"); + attempts.abandon("10.0.9.9"); + + assertTrue(attempts.tryBegin("10.8.0.1").isPresent()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/MutableClock.java b/src/test/java/wellatleastitried/mediagarrdclient/service/MutableClock.java new file mode 100644 index 0000000..83ac6e4 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/MutableClock.java @@ -0,0 +1,43 @@ +package wellatleastitried.mediagarrdclient.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 volatile Instant now; + + MutableClock() { + this(Instant.parse("2026-10-26T00:00:00Z")); + } + + MutableClock(Instant start) { + this.now = start; + } + + void set(Instant instant) { + now = instant; + } + + void advance(Duration duration) { + now = now.plus(duration); + } + + @Override + public Instant instant() { + return now; + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/PasswordServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/PasswordServiceTest.java new file mode 100644 index 0000000..bcb0e5e --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/PasswordServiceTest.java @@ -0,0 +1,152 @@ +package wellatleastitried.mediagarrdclient.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 java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; + +class PasswordServiceTest { + + private static final JsonMapper MAPPER = JsonMapper.builder().build(); + private static final int FAST = 1000; + + @TempDir + Path tempDir; + + private final MediaGarrdProperties configuration = new MediaGarrdProperties(); + + @BeforeEach + void setUp() { + configuration.setStateFile(tempDir.resolve("state.json").toString()); + } + + private PasswordService service() { + return new PasswordService(configuration, MAPPER, FAST); + } + + @Test + void startsWithoutAPasswordAndLetsTheFirstCallerSetOne() { + PasswordService passwords = service(); + assertFalse(passwords.isConfigured()); + assertFalse(passwords.matches("anything")); + + passwords.setInitial("correct horse"); + + assertTrue(passwords.isConfigured()); + assertTrue(passwords.matches("correct horse")); + assertFalse(passwords.matches("correct horsf")); + assertFalse(passwords.matches(null)); + assertTrue(service().matches("correct horse")); + } + + @Test + void refusesASecondInitialPassword() { + PasswordService passwords = service(); + passwords.setInitial("correct horse"); + + assertThrows(ConflictException.class, () -> passwords.setInitial("another one")); + + assertTrue(passwords.matches("correct horse")); + } + + @Test + void rejectsPasswordsThatAreTooShortOrTooLong() { + PasswordService passwords = service(); + + assertThrows(InvalidRequestException.class, () -> passwords.setInitial("short")); + assertThrows(InvalidRequestException.class, () -> passwords.setInitial(null)); + assertThrows(InvalidRequestException.class, () -> passwords.setInitial("x".repeat(PasswordService.MAX_LENGTH + 1))); + assertFalse(passwords.isConfigured()); + assertFalse(Files.exists(tempDir.resolve("password.json"))); + } + + @Test + void theStoredFileHoldsOnlyAHashWithItsParameters() throws IOException { + PasswordService first = service(); + first.setInitial("correct horse"); + Path file = tempDir.resolve("password.json"); + String content = Files.readString(file); + JsonNode json = MAPPER.readTree(content); + + assertFalse(content.contains("correct horse")); + assertEquals(FAST, json.get("iterations").asInt()); + assertEquals(16, java.util.Base64.getDecoder().decode(json.get("salt").asString()).length); + assertEquals(32, java.util.Base64.getDecoder().decode(json.get("hash").asString()).length); + if (Files.getFileStore(file).supportsFileAttributeView("posix")) { + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(file))); + } + } + + @Test + void twoInstallsWithTheSamePasswordGetDifferentSalts() throws IOException { + service().setInitial("correct horse"); + String first = Files.readString(tempDir.resolve("password.json")); + Files.delete(tempDir.resolve("password.json")); + service().setInitial("correct horse"); + + assertFalse(first.equals(Files.readString(tempDir.resolve("password.json")))); + } + + @Test + void anEnvironmentPasswordOverridesAndDisablesSetting() { + configuration.setPassword("from the environment"); + PasswordService passwords = service(); + + assertTrue(passwords.isConfigured()); + assertTrue(passwords.isFromEnvironment()); + assertTrue(passwords.matches("from the environment")); + assertFalse(passwords.matches("something else")); + assertThrows(ConflictException.class, () -> passwords.setInitial("a new password")); + } + + @Test + void anEnvironmentPasswordWinsOverAStoredOne() { + service().setInitial("stored password"); + configuration.setPassword("from the environment"); + PasswordService passwords = service(); + + assertTrue(passwords.matches("from the environment")); + assertFalse(passwords.matches("stored password")); + } + + @Test + void resetRemovesTheStoredPasswordSoAnotherCanBeSet() { + service().setInitial("old password"); + configuration.setResetPassword(true); + + PasswordService passwords = service(); + + assertFalse(passwords.isConfigured()); + assertFalse(Files.exists(tempDir.resolve("password.json"))); + passwords.setInitial("new password"); + assertTrue(passwords.matches("new password")); + } + + @Test + void refusesToStartOnACorruptPasswordFileInsteadOfOpeningTheFirstVisitWindow() throws IOException { + Files.writeString(tempDir.resolve("password.json"), "{not json"); + + IllegalStateException e = assertThrows(IllegalStateException.class, this::service); + + assertTrue(e.getMessage().contains("CLIENT_RESET_PASSWORD")); + } + + @Test + void usesTheDocumentedIterationCountByDefault() { + assertEquals(600_000, PasswordService.ITERATIONS); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/PickupScheduleTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/PickupScheduleTest.java new file mode 100644 index 0000000..1b6ec02 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/PickupScheduleTest.java @@ -0,0 +1,68 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Duration; +import java.time.Instant; + +import org.junit.jupiter.api.Test; + +class PickupScheduleTest { + + private static final Duration INTERVAL = Duration.ofHours(12); + + private final MutableClock clock = new MutableClock(); + private final PickupSchedule schedule = new PickupSchedule(clock); + + @Test + void aClientThatNeverPickedUpIsDueNow() { + assertTrue(schedule.due(null, INTERVAL)); + } + + @Test + void aPickupIsDueOneIntervalAfterTheLastOne() { + Instant last = clock.instant().minus(Duration.ofHours(5)); + + assertFalse(schedule.due(last, INTERVAL)); + assertEquals(last.plus(INTERVAL), schedule.dueAt(last, INTERVAL)); + clock.advance(Duration.ofHours(7)); + assertTrue(schedule.due(last, INTERVAL)); + } + + @Test + void aLastPickupInTheFutureDoesNotStallTheSchedule() { + assertTrue(schedule.due(clock.instant().plus(Duration.ofDays(30)), INTERVAL)); + } + + @Test + void failuresBackOffAndCapThenResetOnSuccess() { + Duration[] expected = {Duration.ofMinutes(1), Duration.ofMinutes(2), Duration.ofMinutes(5), Duration.ofMinutes(10), Duration.ofMinutes(15), Duration.ofMinutes(15)}; + for (Duration wait : expected) { + Instant retry = schedule.failed(); + assertEquals(clock.instant().plus(wait), retry); + assertFalse(schedule.due(null, INTERVAL)); + clock.advance(wait); + assertTrue(schedule.due(null, INTERVAL)); + } + + schedule.reset(); + assertTrue(schedule.due(null, INTERVAL)); + assertEquals(clock.instant().plus(Duration.ofMinutes(1)), schedule.failed()); + } + + @Test + void aClockThatJumpsBackwardDoesNotStallTheRetry() { + schedule.failed(); + schedule.failed(); + schedule.failed(); + schedule.failed(); + schedule.failed(); + clock.advance(Duration.ofHours(-5)); + + assertFalse(schedule.due(null, INTERVAL)); + clock.advance(Duration.ofMinutes(15)); + assertTrue(schedule.due(null, INTERVAL)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicyTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicyTest.java new file mode 100644 index 0000000..52b2a29 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicyTest.java @@ -0,0 +1,58 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.Duration; + +import org.junit.jupiter.api.Test; + +import wellatleastitried.mediagarrdclient.service.ReconnectPolicy.Outcome; + +class ReconnectPolicyTest { + + private static final long LONG = Duration.ofSeconds(60).toNanos(); + private static final long SHORT = Duration.ofSeconds(1).toNanos(); + + private final ReconnectPolicy policy = new ReconnectPolicy(Duration.ofSeconds(1), Duration.ofSeconds(8), Duration.ofMinutes(5), Duration.ofSeconds(5)); + + @Test + void failuresBackOffExponentiallyUpToTheMaximum() { + assertEquals(Duration.ofSeconds(1), policy.next(Outcome.FAILED, false, SHORT).delay()); + assertEquals(Duration.ofSeconds(2), policy.next(Outcome.FAILED, false, SHORT).delay()); + assertEquals(Duration.ofSeconds(4), policy.next(Outcome.FAILED, false, SHORT).delay()); + assertEquals(Duration.ofSeconds(8), policy.next(Outcome.FAILED, false, SHORT).delay()); + assertEquals(Duration.ofSeconds(8), policy.next(Outcome.FAILED, false, SHORT).delay()); + } + + @Test + void aLongStreamThatDeliveredEventsResetsTheBackoff() { + policy.next(Outcome.FAILED, false, SHORT); + policy.next(Outcome.FAILED, false, SHORT); + + assertEquals(Duration.ofSeconds(1), policy.next(Outcome.FAILED, true, LONG).delay()); + } + + @Test + void aShortStreamThatDeliveredEventsDoesNotResetTheBackoff() { + policy.next(Outcome.FAILED, false, SHORT); + + assertEquals(Duration.ofSeconds(2), policy.next(Outcome.FAILED, true, SHORT).delay()); + } + + @Test + void aRolloverReconnectsAtOnceUnlessItWasShortLived() { + assertEquals(Outcome.ROLLOVER, policy.next(Outcome.ROLLOVER, true, LONG).outcome()); + assertEquals(Outcome.FAILED, policy.next(Outcome.ROLLOVER, true, SHORT).outcome()); + } + + @Test + void anUnsupportedServerIsRetriedAfterTheLongDelayWithoutGrowingTheBackoff() { + assertEquals(Duration.ofMinutes(5), policy.next(Outcome.UNSUPPORTED, false, SHORT).delay()); + assertEquals(Duration.ofSeconds(1), policy.next(Outcome.FAILED, false, SHORT).delay()); + } + + @Test + void aRejectionIsPassedThrough() { + assertEquals(Outcome.REJECTED, policy.next(Outcome.REJECTED, false, SHORT).outcome()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/RecordingPublisher.java b/src/test/java/wellatleastitried/mediagarrdclient/service/RecordingPublisher.java new file mode 100644 index 0000000..9959501 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/RecordingPublisher.java @@ -0,0 +1,68 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.util.List; +import java.util.Optional; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +class RecordingPublisher implements ClientEventPublisher { + + final BlockingQueue sent = new LinkedBlockingQueue<>(); + private volatile boolean subscribed; + + @Override + public void publish(String name, String data) { + if (subscribed) { + sent.add(frame(name, data)); + } + } + + Optional subscribe(List initial) { + subscribed = true; + initial.forEach(event -> sent.add(frame(event.name(), event.data()))); + return Optional.of(this); + } + + String next() throws InterruptedException { + String event = sent.poll(5, TimeUnit.SECONDS); + assertNotNull(event, "timed out waiting for an event"); + return event; + } + + String nextContaining(String marker) throws InterruptedException { + while (true) { + String event = next(); + if (event.contains(marker)) { + return event; + } + } + } + + static String eventName(String frame) { + for (String line : frame.split("\n")) { + if (line.startsWith("event:")) { + return line.substring("event:".length()); + } + } + return ""; + } + + static JsonNode data(String frame) { + for (String line : frame.split("\n")) { + if (line.startsWith("data:")) { + return JsonMapper.builder().build().readTree(line.substring("data:".length())); + } + } + throw new AssertionError("no data line in " + frame); + } + + private static String frame(String name, String data) { + return "event:" + name + "\ndata:" + data + "\n\n"; + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ScheduledPickupTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ScheduledPickupTest.java new file mode 100644 index 0000000..dc5bc8c --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ScheduledPickupTest.java @@ -0,0 +1,599 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +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.client.ResourceAccessException; + +import tools.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; + +class ScheduledPickupTest { + + private static final String SERVER = "http://server:8080"; + private static final Duration INTERVAL = Duration.ofHours(12); + private static final BackupDto LATEST = new BackupDto("b2", "b2-media-backup.zip", 4, Instant.EPOCH); + private static final BackupDto OLDER = new BackupDto("b1", "b1-media-backup.zip", 4, Instant.EPOCH); + + @TempDir + Path tempDir; + + private final ServerApiService api = mock(ServerApiService.class); + private final MutableClock clock = new MutableClock(); + private final List services = new ArrayList<>(); + private MediaGarrdProperties configuration; + private ClientStateService state; + private Path downloads; + + @BeforeEach + void setUp() throws IOException { + downloads = tempDir.resolve("downloads"); + Files.createDirectories(downloads); + configuration = new MediaGarrdProperties(); + configuration.setDownloadDirectory(downloads.toString()); + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(INTERVAL); + state = new ClientStateService(configuration, new JsonMapper()); + when(api.listBackups(SERVER)).thenReturn(List.of(LATEST, OLDER)); + when(api.downloadById(eq(SERVER), anyString(), any(), any())).thenAnswer(invocation -> { + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + } + + @AfterEach + void tearDown() { + services.forEach(BackupPickupService::shutdown); + } + + @Test + void aRestartedClientThatIsOverdueDownloadsOnTheFirstTick() throws Exception { + pairedState().recordPickup(SERVER, clock.instant().minus(INTERVAL).minusSeconds(1)); + + BackupPickupService restarted = restart(); + tick(restarted); + + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + assertEquals(clock.instant(), pairedState().getLastPickupAt()); + } + + @Test + void aRestartedClientThatIsNotDueWaitsForTheOriginalDueTime() throws Exception { + Instant last = clock.instant().minus(Duration.ofHours(5)); + pairedState().recordPickup(SERVER, last); + + BackupPickupService restarted = restart(); + tick(restarted); + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + + clock.advance(Duration.ofHours(7).minusSeconds(1)); + tick(restarted); + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + + clock.advance(Duration.ofSeconds(1)); + tick(restarted); + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + assertEquals(clock.instant(), pairedState().getLastPickupAt()); + } + + @Test + void aClientThatNeverPickedUpDownloadsAtOnce() throws Exception { + pairedState(); + + tick(start()); + + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + assertEquals(clock.instant(), pairedState().getLastPickupAt()); + } + + @Test + void anAlreadyDownloadedLatestArchiveCountsAsAPickup() throws Exception { + pairedState(); + Files.write(downloads.resolve("b2-media-backup.zip"), new byte[4]); + + tick(start()); + + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + assertEquals(clock.instant(), pairedState().getLastPickupAt()); + } + + @Test + void anUnpairedClientStaysQuietAndPicksUpOnceItIsPaired() throws Exception { + state.setActiveServer(SERVER); + BackupPickupService pickup = start(); + + tick(pickup); + clock.advance(Duration.ofHours(1)); + tick(pickup); + + verify(api, never()).listBackups(anyString()); + assertNull(state.getLastPickupAt()); + + state.storePairing(SERVER, new StoredPairing("token", "id", "name")); + tick(pickup); + + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + assertEquals(clock.instant(), state.getLastPickupAt()); + } + + @Test + void aServerThatIsDownIsRetriedOnABackoffUntilItAnswers() throws Exception { + pairedState(); + doThrow(new ResourceAccessException("connection refused")).when(api).listBackups(SERVER); + BackupPickupService pickup = start(); + + tick(pickup); + tick(pickup); + verify(api, times(1)).listBackups(SERVER); + + clock.advance(Duration.ofMinutes(1)); + tick(pickup); + verify(api, times(2)).listBackups(SERVER); + + clock.advance(Duration.ofMinutes(1)); + tick(pickup); + verify(api, times(2)).listBackups(SERVER); + + doReturn(List.of(LATEST, OLDER)).when(api).listBackups(SERVER); + clock.advance(Duration.ofMinutes(1)); + tick(pickup); + + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + assertEquals(clock.instant(), pairedState().getLastPickupAt()); + } + + @Test + void aServerWithoutBackupsIsReportedOnceAtInfoAndNeverAsAWarning() throws Exception { + pairedState(); + doReturn(List.of()).when(api).listBackups(SERVER); + BackupPickupService pickup = start(); + ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(BackupPickupService.class); + ch.qos.logback.core.read.ListAppender logs = new ch.qos.logback.core.read.ListAppender<>(); + logs.start(); + logger.addAppender(logs); + try { + for (int i = 0; i < 4; i++) { + tick(pickup); + clock.advance(Duration.ofMinutes(20)); + } + verify(api, times(4)).listBackups(SERVER); + } finally { + logger.detachAppender(logs); + } + + assertTrue(logs.list.stream().noneMatch(event -> event.getLevel().isGreaterOrEqual(ch.qos.logback.classic.Level.WARN))); + assertEquals(1, logs.list.stream().filter(event -> event.getLevel() == ch.qos.logback.classic.Level.INFO && event.getFormattedMessage().contains("no backups")).count()); + } + + @Test + void switchingTheActiveServerReportsAnEmptyServerAgain() throws Exception { + pairedState(); + doReturn(List.of()).when(api).listBackups(SERVER); + BackupPickupService pickup = start(); + ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(BackupPickupService.class); + ch.qos.logback.core.read.ListAppender logs = new ch.qos.logback.core.read.ListAppender<>(); + logs.start(); + logger.addAppender(logs); + try { + tick(pickup); + clock.advance(Duration.ofMinutes(20)); + state.setActiveServer("http://other:8080"); + state.setActiveServer(SERVER); + tick(pickup); + } finally { + logger.detachAppender(logs); + } + + assertEquals(2, logs.list.stream().filter(event -> event.getLevel() == ch.qos.logback.classic.Level.INFO && event.getFormattedMessage().contains("no backups")).count()); + } + + @Test + void aRejectedTokenIsRetriedOnABackoffAndKeepsTheLastPickup() throws Exception { + Instant last = clock.instant().minus(INTERVAL).minusSeconds(1); + pairedState().recordPickup(SERVER, last); + doThrow(new PairingRequiredException("rejected")).when(api).listBackups(SERVER); + BackupPickupService pickup = start(); + + tick(pickup); + tick(pickup); + + verify(api, times(1)).listBackups(SERVER); + assertEquals(last, pairedState().getLastPickupAt()); + } + + @Test + void aDownloadInterruptedByARestartIsRepeatedAfterwards() throws Exception { + pairedState(); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenThrow(new DownloadFailedException("connection reset")); + + tick(restart()); + + assertNull(pairedState().getLastPickupAt()); + + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + tick(restart()); + + verify(api, times(2)).downloadById(eq(SERVER), eq("b2"), any(), any()); + assertEquals(clock.instant(), pairedState().getLastPickupAt()); + } + + @Test + void shorteningTheIntervalMakesAnOverduePickupDue() throws Exception { + pairedState().recordPickup(SERVER, clock.instant().minus(Duration.ofHours(5))); + BackupPickupService pickup = start(); + tick(pickup); + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + + pickup.updatePickupInterval(Duration.ofHours(4)); + tick(pickup); + + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + } + + @Test + void lengtheningTheIntervalMovesTheDueTimeFromTheLastPickup() throws Exception { + Instant last = clock.instant().minus(Duration.ofHours(5)); + pairedState().recordPickup(SERVER, last); + BackupPickupService pickup = start(); + + pickup.updatePickupInterval(Duration.ofHours(8)); + assertEquals(last.plus(Duration.ofHours(8)), pickup.nextPickup()); + clock.advance(Duration.ofHours(3).minusSeconds(1)); + tick(pickup); + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + + clock.advance(Duration.ofSeconds(1)); + tick(pickup); + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + } + + @Test + void aManualDownloadOfTheLatestArchiveRecordsAPickup() throws Exception { + pairedState(); + BackupPickupService pickup = start(); + + PickupProgressDto progress = awaitFinished(pickup, pickup.startPickupLatestTask().taskId()); + + assertEquals("COMPLETED", progress.status()); + assertEquals(clock.instant(), state.getLastPickupAt()); + } + + @Test + void aManualDownloadOfAnOlderArchiveDoesNotRecordAPickup() throws Exception { + pairedState(); + BackupPickupService pickup = start(); + + PickupProgressDto progress = awaitFinished(pickup, pickup.startPickupByIdTask("b1").taskId()); + + assertEquals("COMPLETED", progress.status()); + assertNull(state.getLastPickupAt()); + } + + @Test + void aFailedManualDownloadDoesNotRecordAPickup() throws Exception { + pairedState(); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenThrow(new DownloadFailedException("disk full")); + BackupPickupService pickup = start(); + + PickupProgressDto progress = awaitFinished(pickup, pickup.startPickupLatestTask().taskId()); + + assertEquals("FAILED", progress.status()); + assertNull(state.getLastPickupAt()); + } + + @Test + void aScheduledPickupAndAManualOneNeverDownloadTheSameBackupTwice() throws Exception { + pairedState(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(5, TimeUnit.SECONDS); + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + BackupPickupService pickup = start(); + + pickup.scheduledPickup(); + started.await(5, TimeUnit.SECONDS); + String taskId = pickup.startPickupLatestTask().taskId(); + release.countDown(); + awaitIdle(pickup); + awaitFinished(pickup, taskId); + + verify(api, times(1)).downloadById(anyString(), anyString(), any(), any()); + } + + @Test + void switchingTheActiveServerMakesTheNextPickupDueAtOnce() throws Exception { + pairedState().recordPickup(SERVER, clock.instant()); + + state.setActiveServer(SERVER); + assertEquals(clock.instant(), state.getLastPickupAt()); + + state.setActiveServer("http://other:8080"); + + assertNull(state.getLastPickupAt()); + assertNull(new ClientStateService(configuration, new JsonMapper()).getLastPickupAt()); + } + + @Test + void aFailedRecordOfThePickupBacksOffInsteadOfRetryingEveryTick() throws Exception { + ClientStateService failing = mock(ClientStateService.class); + when(failing.getActiveServer()).thenReturn(SERVER); + when(failing.requireActiveServer()).thenReturn(SERVER); + when(failing.hasPairing(SERVER)).thenReturn(true); + when(failing.getPickupInterval()).thenReturn(INTERVAL); + doThrow(new IllegalStateException("disk full")).when(failing).recordPickup(any(), any()); + BackupPickupService pickup = new BackupPickupService(configuration, failing, api, clock); + services.add(pickup); + + tick(pickup); + tick(pickup); + verify(api, times(1)).listBackups(SERVER); + + clock.advance(Duration.ofMinutes(1)); + tick(pickup); + verify(api, times(2)).listBackups(SERVER); + } + + @Test + void aPickupThatFinishesAfterTheServerWasSwitchedDoesNotDelayTheNewServer() throws Exception { + pairedState(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(5, TimeUnit.SECONDS); + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + BackupPickupService pickup = start(); + + pickup.scheduledPickup(); + started.await(5, TimeUnit.SECONDS); + state.setActiveServer("http://other:8080"); + release.countDown(); + awaitIdle(pickup); + + assertNull(state.getLastPickupAt()); + assertNull(new ClientStateService(configuration, new JsonMapper()).getLastPickupAt()); + } + + @Test + void aManualLatestDownloadThatFinishesAfterTheServerWasSwitchedDoesNotDelayTheNewServer() throws Exception { + pairedState(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(5, TimeUnit.SECONDS); + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + BackupPickupService pickup = start(); + + String taskId = pickup.startPickupLatestTask().taskId(); + started.await(5, TimeUnit.SECONDS); + state.setActiveServer("http://other:8080"); + release.countDown(); + + assertEquals("COMPLETED", awaitFinished(pickup, taskId).status()); + assertNull(state.getLastPickupAt()); + } + + @Test + void aScheduledPickupIsRecordedBeforeItsTaskReportsCompleted() throws Exception { + pairedState(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(5, TimeUnit.SECONDS); + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + ClientStateService spied = spy(state); + BackupPickupService pickup = new BackupPickupService(configuration, spied, api, clock); + services.add(pickup); + List statusWhenRecorded = new ArrayList<>(); + String[] taskId = new String[1]; + doAnswer(invocation -> { + statusWhenRecorded.add(pickup.pickupProgress(taskId[0]).status()); + return invocation.callRealMethod(); + }).when(spied).recordPickup(anyString(), any()); + + pickup.scheduledPickup(); + started.await(5, TimeUnit.SECONDS); + taskId[0] = pickup.startPickupLatestTask().taskId(); + release.countDown(); + awaitIdle(pickup); + + assertEquals(List.of("RUNNING"), statusWhenRecorded); + assertEquals("COMPLETED", pickup.pickupProgress(taskId[0]).status()); + } + + @Test + void aTickDuringAManualLatestDownloadDefersAndTheManualDownloadRecordsThePickup() throws Exception { + pairedState(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(5, TimeUnit.SECONDS); + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + BackupPickupService pickup = start(); + + String taskId = pickup.startPickupLatestTask().taskId(); + started.await(5, TimeUnit.SECONDS); + tick(pickup); + + assertNull(state.getLastPickupAt()); + clock.advance(Duration.ofSeconds(30)); + tick(pickup); + verify(api, times(1)).downloadById(anyString(), anyString(), any(), any()); + + release.countDown(); + assertEquals("COMPLETED", awaitFinished(pickup, taskId).status()); + + assertEquals(clock.instant(), state.getLastPickupAt()); + clock.advance(Duration.ofMinutes(5)); + tick(pickup); + verify(api, times(1)).downloadById(anyString(), anyString(), any(), any()); + } + + @Test + void aPartFileLeftByACrashIsRemovedByTheNextPickup() throws Exception { + pairedState(); + Path junk = downloads.resolve("b0-media-backup-AD.zip.part"); + Path unrelated = downloads.resolve("notes.txt"); + Files.write(junk, new byte[7]); + Files.write(unrelated, new byte[1]); + + tick(start()); + + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + assertEquals(clock.instant(), state.getLastPickupAt()); + assertFalse(Files.exists(junk)); + assertTrue(Files.exists(unrelated)); + assertTrue(Files.exists(downloads.resolve("b2-media-backup-AD.zip"))); + } + + @Test + void aPartFileIsRemovedBeforeAManualPickupToo() throws Exception { + pairedState(); + Path junk = downloads.resolve("b9-media-backup.zip.part"); + Files.write(junk, new byte[7]); + BackupPickupService pickup = start(); + + assertEquals("COMPLETED", awaitFinished(pickup, pickup.startPickupByIdTask("b1").taskId()).status()); + + assertFalse(Files.exists(junk)); + } + + @Test + void aPartFileLeftByACrashIsRemovedAtStartup() throws Exception { + Path junk = downloads.resolve("b2-media-backup-AD.zip.part"); + Files.write(junk, new byte[7]); + + start().removeStalePartFilesAtStartup(); + + assertFalse(Files.exists(junk)); + } + + @Test + void aPartFileOfATransferInProgressIsNeverRemoved() throws Exception { + pairedState(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + Path target = invocation.getArgument(2); + Files.write(target.resolveSibling(target.getFileName() + ".part"), new byte[2]); + started.countDown(); + release.await(5, TimeUnit.SECONDS); + Files.write(target, new byte[4]); + return target; + }); + Path junk = downloads.resolve("b0-media-backup.zip.part"); + Files.write(junk, new byte[7]); + BackupPickupService pickup = start(); + + pickup.scheduledPickup(); + started.await(5, TimeUnit.SECONDS); + assertEquals("COMPLETED", awaitFinished(pickup, pickup.startPickupByIdTask("b1").taskId()).status()); + Path inProgress = downloads.resolve("b2-media-backup-AD.zip.part"); + boolean keptWhileRunning = Files.exists(inProgress); + boolean junkGone = !Files.exists(junk); + release.countDown(); + awaitIdle(pickup); + + assertTrue(keptWhileRunning); + assertTrue(junkGone); + assertEquals(clock.instant(), state.getLastPickupAt()); + } + + private ClientStateService pairedState() { + state.setActiveServer(SERVER); + state.storePairing(SERVER, new StoredPairing("token", "id", "name")); + return state; + } + + private BackupPickupService restart() { + state = new ClientStateService(configuration, new JsonMapper()); + return start(); + } + + private BackupPickupService start() { + BackupPickupService service = new BackupPickupService(configuration, state, api, clock); + services.add(service); + return service; + } + + private void tick(BackupPickupService pickup) throws InterruptedException { + pickup.scheduledPickup(); + awaitIdle(pickup); + } + + private static void awaitIdle(BackupPickupService pickup) throws InterruptedException { + for (int attempt = 0; attempt < 500 && pickup.scheduledRunning(); attempt++) { + Thread.sleep(10); + } + if (pickup.scheduledRunning()) { + throw new AssertionError("The scheduled pickup did not finish"); + } + } + + private static PickupProgressDto awaitFinished(BackupPickupService pickup, String taskId) throws InterruptedException { + for (int attempt = 0; attempt < 500; attempt++) { + PickupProgressDto progress = pickup.pickupProgress(taskId); + if (progress.status().equals("COMPLETED") || progress.status().equals("FAILED")) { + return progress; + } + Thread.sleep(10); + } + throw new AssertionError("Pickup task " + taskId + " did not finish"); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/SemVerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/SemVerTest.java new file mode 100644 index 0000000..92f90db --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/SemVerTest.java @@ -0,0 +1,63 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +class SemVerTest { + + private static SemVer v(String text) { + return SemVer.parse(text).orElseThrow(); + } + + @Test + void parsesWithAndWithoutLeadingV() { + assertEquals(new SemVer(0, 1, 0, List.of()), v("0.1.0")); + assertEquals(new SemVer(0, 1, 0, List.of()), v("v0.1.0")); + assertEquals(new SemVer(12, 34, 56, List.of()), v(" v12.34.56 ")); + } + + @Test + void parsesPrereleaseAndIgnoresBuildMetadata() { + assertEquals(new SemVer(1, 0, 0, List.of("rc", "1")), v("v1.0.0-rc.1+build.5")); + assertEquals(0, v("1.0.0+a").compareTo(v("1.0.0+b"))); + } + + @ParameterizedTest + @NullSource + @ValueSource(strings = {"", " ", "1", "1.2", "v1.2", "1.2.3.4", "latest", "1.2.x", "1.2.3-", "1.2.3-a..b", "vv1.2.3", "1.2.3 beta", "99999999999999999999.0.0"}) + void rejectsInvalidVersions(String text) { + assertEquals(Optional.empty(), SemVer.parse(text)); + } + + @Test + void comparesNumericallyNotLexically() { + assertTrue(v("0.10.0").compareTo(v("0.9.0")) > 0); + assertTrue(v("1.0.0").compareTo(v("0.99.99")) > 0); + assertTrue(v("0.1.10").compareTo(v("0.1.9")) > 0); + assertTrue(v("0.1.0").compareTo(v("0.2.0")) < 0); + assertEquals(0, v("v0.1.0").compareTo(v("0.1.0"))); + } + + @Test + void ordersPrereleasesPerSemver() { + List ascending = List.of("1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.beta", "1.0.0-beta", "1.0.0-beta.2", "1.0.0-beta.11", "1.0.0-rc.1", "1.0.0"); + for (int i = 0; i < ascending.size() - 1; i++) { + assertTrue(v(ascending.get(i)).compareTo(v(ascending.get(i + 1))) < 0, ascending.get(i) + " < " + ascending.get(i + 1)); + assertTrue(v(ascending.get(i + 1)).compareTo(v(ascending.get(i))) > 0); + } + } + + @Test + void rendersWithoutPrefixOrMetadata() { + assertEquals("0.2.0", v("v0.2.0").toString()); + assertEquals("1.0.0-rc.1", v("v1.0.0-rc.1+x").toString()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java new file mode 100644 index 0000000..cd76332 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java @@ -0,0 +1,590 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.http.HttpConnectTimeoutException; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClientResponseException; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.api.ApiExceptionHandler; +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.PairingCodeDto; +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.dto.WebhookStatusDto; +import wellatleastitried.mediagarrdclient.dto.WebhookTestDto; +import wellatleastitried.mediagarrdclient.golden.Fixtures; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; + +class ServerApiServiceTest { + + private record Exchange(String method, String path, String body) { + } + + private final List exchanges = new ArrayList<>(); + private final List authorizations = new ArrayList<>(); + private volatile Optional token = Optional.of("secret-token"); + private final ServerApiService service = new ServerApiService(Duration.ofHours(6), url -> token, ServerTls.defaults()); + private HttpServer server; + private String serverUrl; + private int status = 200; + private String response = "{}"; + private Duration delay = Duration.ZERO; + private String location; + private final CountDownLatch release = new CountDownLatch(1); + + @BeforeEach + void startServer() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", this::handle); + server.start(); + serverUrl = "http://127.0.0.1:" + server.getAddress().getPort(); + } + + @AfterEach + void stopServer() { + release.countDown(); + server.stop(0); + } + + @Test + void tellsListenersWhichServerRejectedTheToken() { + List rejected = new ArrayList<>(); + service.addTokenRejectedListener(rejected::add); + status = 401; + + assertThrows(PairingRequiredException.class, () -> service.listBackups(serverUrl)); + + assertEquals(List.of(serverUrl), rejected); + } + + @Test + void doesNotTellListenersWhenNoTokenIsStored() { + List rejected = new ArrayList<>(); + service.addTokenRejectedListener(rejected::add); + token = Optional.empty(); + + assertThrows(PairingRequiredException.class, () -> service.listBackups(serverUrl)); + + assertEquals(List.of(), rejected); + } + + @Test + void savesADownloadOwnerOnly(@org.junit.jupiter.api.io.TempDir java.nio.file.Path tempDir) throws Exception { + response = "PK\u0003\u0004zip"; + java.nio.file.Path destination = tempDir.resolve("fresh").resolve("b1.zip"); + + service.downloadById(serverUrl, "b1", destination, null); + + if (java.nio.file.Files.getFileStore(destination).supportsFileAttributeView("posix")) { + assertEquals("rw-------", java.nio.file.attribute.PosixFilePermissions.toString(java.nio.file.Files.getPosixFilePermissions(destination))); + assertEquals("rwx------", java.nio.file.attribute.PosixFilePermissions.toString(java.nio.file.Files.getPosixFilePermissions(destination.getParent()))); + } + } + + @Test + void aStalledDownloadFailsAndLeavesNoPartFile(@org.junit.jupiter.api.io.TempDir java.nio.file.Path tempDir) throws Exception { + server.createContext("/api/v1/backups/stall/download", exchange -> { + exchange.sendResponseHeaders(200, 100); + OutputStream out = exchange.getResponseBody(); + out.write("PK\u0003\u0004".getBytes(StandardCharsets.UTF_8)); + out.flush(); + try { + release.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + exchange.close(); + }); + ServerApiService stalling = new ServerApiService(Duration.ofHours(6), Duration.ofMillis(300), url -> token, ServerTls.defaults()); + java.nio.file.Path destination = tempDir.resolve("stall.zip"); + + DownloadFailedException e = assertThrows(DownloadFailedException.class, () -> stalling.downloadById(serverUrl, "stall", destination, null)); + + assertTrue(e.getMessage().contains("stopped sending data")); + try (var files = java.nio.file.Files.list(tempDir)) { + assertEquals(List.of(), files.toList()); + } + stalling.shutdown(); + } + + @Test + void aFailedDownloadMessageDoesNotLeakThePath(@org.junit.jupiter.api.io.TempDir java.nio.file.Path tempDir) { + response = "not a zip"; + + DownloadFailedException e = assertThrows(DownloadFailedException.class, () -> service.downloadById(serverUrl, "b1", tempDir.resolve("b1.zip"), null)); + + assertFalse(e.getMessage().contains(tempDir.toString())); + } + + @Test + void sendsConfigUpdatesWithOmittedFieldsAsNull() { + response = "{\"backupLocation\": \"/backups\", \"retentionCount\": 5, \"backupInterval\": \"PT6H\"}"; + + ServerConfigDto config = service.updateServerConfig(serverUrl, null, 5); + + assertEquals(new ServerConfigDto("/backups", 5, Duration.ofHours(6)), config); + assertEquals(new Exchange("PUT", "/api/v1/config", "{\"backupLocation\":null,\"retentionCount\":5}"), exchanges.getFirst()); + } + + @Test + void readsTheServerVersionStatusAndIgnoresUnknownFields() { + response = "{\"currentVersion\": \"0.1.0\", \"latestVersion\": \"0.2.0\", \"releaseUrl\": \"https://github.com/MediaGarrd/Server/releases/tag/v0.2.0\"," + + " \"updateAvailable\": true, \"checkState\": \"OK\", \"checkedAt\": \"2026-11-11T18:00:00Z\", \"message\": null, \"extra\": 1}"; + + VersionStatusDto version = service.serverVersion(serverUrl); + + assertEquals(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), version); + assertEquals(new Exchange("GET", "/api/v1/version", ""), exchanges.getFirst()); + } + + @Test + void readsTheWebhookStatusAndTestFromTheServerPayloads() { + response = Fixtures.read("server/webhook-status.json"); + assertEquals(new WebhookStatusDto(true, "https://discord.com"), service.webhook(serverUrl)); + response = Fixtures.read("server/webhook-test.json"); + assertEquals(new WebhookTestDto(false, 404, "Webhook answered 404"), service.testWebhook(serverUrl)); + + assertEquals(new Exchange("GET", "/api/v1/notifications/webhook", ""), exchanges.get(0)); + assertEquals(new Exchange("POST", "/api/v1/notifications/webhook/test", ""), exchanges.get(1)); + assertEquals(List.of("Bearer secret-token", "Bearer secret-token"), authorizations); + } + + @Test + void sendsTheWebhookUrlAndClearsItWithAnEmptyString() { + response = Fixtures.read("server/webhook-status.json"); + + service.updateWebhook(serverUrl, "https://discord.com/api/webhooks/1/abc"); + service.updateWebhook(serverUrl, ""); + + assertEquals(new Exchange("PUT", "/api/v1/notifications/webhook", "{\"url\":\"https://discord.com/api/webhooks/1/abc\"}"), exchanges.get(0)); + assertEquals(new Exchange("PUT", "/api/v1/notifications/webhook", "{\"url\":\"\"}"), exchanges.get(1)); + } + + @Test + void theWebhookUrlIsNotWrittenToTheLog() { + ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + ch.qos.logback.core.read.ListAppender logs = new ch.qos.logback.core.read.ListAppender<>(); + logs.start(); + root.addAppender(logs); + try { + response = Fixtures.read("server/webhook-status.json"); + service.updateWebhook(serverUrl, "https://discord.com/api/webhooks/1/SECRETTOKEN"); + service.testWebhook(serverUrl); + } finally { + root.detachAppender(logs); + } + + assertTrue(logs.list.stream().noneMatch(event -> event.getFormattedMessage().contains("SECRETTOKEN"))); + } + + @Test + void aServerRejectionOfTheWebhookKeepsItsStatusAndMessage() { + status = 429; + response = "{\"error\":\"Wait 7 seconds before sending another test\"}"; + + RestClientResponseException e = assertThrows(RestClientResponseException.class, () -> service.testWebhook(serverUrl)); + + assertEquals(429, e.getStatusCode().value()); + } + + @Test + void sendsScheduleAsIsoDuration() { + response = "{\"healthy\": true, \"running\": false, \"backupRetentionCount\": 4, \"backupInterval\": \"PT1H30M\"}"; + + assertEquals(Duration.ofMinutes(90), service.updateServerSchedule(serverUrl, Duration.ofMinutes(90)).backupInterval()); + assertEquals(new Exchange("PUT", "/api/v1/schedule", "{\"backupInterval\":\"PT1H30M\"}"), exchanges.getFirst()); + } + + @Test + void encodesServiceNamesInPaths() { + ServiceDto radarr = new ServiceDto("radarr", List.of("/srv/radarr")); + response = "{\"name\": \"radarr\", \"paths\": [\"/srv/radarr\"]}"; + + assertEquals(radarr, service.updateService(serverUrl, "old name", radarr)); + status = 204; + service.removeService(serverUrl, "radarr"); + + assertEquals("/api/v1/services/old%20name", exchanges.get(0).path()); + assertEquals(new Exchange("DELETE", "/api/v1/services/radarr", ""), exchanges.get(1)); + } + + @Test + void forwardsTheServerErrorMessageAndStatus() { + status = 409; + response = "{\"error\": \"Service already exists: radarr\"}"; + + RestClientResponseException e = assertThrows(RestClientResponseException.class, + () -> service.addService(serverUrl, new ServiceDto("radarr", List.of("/srv/radarr")))); + ResponseEntity forwarded = new ApiExceptionHandler().serverRejected(e); + + assertEquals(HttpStatus.CONFLICT, forwarded.getStatusCode()); + assertEquals(Map.of("error", "Service already exists: radarr"), forwarded.getBody()); + } + + @Test + void fallsBackToTheStatusWhenTheServerSendsNoMessage() { + status = 502; + response = "Bad Gateway"; + + RestClientResponseException e = assertThrows(RestClientResponseException.class, () -> service.serverConfig(serverUrl)); + + assertEquals(Map.of("error", "MediaGarrd server responded with 502"), new ApiExceptionHandler().serverRejected(e).getBody()); + } + + @Test + void aFailedBackupRunCarriesTheServersReasonToTheDashboard() { + status = 500; + response = "{\"error\": \"Backup of radarr failed: disk is full\"}"; + + BackupRunFailedException e = assertThrows(BackupRunFailedException.class, () -> service.triggerBackup(serverUrl)); + ResponseEntity forwarded = new ApiExceptionHandler().backupRunFailed(e); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, forwarded.getStatusCode()); + assertEquals(Map.of("error", "Backup of radarr failed: disk is full"), forwarded.getBody()); + } + + @Test + void aFailedBackupRunWithoutAReasonFallsBackToTheStatus() { + status = 500; + response = "oops"; + + BackupRunFailedException e = assertThrows(BackupRunFailedException.class, () -> service.triggerBackup(serverUrl)); + + assertEquals("MediaGarrd server responded with 500", e.getMessage()); + } + + @Test + void everyOtherServerFailureKeepsTheGenericText() { + status = 500; + response = "{\"error\": \"Disk /srv/backups is full\"}"; + + RestClientResponseException e = assertThrows(RestClientResponseException.class, () -> service.listBackups(serverUrl)); + + assertEquals(Map.of("error", "MediaGarrd server responded with 500"), new ApiExceptionHandler().serverRejected(e).getBody()); + } + + @Test + void reportsABackupRunThatOutlastsTheTimeout() { + ServerApiService shortTimeout = new ServerApiService(Duration.ofMillis(200), url -> token, ServerTls.defaults()); + delay = Duration.ofSeconds(2); + + BackupRunTimeoutException e = assertThrows(BackupRunTimeoutException.class, () -> shortTimeout.triggerBackup(serverUrl)); + ResponseEntity forwarded = new ApiExceptionHandler().backupRunTimedOut(e); + + assertEquals("POST", exchanges.get(0).method()); + assertEquals("/api/v1/backups/run", exchanges.get(0).path()); + assertEquals(HttpStatus.GATEWAY_TIMEOUT, forwarded.getStatusCode()); + assertTrue(e.getMessage().contains("still running on the server")); + } + + @Test + void rejectsABackupRunTimeoutBelowTheMinimum() { + assertRejected(null); + assertRejected(Duration.ofSeconds(-1)); + assertRejected(Duration.ZERO); + IllegalStateException e = assertRejected(Duration.ofSeconds(59)); + assertTrue(e.getMessage().contains("at least PT1M")); + MediaGarrdProperties ok = new MediaGarrdProperties(); + ok.setBackupRunTimeout(Duration.ofMinutes(1)); + new ServerApiService(ok, mock(ClientStateService.class), ServerTls.defaults()); + } + + private static IllegalStateException assertRejected(Duration timeout) { + MediaGarrdProperties properties = new MediaGarrdProperties(); + properties.setBackupRunTimeout(timeout); + return assertThrows(IllegalStateException.class, () -> new ServerApiService(properties, mock(ClientStateService.class), ServerTls.defaults())); + } + + @Test + void mapsAReadTimeoutOnTheOrdinaryClientsToGatewayTimeout() { + ServerApiService impatient = new ServerApiService(Duration.ofHours(6), Duration.ofSeconds(60), Duration.ofMillis(200), Duration.ofMillis(200), url -> token, ServerTls.defaults()); + delay = Duration.ofSeconds(3); + ResourceAccessException e = assertThrows(ResourceAccessException.class, () -> impatient.health(serverUrl)); + + assertEquals(HttpStatus.GATEWAY_TIMEOUT, new ApiExceptionHandler().serverUnreachable(e).getStatusCode()); + assertEquals(Map.of("error", "MediaGarrd server did not respond in time"), new ApiExceptionHandler().serverUnreachable(e).getBody()); + } + + @Test + void sendsTheBearerTokenOnEveryAuthenticatedCall() { + ServiceDto radarr = new ServiceDto("radarr", List.of()); + + response = "[]"; + service.listBackups(serverUrl); + service.listServices(serverUrl); + response = "{\"name\": \"radarr\", \"paths\": []}"; + service.triggerBackup(serverUrl); + service.serverConfig(serverUrl); + service.updateServerConfig(serverUrl, "/b", 3); + service.updateServerSchedule(serverUrl, Duration.ofHours(1)); + service.addService(serverUrl, radarr); + service.updateService(serverUrl, "radarr", radarr); + status = 204; + service.removeService(serverUrl, "radarr"); + service.revokeClient(serverUrl, "abc"); + + assertEquals(10, authorizations.size()); + assertTrue(authorizations.stream().allMatch("Bearer secret-token"::equals), authorizations.toString()); + } + + @Test + void sendsTheTokenOnHealthOnlyWhenPairedAndNeverOnTheVersion() { + response = "{\"healthy\": true, \"running\": false, \"backupRetentionCount\": 4, \"backupInterval\": \"PT1H\"}"; + + service.health(serverUrl); + token = Optional.empty(); + service.health(serverUrl); + token = Optional.of("secret-token"); + service.serverVersion(serverUrl); + + assertEquals(List.of("Bearer secret-token", "null", "null"), authorizations); + } + + @Test + void doesNotCallTheServerOnAnAuthenticatedRequestWithoutAToken() { + token = Optional.empty(); + + assertThrows(PairingRequiredException.class, () -> service.listBackups(serverUrl)); + assertThrows(PairingRequiredException.class, () -> service.downloadById(serverUrl, "b1", java.nio.file.Path.of("/nonexistent/x.zip"), null)); + + assertTrue(exchanges.isEmpty()); + } + + @Test + void turnsAServer401IntoPairingRequiredForEveryKindOfCall(@org.junit.jupiter.api.io.TempDir java.nio.file.Path dir) { + status = 401; + response = "{\"error\": \"Invalid or revoked token\"}"; + + assertThrows(PairingRequiredException.class, () -> service.listBackups(serverUrl)); + assertThrows(PairingRequiredException.class, () -> service.health(serverUrl)); + assertThrows(PairingRequiredException.class, () -> service.triggerBackup(serverUrl)); + assertThrows(PairingRequiredException.class, () -> service.downloadById(serverUrl, "b1", dir.resolve("b.zip"), null)); + PairingRequiredException e = assertThrows(PairingRequiredException.class, () -> service.createPairingCode(serverUrl)); + ResponseEntity forwarded = new ApiExceptionHandler().pairingRequired(e); + + assertEquals(HttpStatus.BAD_GATEWAY, forwarded.getStatusCode()); + assertEquals("required", ((Map) forwarded.getBody()).get("pairing")); + } + + @Test + void doesNotFollowARedirectAndNamesWhereItPointed() { + status = 301; + location = "https://mediagarrd.example.com/api/v1/backups"; + + ServerRedirectException e = assertThrows(ServerRedirectException.class, () -> service.listBackups(serverUrl)); + + assertEquals("https://mediagarrd.example.com/api/v1/backups", e.location()); + assertTrue(e.getMessage().contains("https://mediagarrd.example.com/api/v1/backups")); + assertEquals(1, exchanges.size()); + assertEquals(HttpStatus.BAD_GATEWAY, new ApiExceptionHandler().serverRedirected(e).getStatusCode()); + } + + @Test + void doesNotFollowARedirectOnADownloadEither(@org.junit.jupiter.api.io.TempDir java.nio.file.Path dir) { + status = 302; + location = "https://elsewhere.example.com/download"; + + assertThrows(ServerRedirectException.class, () -> service.downloadById(serverUrl, "b1", dir.resolve("b.zip"), null)); + + assertEquals(1, exchanges.size()); + assertEquals(List.of("Bearer secret-token"), authorizations); + } + + @Test + void pairsWithoutATokenAndKeepsTheTokenOutOfTheLog() { + token = Optional.empty(); + response = "{\"token\": \"abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG\", \"id\": \"0123456789abcdef\", \"name\": \"Home\"}"; + + StoredPairing pairing = service.pair(serverUrl, "123456", "Home"); + + assertEquals("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG", pairing.token()); + assertEquals("0123456789abcdef", pairing.id()); + assertFalse(pairing.toString().contains("abcdefghij")); + assertEquals(new Exchange("POST", "/api/v1/pair", "{\"pin\":\"123456\",\"name\":\"Home\"}"), exchanges.getFirst()); + assertEquals("null", authorizations.getFirst()); + } + + @Test + void aWrongPinIsABadRequestNotAPairingRequiredSignal() { + token = Optional.empty(); + status = 401; + response = "{\"error\": \"Invalid PIN\"}"; + + InvalidRequestException e = assertThrows(InvalidRequestException.class, () -> service.pair(serverUrl, "000000", "Home")); + + assertEquals("Invalid PIN", e.getMessage()); + } + + @Test + void passesOnWhyPairingIsClosedOrLocked() { + token = Optional.empty(); + status = 429; + response = "{\"error\": \"Too many attempts\"}"; + + RestClientResponseException e = assertThrows(RestClientResponseException.class, () -> service.pair(serverUrl, "000000", "Home")); + + assertEquals(Map.of("error", "Too many attempts"), new ApiExceptionHandler().serverRejected(e).getBody()); + assertEquals(HttpStatus.TOO_MANY_REQUESTS, new ApiExceptionHandler().serverRejected(e).getStatusCode()); + } + + @Test + void confirmsAPairingWithTheNewTokenAndNotTheStoredOne() { + token = Optional.of("stored-token"); + response = "{\"healthy\": true, \"running\": false, \"backupRetentionCount\": 4, \"backupInterval\": \"PT1H\"}"; + + service.confirmPairing(serverUrl, "new-token"); + + assertEquals(new Exchange("GET", "/api/v1/health", ""), exchanges.getFirst()); + assertEquals(List.of("Bearer new-token"), authorizations); + } + + @Test + void aPublicOnlyHealthReplyIsNotAConfirmation() { + response = "{\"healthy\": true, \"backupInterval\": \"PT1H\"}"; + + ConfirmationRefusedException e = assertThrows(ConfirmationRefusedException.class, () -> service.confirmPairing(serverUrl, "new-token")); + + assertTrue(e.getMessage().contains("did not confirm"), e.getMessage()); + } + + @Test + void aRefusedConfirmationIsABadRequestAndDoesNotTellListenersTheStoredTokenFailed() { + List rejected = new ArrayList<>(); + service.addTokenRejectedListener(rejected::add); + status = 401; + response = "{\"error\": \"nope\"}"; + + InvalidRequestException e = assertThrows(InvalidRequestException.class, () -> service.confirmPairing(serverUrl, "new-token")); + + assertTrue(e.getMessage().contains("did not accept this pairing"), e.getMessage()); + assertTrue(rejected.isEmpty()); + } + + @Test + void aServerErrorOnConfirmationIsAnUpstreamFailure() { + status = 500; + response = "{\"error\": \"Internal error\"}"; + + UpstreamResponseException e = assertThrows(UpstreamResponseException.class, () -> service.confirmPairing(serverUrl, "new-token")); + + assertTrue(e.getMessage().contains("500"), e.getMessage()); + assertEquals(1, exchanges.size()); + } + + @Test + void gatewayStatusesOnConfirmationAreMarkedRetryable() { + for (int gateway : new int[] {502, 503, 504}) { + exchanges.clear(); + status = gateway; + response = "{}"; + + ConfirmationUnavailableException e = assertThrows(ConfirmationUnavailableException.class, () -> service.confirmPairing(serverUrl, "new-token")); + + assertTrue(e.getMessage().contains(String.valueOf(gateway)), e.getMessage()); + } + } + + @Test + void aRedirectOnConfirmationIsRefused() { + status = 302; + location = "http://127.0.0.1:1/api/v1/health"; + + assertThrows(ServerRedirectException.class, () -> service.confirmPairing(serverUrl, "new-token")); + + assertEquals(1, exchanges.size()); + } + + @Test + void readsAPairingCode() { + response = "{\"code\": \"ABCDE-FGHJK\", \"expiresAt\": \"2026-11-19T12:10:00Z\"}"; + + PairingCodeDto code = service.createPairingCode(serverUrl); + + assertEquals("ABCDE-FGHJK", code.code()); + assertEquals(Instant.parse("2026-11-19T12:10:00Z"), code.expiresAt()); + assertEquals(new Exchange("POST", "/api/v1/pairing-codes", ""), exchanges.getFirst()); + assertEquals(1, exchanges.size()); + } + + @Test + void survivesACyclicCauseChain() { + Exception a = new Exception("a"); + Exception b = new Exception("b", a); + a.initCause(b); + + assertFalse(RequestTimeouts.isTimeout(a)); + assertFalse(RequestTimeouts.isReadTimeout(a)); + } + + @Test + void mapsAConnectionRefusedToBadGateway() { + ResourceAccessException e = assertThrows(ResourceAccessException.class, () -> service.health("http://127.0.0.1:1")); + + assertEquals(HttpStatus.BAD_GATEWAY, new ApiExceptionHandler().serverUnreachable(e).getStatusCode()); + RuntimeException backupRun = assertThrows(RuntimeException.class, () -> service.triggerBackup("http://127.0.0.1:1")); + assertInstanceOf(ResourceAccessException.class, backupRun); + assertFalse(backupRun instanceof BackupRunTimeoutException); + } + + @Test + void treatsAConnectTimeoutAsATimeoutButNotAsAReadTimeout() { + Throwable connect = new ResourceAccessException("x", new IOException("y", new HttpConnectTimeoutException("z"))); + + assertTrue(RequestTimeouts.isTimeout(connect)); + assertFalse(RequestTimeouts.isReadTimeout(connect)); + assertEquals(HttpStatus.GATEWAY_TIMEOUT, new ApiExceptionHandler().serverUnreachable((ResourceAccessException) connect).getStatusCode()); + } + + private void handle(HttpExchange exchange) throws IOException { + String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); + exchanges.add(new Exchange(exchange.getRequestMethod(), exchange.getRequestURI().getRawPath(), body)); + authorizations.add(String.valueOf(exchange.getRequestHeaders().getFirst("Authorization"))); + try { + release.await(delay.toMillis(), TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + byte[] bytes = response.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + if (location != null) { + exchange.getResponseHeaders().add("Location", location); + } + if (status == 204) { + exchange.sendResponseHeaders(204, -1); + } else { + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + } + exchange.close(); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java new file mode 100644 index 0000000..462bf83 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java @@ -0,0 +1,356 @@ +package wellatleastitried.mediagarrdclient.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.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.scheduling.annotation.Scheduled; + +import tools.jackson.databind.json.JsonMapper; +import com.sun.net.httpserver.HttpServer; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService.HostInput; + +@Timeout(10) +class ServerDiscoveryServiceTest { + + private static final String HEALTH = "{\"healthy\":true,\"running\":false,\"backupRetentionCount\":4,\"backupInterval\":\"PT6H\"}"; + + private final MediaGarrdProperties configuration = new MediaGarrdProperties(); + private final ClientStateService state = mock(ClientStateService.class); + private final ServerDiscoveryService discovery = new ServerDiscoveryService(configuration, state, JsonMapper.builder().build(), ServerTls.defaults()); + private HttpServer mediaGarrd; + private HttpServer otherApp; + + @BeforeEach + void startServers() throws IOException { + mediaGarrd = serve(HEALTH); + otherApp = serve("ok"); + } + + @AfterEach + void stopServers() { + mediaGarrd.stop(0); + otherApp.stop(0); + discovery.shutdown(); + } + + @Test + void resolvesTheGivenPort() { + assertEquals(Optional.of(url(mediaGarrd)), discovery.resolveServerByIp("127.0.0.1", port(mediaGarrd))); + } + + @Test + void readsThePortFromTheAddress() { + assertEquals(Optional.of(url(mediaGarrd)), discovery.resolveServerByIp("127.0.0.1:" + port(mediaGarrd), null)); + } + + @Test + void scansEveryPortWhenTheGivenPortIsNotAMediaGarrdServer() { + long start = System.nanoTime(); + + Optional found = discovery.resolveServerByIp("127.0.0.1", port(otherApp)); + + assertTrue(found.isPresent(), "no MediaGarrd server found by the port scan"); + assertNotEquals(url(otherApp), found.get()); + assertTrue(Duration.ofNanos(System.nanoTime() - start).toSeconds() < 15, "full port scan took too long"); + } + + @Test + void connectsThePreferredServerOnlyWhileNoneIsSelected() { + configuration.setPreferredServerIp("localhost:" + port(mediaGarrd)); + + discovery.connectPreferredServer(); + when(state.getActiveServer()).thenReturn("http://other:38471"); + discovery.connectPreferredServer(); + + verify(state, times(1)).setActiveServerIfBlank("http://localhost:" + port(mediaGarrd)); + } + + @Test + void keepsRetryingUntilThePreferredServerComesUp() throws IOException { + int freePort; + try (java.net.ServerSocket probe = new java.net.ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + freePort = probe.getLocalPort(); + } + configuration.setPreferredServerIp("127.0.0.1:" + freePort); + + discovery.connectPreferredServer(); + discovery.connectPreferredServer(); + verify(state, never()).setActiveServerIfBlank(anyString()); + + HttpServer late = serve(HEALTH, freePort); + try { + discovery.connectPreferredServer(); + verify(state, times(1)).setActiveServerIfBlank("http://127.0.0.1:" + freePort); + } finally { + late.stop(0); + } + } + + @Test + void abandonsAHangingResolveAtTheDeadlineAndNeverOverlapsAttempts() throws InterruptedException { + CountDownLatch release = new CountDownLatch(1); + AtomicInteger attempts = new AtomicInteger(); + AtomicBoolean resolveFinished = new AtomicBoolean(); + ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor(); + Duration deadline = Duration.ofMillis(300); + ServerDiscoveryService hanging = new ServerDiscoveryService(configuration, state, JsonMapper.builder().build(), ServerTls.defaults(), pool, deadline) { + @Override + public Optional resolvePreferredServer() { + attempts.incrementAndGet(); + long end = System.nanoTime() + Duration.ofSeconds(30).toNanos(); + while (release.getCount() > 0 && System.nanoTime() < end) { + try { + release.await(50, TimeUnit.MILLISECONDS); + } catch (InterruptedException ignored) { + } + } + resolveFinished.set(true); + return Optional.empty(); + } + }; + try { + hanging.connectPreferredServer(); + assertFalse(resolveFinished.get(), "the tick waited for the hanging resolve instead of abandoning it at the deadline"); + + hanging.connectPreferredServer(); + hanging.connectPreferredServer(); + assertEquals(1, attempts.get()); + + release.countDown(); + long waitUntil = System.nanoTime() + Duration.ofSeconds(5).toNanos(); + while (attempts.get() < 2 && System.nanoTime() < waitUntil) { + hanging.connectPreferredServer(); + Thread.sleep(20); + } + assertEquals(2, attempts.get()); + } finally { + release.countDown(); + hanging.shutdown(); + pool.shutdownNow(); + } + } + + @Test + void anAttemptCancelledBeforeItStartsDoesNotBlockLaterAttempts() { + List queued = new CopyOnWriteArrayList<>(); + ExecutorService deferred = new AbstractExecutorService() { + @Override + public void execute(Runnable command) { + queued.add(command); + } + + @Override + public void shutdown() { + } + + @Override + public List shutdownNow() { + return List.of(); + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return true; + } + }; + ServerDiscoveryService service = new ServerDiscoveryService(configuration, state, JsonMapper.builder().build(), ServerTls.defaults(), deferred, Duration.ofMillis(100)); + + service.connectPreferredServer(); + assertEquals(1, queued.size()); + service.connectPreferredServer(); + + assertEquals(2, queued.size(), "the guard stayed set after the attempt was cancelled before starting"); + queued.forEach(Runnable::run); + verify(state, never()).setActiveServerIfBlank(anyString()); + } + + @Test + void doesNotProbeOnceAServerIsSelected() throws IOException { + AtomicInteger requests = new AtomicInteger(); + mediaGarrd.stop(0); + mediaGarrd = serve(HEALTH, 0, requests); + configuration.setPreferredServerIp("127.0.0.1:" + port(mediaGarrd)); + when(state.getActiveServer()).thenReturn("http://other:38471"); + + discovery.connectPreferredServer(); + discovery.connectPreferredServer(); + + assertEquals(0, requests.get()); + verify(state, never()).setActiveServerIfBlank(anyString()); + } + + @Test + void givesUpQuicklyOnAnUnreachableHost() { + long start = System.nanoTime(); + + assertEquals(Optional.empty(), discovery.resolveServerByIp("192.0.2.1", 8123)); + assertTrue(Duration.ofNanos(System.nanoTime() - start).toSeconds() < 3, "unreachable host was port scanned"); + } + + @Test + void ignoresUnresolvableHosts() { + assertEquals(Optional.empty(), discovery.resolveServerByIp("no-such-host.invalid", null)); + assertEquals(Optional.empty(), discovery.resolveServerByIp(" ", null)); + } + + @Test + void rejectsHealthResponsesThatAreNotFromAMediaGarrdServer() throws IOException { + HttpServer lookalike = serve("{\"status\":\"UP\"}"); + try { + InetAddress loopback = InetAddress.getLoopbackAddress(); + assertFalse(discovery.isMediaGarrdServer(new ServerDiscoveryService.Candidate("127.0.0.1", loopback, port(lookalike)))); + assertFalse(discovery.isMediaGarrdServer(new ServerDiscoveryService.Candidate("127.0.0.1", loopback, port(otherApp)))); + assertTrue(discovery.isMediaGarrdServer(new ServerDiscoveryService.Candidate("127.0.0.1", loopback, port(mediaGarrd)))); + } finally { + lookalike.stop(0); + } + } + + @ParameterizedTest + @CsvSource({"24, 254, 192.168.1.1, 192.168.1.254", "16, 254, 192.168.1.1, 192.168.1.254", "30, 2, 192.168.1.77, 192.168.1.78", "32, 2, 192.168.1.77, 192.168.1.78"}) + void listsTheHostsOfTheLocalSubnet(int prefix, int count, String first, String last) throws IOException { + List hosts = ServerDiscoveryService.subnetHosts((Inet4Address) InetAddress.getByName("192.168.1.77"), prefix); + + assertEquals(count, hosts.size()); + assertEquals(first, hosts.getFirst().getHostAddress()); + assertEquals(last, hosts.getLast().getHostAddress()); + } + + @ParameterizedTest + @CsvSource(value = {"192.168.1.5, 192.168.1.5, null", "192.168.1.5:9000, 192.168.1.5, 9000", "http://server:38471/, server, 38471", "[::1]:8080, ::1, 8080"}, nullValues = "null") + void parsesHostsWithOptionalPorts(String input, String host, Integer port) { + assertEquals(new HostInput("http", host, port), ServerDiscoveryService.parseHost(input)); + } + + @Test + void rejectsInputWithoutAHost() { + assertNull(ServerDiscoveryService.parseHost("http://")); + } + + private static HttpServer serve(String body) throws IOException { + return serve(body, 0); + } + + private static HttpServer serve(String body, int port) throws IOException { + return serve(body, port, new AtomicInteger()); + } + + private static HttpServer serve(String body, int port, AtomicInteger requests) throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0); + server.createContext("/", exchange -> { + requests.incrementAndGet(); + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + }); + server.start(); + return server; + } + + private static int port(HttpServer server) { + return server.getAddress().getPort(); + } + + private static String url(HttpServer server) { + return "http://127.0.0.1:" + port(server); + } + + @ParameterizedTest + @CsvSource(value = {"https://garrd.example.com, garrd.example.com, null", "https://garrd.example.com:8443/, garrd.example.com, 8443", "HTTPS://Host, Host, null"}, nullValues = "null") + void keepsTheHttpsSchemeOfAnAddress(String input, String host, Integer port) { + HostInput parsed = ServerDiscoveryService.parseHost(input); + + assertEquals(new HostInput("https", host, port), parsed); + assertTrue(parsed.https()); + } + + @Test + void anHttpsCandidateOmitsTheDefaultPort() { + assertEquals("https://garrd.example.com", new ServerDiscoveryService.Candidate("https", "garrd.example.com", null, 443).url()); + assertEquals("https://garrd.example.com:8443", new ServerDiscoveryService.Candidate("https", "garrd.example.com", null, 8443).url()); + assertEquals("http://10.0.0.5:80", new ServerDiscoveryService.Candidate("10.0.0.5", null, 80).url()); + } + + @Test + void anHttpsAddressWithoutAPortIsProbedExactlyOnceOnPort443() { + List probed = new java.util.concurrent.CopyOnWriteArrayList<>(); + ServerDiscoveryService service = new ServerDiscoveryService(configuration, state, JsonMapper.builder().build(), ServerTls.defaults()) { + @Override + boolean isMediaGarrdServer(Candidate candidate) { + probed.add(candidate.url()); + return true; + } + }; + + assertEquals(java.util.Optional.of("https://127.0.0.1"), service.resolveServerByIp("https://127.0.0.1", null)); + assertEquals(java.util.Optional.of("https://127.0.0.1:8443"), service.resolveServerByIp("https://127.0.0.1:8443", null)); + assertEquals(java.util.Optional.of("https://127.0.0.1:9443"), service.resolveServerByIp("https://127.0.0.1", 9443)); + + assertEquals(List.of("https://127.0.0.1", "https://127.0.0.1:8443", "https://127.0.0.1:9443"), probed); + } + + @Test + void anHttpsPreferredServerIsProbedOnce() { + MediaGarrdProperties https = new MediaGarrdProperties(); + https.setPreferredServerIp("https://127.0.0.1"); + List probed = new java.util.concurrent.CopyOnWriteArrayList<>(); + ServerDiscoveryService service = new ServerDiscoveryService(https, state, JsonMapper.builder().build(), ServerTls.defaults()) { + @Override + boolean isMediaGarrdServer(Candidate candidate) { + probed.add(candidate.url()); + return false; + } + }; + + assertTrue(service.resolvePreferredServer().isEmpty()); + + assertEquals(List.of("https://127.0.0.1"), probed); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamServiceTest.java new file mode 100644 index 0000000..6f645da --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamServiceTest.java @@ -0,0 +1,793 @@ +package wellatleastitried.mediagarrdclient.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.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.web.client.ResourceAccessException; + +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.cfg.DateTimeFeature; +import tools.jackson.databind.json.JsonMapper; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; +import wellatleastitried.mediagarrdclient.service.ServerEventStreamService.Timing; + +@Timeout(30) +class ServerEventStreamServiceTest { + + private static final ObjectMapper MAPPER = JsonMapper.builder() + .findAndAddModules() + .disable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS, DateTimeFeature.WRITE_DURATIONS_AS_TIMESTAMPS) + .build(); + private static final Timing FAST = new Timing(Duration.ofSeconds(5), Duration.ofSeconds(30), Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofMillis(400), Duration.ZERO); + + interface Behavior { + void handle(HttpExchange exchange, int connection) throws Exception; + } + + static final class FakeServer { + + final HttpServer server; + final ExecutorService executor = Executors.newCachedThreadPool(); + final BlockingQueue connections = new LinkedBlockingQueue<>(); + final AtomicInteger count = new AtomicInteger(); + final CountDownLatch release = new CountDownLatch(1); + final List authorizations = new CopyOnWriteArrayList<>(); + + FakeServer(Behavior behavior) throws IOException { + server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + server.setExecutor(executor); + server.createContext("/api/v1/events", exchange -> { + int connection = count.incrementAndGet(); + authorizations.add(String.valueOf(exchange.getRequestHeaders().getFirst("Authorization"))); + connections.add(System.nanoTime()); + try { + behavior.handle(exchange, connection); + } catch (Exception e) { + exchange.close(); + } finally { + exchange.close(); + } + }); + server.start(); + } + + String url() { + return "http://127.0.0.1:" + server.getAddress().getPort(); + } + + long awaitConnection() throws InterruptedException { + Long at = connections.poll(10, TimeUnit.SECONDS); + assertNotNull(at, "the fake server was never contacted"); + return at; + } + + void stop() { + release.countDown(); + server.stop(0); + executor.shutdownNow(); + } + } + + @TempDir + Path tempDir; + + private ClientStateService state; + private RecordingPublisher publisher; + private DashboardService dashboard; + private ServerApiService serverApi; + private ExecutorService refreshes; + private ServerEventStreamService service; + private RecordingPublisher browser; + private final List servers = new ArrayList<>(); + + @BeforeEach + void setUp() { + MediaGarrdProperties configuration = new MediaGarrdProperties(); + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(Duration.ofHours(12)); + state = new ClientStateService(configuration, MAPPER); + publisher = new RecordingPublisher(); + serverApi = mock(ServerApiService.class); + when(serverApi.health(anyString())).thenThrow(new ResourceAccessException("refused")); + when(serverApi.serverVersion(anyString())).thenThrow(new ResourceAccessException("refused")); + UpdateCheckService updateCheck = mock(UpdateCheckService.class); + when(updateCheck.status()).thenReturn(new VersionStatusDto("0.1.0", null, null, false, CheckState.NOT_CHECKED, null, null)); + refreshes = Executors.newSingleThreadExecutor(); + dashboard = new DashboardService(state, publisher, serverApi, new VersionService(updateCheck, serverApi), updateCheck, MAPPER, refreshes, Clock.systemUTC()); + } + + @AfterEach + void tearDown() { + if (service != null) { + service.shutdown(); + } + refreshes.shutdownNow(); + servers.forEach(FakeServer::stop); + } + + private void activate(String url) { + state.storePairing(url, new StoredPairing("test-token", "abc", "Test")); + state.setActiveServer(url); + } + + private FakeServer fake(Behavior behavior) throws IOException { + FakeServer fake = new FakeServer(behavior); + servers.add(fake); + return fake; + } + + private void startService(Timing timing) { + service = new ServerEventStreamService(state, dashboard, MAPPER, ServerTls.defaults(), timing); + browser = dashboard.subscribe(publisher::subscribe).orElseThrow(); + service.start(); + } + + private static void frame(OutputStream out, String text) throws IOException { + out.write(text.getBytes(StandardCharsets.UTF_8)); + out.flush(); + } + + private static OutputStream open(HttpExchange exchange) throws IOException { + exchange.getResponseHeaders().add("Content-Type", "text/event-stream"); + exchange.sendResponseHeaders(200, 0); + OutputStream out = exchange.getResponseBody(); + frame(out, ": connected\n\n"); + return out; + } + + private static Behavior holdOpen(CountDownLatch closed, String... frames) { + return (exchange, connection) -> { + OutputStream out = open(exchange); + for (String text : frames) { + frame(out, text); + } + try { + while (true) { + Thread.sleep(10); + frame(out, ": keep\n\n"); + } + } catch (IOException e) { + closed.countDown(); + } + }; + } + + private List collectUntil(String marker) throws InterruptedException { + List seen = new ArrayList<>(); + while (true) { + seen.add(browser.next()); + if (seen.get(seen.size() - 1).contains(marker)) { + return seen; + } + } + } + + @Test + void forwardsRunEventsAndIgnoresEverythingElse() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + OutputStream out = open(exchange); + frame(out, "event:state\ndata:{\"running\":false,\"at\":\"t0\"}\n\n"); + frame(out, "event: ping\ndata: {}\n\n"); + frame(out, "event: surprise\ndata: {\"x\":1}\n\n"); + frame(out, "event: run-started\ndata: not-json\n\n"); + frame(out, "event: run-started\r\ndata: {\"running\":true,\"startedAt\":\"t1\"}\r\n\r\n"); + frame(out, "event: backups-changed\ndata: not-json\n\n"); + frame(out, "event: backups-changed\ndata: {\"at\":\"t3\"}\n\n"); + frame(out, "event: config-changed\ndata: {\"at\":\"t4\"}\n\n"); + frame(out, "event:run-finished\ndata:{\"running\":false,\"status\":\"PARTIAL\",\"startedAt\":\"t1\",\"finishedAt\":\"t2\"}\n\n"); + hold(); + }); + activate(fake.url()); + + startService(FAST); + + List seen = collectUntil("event:run-finished"); + List relevant = seen.stream().filter(event -> !nameOf(event).equals("versions") && !isLink(event, "DOWN")).toList(); + List names = relevant.stream().map(ServerEventStreamServiceTest::nameOf).toList(); + assertEquals(List.of("snapshot", "snapshot", "link", "state", "run-started", "backups-changed", "run-finished"), names); + assertTrue(dataOf(relevant.get(0)).path("activeServer").isNull()); + assertEquals(fake.url(), dataOf(relevant.get(1)).path("activeServer").asString()); + assertEquals("CONNECTING", dataOf(relevant.get(1)).path("link").asString()); + assertEquals("LIVE", dataOf(relevant.get(2)).path("state").asString()); + assertEquals(fake.url(), dataOf(relevant.get(2)).path("server").asString()); + assertEquals("t1", dataOf(relevant.get(4)).path("startedAt").asString()); + assertEquals("t3", dataOf(relevant.get(5)).path("at").asString()); + assertEquals("PARTIAL", dataOf(relevant.get(6)).path("status").asString()); + } + + @Test + void switchingBetweenTwoUnpairedKnownServersUpdatesTheDashboard() throws InterruptedException { + dashboard.start(); + state.updateKnownServers(List.of("http://unpaired-a:38471", "http://unpaired-b:38471")); + startService(FAST); + assertEquals("http://unpaired-a:38471", dashboard.state().activeServer()); + + state.setActiveServer("http://unpaired-b:38471"); + + assertEquals("http://unpaired-b:38471", dashboard.state().activeServer()); + String snapshot = browser.nextContaining("\"activeServer\":\"http://unpaired-b:38471\""); + assertEquals("snapshot", nameOf(snapshot)); + } + + @Test + void forwardsEventDataAsOneLineSoItCannotInjectFields() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + OutputStream out = open(exchange); + frame(out, "event: backups-changed\ndata: {\"at\":\ndata: \"t3\",\ndata: \"x\":\"y\"}\n\n"); + frame(out, "event:run-finished\ndata:{\"running\":false,\"status\":\"OK\"}\n\n"); + hold(); + }); + activate(fake.url()); + + startService(FAST); + + List seen = collectUntil("event:run-finished"); + String changed = seen.stream().filter(event -> nameOf(event).equals("backups-changed")).findFirst().orElseThrow(); + assertEquals(List.of("event:backups-changed", "data:{\"at\":\"t3\",\"x\":\"y\"}"), changed.lines().filter(line -> !line.isEmpty()).toList()); + } + + private static String nameOf(String event) { + return RecordingPublisher.eventName(event); + } + + private static JsonNode dataOf(String event) { + return RecordingPublisher.data(event); + } + + private static boolean isLink(String event, String state) { + return nameOf(event).equals("link") && state.equals(dataOf(event).path("state").asString()); + } + + private String awaitLink(String state) throws InterruptedException { + while (true) { + String event = browser.next(); + if (isLink(event, state)) { + return event; + } + } + } + + private static List streamThreads() { + return Thread.getAllStackTraces().keySet().stream() + .filter(thread -> thread.isAlive() && thread.getName().startsWith("server-event-stream-")) + .toList(); + } + + private static void hold() throws Exception { + new CountDownLatch(1).await(20, TimeUnit.SECONDS); + } + + @Test + void reconnectsRightAwayAfterACleanEndWithoutFlickeringTheLink() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":" + (connection == 1) + "}\n\n"); + if (connection > 1) { + hold(); + } + }); + activate(fake.url()); + + startService(FAST); + + fake.awaitConnection(); + fake.awaitConnection(); + List seen = collectUntil("\"running\":false"); + int connectedAt = -1; + for (int i = 0; i < seen.size(); i++) { + if (isLink(seen.get(i), "LIVE")) { + assertEquals(-1, connectedAt, "link reported connected twice"); + connectedAt = i; + } + } + assertTrue(connectedAt >= 0); + assertTrue(seen.subList(connectedAt, seen.size()).stream().noneMatch(event -> isLink(event, "DOWN"))); + } + + @Test + void retriesWithBackoffAfterAFailureAndReportsTheLinkDown() throws Exception { + CountDownLatch allowStream = new CountDownLatch(1); + FakeServer fake = fake((exchange, connection) -> { + if (connection < 3) { + exchange.sendResponseHeaders(500, -1); + return; + } + allowStream.await(10, TimeUnit.SECONDS); + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":true}\n\n"); + hold(); + }); + activate(fake.url()); + + startService(FAST); + + long first = fake.awaitConnection(); + long second = fake.awaitConnection(); + long third = fake.awaitConnection(); + awaitLink("DOWN"); + allowStream.countDown(); + List seen = collectUntil("event:state"); + assertEquals(3, fake.count.get()); + assertTrue(TimeUnit.NANOSECONDS.toMillis(second - first) >= 20, "first retry came before the initial backoff"); + assertTrue(TimeUnit.NANOSECONDS.toMillis(third - second) >= 40, "second retry came before the doubled backoff"); + assertTrue(seen.stream().anyMatch(event -> isLink(event, "LIVE"))); + } + + @Test + void rejectsAResponseThatIsNotAnEventStream() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + if (connection == 1) { + exchange.getResponseHeaders().add("Content-Type", "text/html"); + exchange.sendResponseHeaders(200, 0); + frame(exchange.getResponseBody(), "event: state\ndata: {\"running\":true}\n\n"); + return; + } + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":false}\n\n"); + hold(); + }); + activate(fake.url()); + + startService(FAST); + + List seen = collectUntil("event:state"); + assertFalse(dataOf(seen.get(seen.size() - 1)).path("running").asBoolean(true)); + assertEquals(2, fake.count.get()); + } + + @Test + void anOldServerWithoutTheStreamIsRetriedOnlyAfterTheLongInterval() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + if (connection == 1) { + exchange.sendResponseHeaders(404, -1); + return; + } + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":false}\n\n"); + hold(); + }); + activate(fake.url()); + + startService(FAST); + + long first = fake.awaitConnection(); + long second = fake.awaitConnection(); + assertTrue(TimeUnit.NANOSECONDS.toMillis(second - first) >= 350, "retried too early"); + collectUntil("event:state"); + } + + @Test + void movingToAnotherServerClosesTheOldStreamAndSubscribesToTheNewOne() throws Exception { + CountDownLatch oldClosed = new CountDownLatch(1); + FakeServer old = fake(holdOpen(oldClosed, "event: state\ndata: {\"running\":true}\n\n")); + FakeServer next = fake(holdOpen(new CountDownLatch(1), "event: state\ndata: {\"running\":false}\n\n")); + activate(old.url()); + startService(FAST); + collectUntil("\"running\":true"); + + activate(next.url()); + + assertTrue(oldClosed.await(10, TimeUnit.SECONDS), "the old stream was not closed"); + List seen = collectUntil("\"running\":false"); + assertTrue(seen.stream().anyMatch(event -> nameOf(event).equals("snapshot") + && next.url().equals(dataOf(event).path("activeServer").asString()) && dataOf(event).path("running").isNull())); + assertTrue(seen.stream().anyMatch(event -> isLink(event, "LIVE") && next.url().equals(dataOf(event).path("server").asString()))); + assertEquals(1, old.count.get()); + } + + @Test + void clearingTheActiveServerStopsTheStreamAndDoesNotReconnect() throws Exception { + CountDownLatch closed = new CountDownLatch(1); + FakeServer fake = fake(holdOpen(closed, "event: state\ndata: {\"running\":true}\n\n")); + activate(fake.url()); + startService(FAST); + collectUntil("\"running\":true"); + + state.setActiveServer(""); + + assertTrue(closed.await(10, TimeUnit.SECONDS)); + String cleared = browser.nextContaining("\"activeServer\":null"); + assertEquals("snapshot", nameOf(cleared)); + assertEquals("DOWN", dataOf(cleared).path("link").asString(), cleared); + assertEquals(1, fake.count.get()); + } + + @Test + void doesNotConnectWithoutAnActiveServer() throws Exception { + startService(FAST); + + String snapshot = browser.next(); + assertEquals("snapshot", nameOf(snapshot)); + assertEquals("DOWN", dataOf(snapshot).path("link").asString()); + assertTrue(streamThreads().isEmpty()); + assertNull(browser.sent.poll()); + } + + @Test + void reconnectsAStreamThatGoesSilent() throws Exception { + Timing quick = new Timing(Duration.ofSeconds(5), Duration.ofMillis(200), Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofMillis(400), Duration.ZERO); + FakeServer fake = fake((exchange, connection) -> { + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":" + (connection == 1) + "}\n\n"); + hold(); + }); + activate(fake.url()); + + startService(quick); + + fake.awaitConnection(); + fake.awaitConnection(); + List seen = collectUntil("\"running\":false"); + List linkStates = seen.stream().filter(event -> nameOf(event).equals("link")).map(event -> dataOf(event).path("state").asString()).toList(); + int firstLive = linkStates.indexOf("LIVE"); + assertTrue(firstLive >= 0, "the first connection never went live: " + linkStates); + List afterwards = linkStates.subList(firstLive + 1, linkStates.size()); + assertEquals("LIVE", afterwards.getLast(), "the link did not come back after the silence: " + linkStates); + assertTrue(afterwards.stream().anyMatch(state -> !state.equals("LIVE")), "the silent stream was never reported as lost: " + linkStates); + assertEquals(2, fake.count.get()); + } + + @Test + void startsOnItsOwnForAServerRestoredFromTheStateFile() throws Exception { + FakeServer fake = fake(holdOpen(new CountDownLatch(1), "event: state\ndata: {\"running\":true}\n\n")); + activate(fake.url()); + MediaGarrdProperties configuration = new MediaGarrdProperties(); + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(Duration.ofHours(12)); + state = new ClientStateService(configuration, MAPPER); + + startService(FAST); + + fake.awaitConnection(); + collectUntil("\"running\":true"); + } + + @Test + void aStreamThatEndsRightAfterOpeningIsRetriedWithBackoffInsteadOfInALoop() throws Exception { + Timing slowRetry = new Timing(Duration.ofSeconds(5), Duration.ofSeconds(30), Duration.ofMillis(300), Duration.ofMillis(300), Duration.ofMillis(400), Duration.ofMinutes(1)); + FakeServer fake = fake((exchange, connection) -> { + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":false}\n\n"); + }); + activate(fake.url()); + + startService(slowRetry); + + long first = fake.awaitConnection(); + long second = fake.awaitConnection(); + long third = fake.awaitConnection(); + assertTrue(TimeUnit.NANOSECONDS.toMillis(second - first) >= 250, "reconnected too fast"); + assertTrue(TimeUnit.NANOSECONDS.toMillis(third - second) >= 250, "reconnected too fast"); + } + + @Test + void severalConfigChangedEventsDuringARefreshAreCoalescedIntoOneMoreFetch() throws Exception { + AtomicInteger fetches = new AtomicInteger(); + CountDownLatch firstFetchStarted = new CountDownLatch(1); + CountDownLatch finishFetch = new CountDownLatch(1); + doAnswer(invocation -> { + fetches.incrementAndGet(); + firstFetchStarted.countDown(); + finishFetch.await(10, TimeUnit.SECONDS); + return new ServerStatusDto(true, false, 5, Duration.ofHours(6)); + }).when(serverApi).health(anyString()); + CountDownLatch burst = new CountDownLatch(1); + FakeServer fake = fake((exchange, connection) -> { + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":false}\n\n"); + burst.await(10, TimeUnit.SECONDS); + for (int i = 0; i < 3; i++) { + frame(out, "event: config-changed\ndata: {\"at\":\"t" + i + "\"}\n\n"); + } + frame(out, "event: state\ndata: {\"running\":true}\n\n"); + hold(); + }); + activate(fake.url()); + + startService(FAST); + + assertTrue(firstFetchStarted.await(10, TimeUnit.SECONDS)); + awaitLink("LIVE"); + burst.countDown(); + browser.nextContaining("\"running\":true"); + assertEquals(1, fetches.get(), "no fetch may start while the first one is still in flight"); + finishFetch.countDown(); + refreshes.submit(() -> { }).get(10, TimeUnit.SECONDS); + + assertEquals(2, fetches.get(), "the burst of config-changed events must cost exactly one more fetch"); + } + + @Test + void sendsTheBearerTokenWhenSubscribing() throws Exception { + FakeServer fake = fake(holdOpen(new CountDownLatch(1), "event: state\ndata: {\"running\":true}\n\n")); + activate(fake.url()); + + startService(FAST); + + fake.awaitConnection(); + assertEquals("Bearer test-token", fake.authorizations.getFirst()); + } + + @Test + void aRejectedTokenStopsTheStreamInsteadOfRetrying() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + exchange.sendResponseHeaders(401, -1); + }); + activate(fake.url()); + + startService(FAST); + + fake.awaitConnection(); + awaitRejected(); + assertEquals(1, fake.count.get()); + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.REJECTED, dashboard.state().pairing()); + } + + @Test + void pairingAgainRestartsTheStreamWithTheNewToken() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + if ("Bearer test-token".equals(exchange.getRequestHeaders().getFirst("Authorization"))) { + exchange.sendResponseHeaders(401, -1); + return; + } + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":true}\n\n"); + hold(); + }); + activate(fake.url()); + startService(FAST); + fake.awaitConnection(); + + state.storePairing(fake.url(), new StoredPairing("second-token", "id2", "Test")); + + fake.awaitConnection(); + collectUntil("\"running\":true"); + assertEquals("Bearer second-token", fake.authorizations.getLast()); + } + + @Test + void doesNotConnectToAServerThatIsNotPaired() throws Exception { + FakeServer fake = fake(holdOpen(new CountDownLatch(1))); + state.setActiveServer(fake.url()); + + startService(FAST); + + assertEquals("snapshot", nameOf(browser.next())); + assertTrue(streamThreads().isEmpty()); + assertEquals(0, fake.count.get()); + } + + @Test + void doesNotFollowARedirectWithTheToken() throws Exception { + FakeServer elsewhere = fake(holdOpen(new CountDownLatch(1))); + FakeServer fake = fake((exchange, connection) -> { + exchange.getResponseHeaders().add("Location", elsewhere.url() + "/api/v1/events"); + exchange.sendResponseHeaders(302, -1); + }); + activate(fake.url()); + + startService(FAST); + + fake.awaitConnection(); + fake.awaitConnection(); + assertEquals(0, elsewhere.count.get()); + } + + @Test + void recoveryRestartsARejectedStreamAgainOnceTheCoolDownHasPassed() throws Exception { + FakeServer fake = fake((exchange, connection) -> exchange.sendResponseHeaders(401, -1)); + activate(fake.url()); + AtomicLong nanos = new AtomicLong(1_000_000_000L); + CapturingScheduler scheduler = new CapturingScheduler(); + startService(new Timing(Duration.ofSeconds(5), Duration.ofSeconds(30), Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofMinutes(5), Duration.ZERO), nanos, scheduler); + fake.awaitConnection(); + awaitRejected(); + + service.recovered(fake.url()); + fake.awaitConnection(); + awaitRejected(); + nanos.addAndGet(Duration.ofMinutes(5).toNanos()); + service.recovered(fake.url()); + + fake.awaitConnection(); + assertEquals(3, fake.count.get()); + assertTrue(scheduler.commands.isEmpty(), "a recovery after the cool-down must restart at once, not be deferred"); + scheduler.shutdownNow(); + } + + static final class CapturingScheduler extends ScheduledThreadPoolExecutor { + + final List commands = new CopyOnWriteArrayList<>(); + final List delays = new CopyOnWriteArrayList<>(); + final List> futures = new CopyOnWriteArrayList<>(); + + CapturingScheduler() { + super(1, runnable -> { + Thread thread = new Thread(runnable); + thread.setDaemon(true); + return thread; + }); + } + + @Override + public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { + commands.add(command); + delays.add(unit.toNanos(delay)); + ScheduledFuture future = super.schedule(command, 1, TimeUnit.DAYS); + futures.add(future); + return future; + } + } + + private void startService(Timing timing, AtomicLong nanos, CapturingScheduler scheduler) { + service = new ServerEventStreamService(state, dashboard, MAPPER, ServerTls.defaults(), timing, nanos::get, scheduler); + browser = dashboard.subscribe(publisher::subscribe).orElseThrow(); + service.start(); + } + + @Test + void recoveryDuringTheCoolDownIsDeferredAndRestartsAStillRejectedStream() throws Exception { + FakeServer fake = fake((exchange, connection) -> exchange.sendResponseHeaders(401, -1)); + activate(fake.url()); + AtomicLong nanos = new AtomicLong(1_000_000_000L); + CapturingScheduler scheduler = new CapturingScheduler(); + startService(new Timing(Duration.ofSeconds(5), Duration.ofSeconds(30), Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofMinutes(5), Duration.ZERO), nanos, scheduler); + fake.awaitConnection(); + awaitRejected(); + + service.recovered(fake.url()); + fake.awaitConnection(); + awaitRejected(); + nanos.addAndGet(TimeUnit.SECONDS.toNanos(10)); + service.recovered(fake.url()); + service.recovered(fake.url()); + + assertEquals(2, fake.count.get()); + assertEquals(2, scheduler.commands.size()); + assertEquals(Duration.ofMinutes(5).minusSeconds(10).toNanos(), scheduler.delays.getLast()); + assertTrue(scheduler.futures.getFirst().isCancelled()); + + nanos.addAndGet(Duration.ofMinutes(5).toNanos()); + scheduler.commands.getLast().run(); + fake.awaitConnection(); + assertEquals(3, fake.count.get()); + scheduler.shutdownNow(); + } + + @Test + void aDeferredRecoveryIsCancelledAndIgnoredOnceTheStreamWasReplaced() throws Exception { + FakeServer fake = fake((exchange, connection) -> exchange.sendResponseHeaders(401, -1)); + activate(fake.url()); + AtomicLong nanos = new AtomicLong(1_000_000_000L); + CapturingScheduler scheduler = new CapturingScheduler(); + startService(new Timing(Duration.ofSeconds(5), Duration.ofSeconds(30), Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofMinutes(5), Duration.ZERO), nanos, scheduler); + fake.awaitConnection(); + awaitRejected(); + service.recovered(fake.url()); + fake.awaitConnection(); + awaitRejected(); + nanos.addAndGet(TimeUnit.SECONDS.toNanos(10)); + service.recovered(fake.url()); + assertEquals(1, scheduler.commands.size()); + + state.storePairing(fake.url(), new StoredPairing("new-token", "def", "Test")); + fake.awaitConnection(); + awaitRejected(); + + assertTrue(scheduler.futures.getFirst().isCancelled()); + nanos.addAndGet(Duration.ofMinutes(10).toNanos()); + scheduler.commands.getFirst().run(); + assertNull(fake.connections.poll(300, TimeUnit.MILLISECONDS)); + assertEquals(3, fake.count.get()); + scheduler.shutdownNow(); + } + + @Test + void deferredRecoveryDoesNothingOnceTheStreamIsNoLongerRejected() throws Exception { + FakeServer fake = fake((exchange, connection) -> exchange.sendResponseHeaders(401, -1)); + activate(fake.url()); + AtomicLong nanos = new AtomicLong(1_000_000_000L); + CapturingScheduler scheduler = new CapturingScheduler(); + startService(new Timing(Duration.ofSeconds(5), Duration.ofSeconds(30), Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofMinutes(5), Duration.ZERO), nanos, scheduler); + fake.awaitConnection(); + awaitRejected(); + service.recovered(fake.url()); + fake.awaitConnection(); + awaitRejected(); + service.recovered(fake.url()); + assertEquals(1, scheduler.commands.size()); + + state.setActiveServer(null); + + assertTrue(scheduler.futures.getFirst().isCancelled()); + nanos.addAndGet(Duration.ofMinutes(10).toNanos()); + scheduler.commands.getFirst().run(); + assertTrue(streamThreads().isEmpty()); + assertEquals(2, fake.count.get()); + scheduler.shutdownNow(); + } + + @Test + void recoveryDoesNotRestartAStreamThatWasNotRejected() throws Exception { + FakeServer fake = fake(holdOpen(new CountDownLatch(1))); + activate(fake.url()); + startService(FAST); + fake.awaitConnection(); + List before = streamThreads(); + assertEquals(1, before.size()); + + service.recovered(fake.url()); + + assertEquals(before, streamThreads(), "a restart would have replaced the stream thread"); + assertEquals(1, fake.count.get()); + } + + @Test + void recoveryOfAnotherServerDoesNotRestartARejectedStream() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + if (connection == 1) { + exchange.sendResponseHeaders(401, -1); + return; + } + holdOpen(new CountDownLatch(1)).handle(exchange, connection); + }); + activate(fake.url()); + startService(FAST); + fake.awaitConnection(); + awaitRejected(); + + service.recovered("http://127.0.0.1:1"); + + assertTrue(streamThreads().isEmpty(), "a restart would have started a stream that stays open"); + assertEquals(1, fake.count.get()); + } + + private void awaitRejected() throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (!streamThreads().isEmpty()) { + assertTrue(System.nanoTime() < deadline, "the rejected stream never ended"); + Thread.sleep(10); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerPayloadGoldenTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerPayloadGoldenTest.java new file mode 100644 index 0000000..a35bda6 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerPayloadGoldenTest.java @@ -0,0 +1,174 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.web.client.RestClientResponseException; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.PairingCodeDto; +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; +import wellatleastitried.mediagarrdclient.golden.Fixtures; + +class ServerPayloadGoldenTest { + + private final ServerApiService service = new ServerApiService(Duration.ofHours(6), url -> Optional.of("secret-token"), ServerTls.defaults()); + private HttpServer server; + private String serverUrl; + private volatile int status = 200; + private volatile String response = "{}"; + + @BeforeEach + void startServer() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", this::handle); + server.start(); + serverUrl = "http://127.0.0.1:" + server.getAddress().getPort(); + } + + @AfterEach + void stopServer() { + server.stop(0); + } + + @Test + void readsThePublicHealthPayloadWithFieldsTheServerDoesNotSend() { + response = Fixtures.read("server/health-public.json"); + + ServerStatusDto health = service.health(serverUrl); + + assertEquals(new ServerStatusDto(true, false, 0, Duration.ofHours(6)), health); + } + + @Test + void readsTheAuthenticatedHealthPayload() { + response = Fixtures.read("server/health-status.json"); + + ServerStatusDto health = service.health(serverUrl); + + assertEquals(new ServerStatusDto(true, false, 7, Duration.ofHours(12)), health); + } + + @Test + void readsTheVersionPayload() { + response = Fixtures.read("server/version.json"); + + VersionStatusDto version = service.serverVersion(serverUrl); + + assertEquals(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-20T10:15:30.123456Z"), null), version); + } + + @Test + void readsTheBackupList() { + response = Fixtures.read("server/backups.json"); + + List backups = service.listBackups(serverUrl); + + assertEquals(List.of( + new BackupDto("backup-2026-11-20", "mediagarrd-2026-11-20.zip", 1048576L, Instant.parse("2026-11-20T10:15:30.123456Z")), + new BackupDto("backup-2026-11-19", "mediagarrd-2026-11-19.zip", 2097152L, Instant.parse("2026-11-19T04:00:00Z"))), backups); + } + + @Test + void readsTheConfigPayload() { + response = Fixtures.read("server/config.json"); + + ServerConfigDto config = service.serverConfig(serverUrl); + + assertEquals(new ServerConfigDto("/var/backups/mediagarrd", 7, Duration.ofHours(6)), config); + } + + @Test + void readsTheServiceList() { + response = Fixtures.read("server/services.json"); + + List services = service.listServices(serverUrl); + + assertEquals(List.of( + new ServiceDto("jellyfin", List.of("/srv/jellyfin/config", "/srv/jellyfin/data")), + new ServiceDto("radarr", List.of("/srv/radarr"))), services); + } + + @Test + void readsThePairResponse() { + response = Fixtures.read("server/pair-response.json"); + + StoredPairing pairing = service.pair(serverUrl, "123456", "Golden Laptop"); + + assertEquals("golden-token", pairing.token()); + assertEquals("c0ffee00-0000-4000-8000-000000000003", pairing.id()); + assertEquals("Golden Laptop", pairing.name()); + } + + @Test + void readsThePairingCode() { + response = Fixtures.read("server/pairing-code.json"); + + PairingCodeDto code = service.createPairingCode(serverUrl); + + assertEquals(new PairingCodeDto("482913", Instant.parse("2026-11-20T10:25:30.500Z")), code); + } + + @Test + void readsTheErrorMessageFromTheServerErrorShape() { + status = 401; + response = Fixtures.read("server/error-4xx.json"); + + var e = assertThrows(InvalidRequestException.class, () -> service.pair(serverUrl, "000000", null)); + + assertEquals("The PIN is not valid", e.getMessage()); + } + + @Test + void readsTheErrorMessageFromSpringsDefaultErrorBody() { + status = 401; + response = Fixtures.read("server/error-spring-default.json"); + + var e = assertThrows(InvalidRequestException.class, () -> service.pair(serverUrl, "000000", null)); + + assertEquals("Unauthorized", e.getMessage()); + } + + @Test + void exposesTheServerErrorBodyOfAnUnexpectedStatus() { + status = 409; + response = Fixtures.read("server/error-4xx.json"); + + RestClientResponseException e = assertThrows(RestClientResponseException.class, () -> service.createPairingCode(serverUrl)); + + assertEquals(409, e.getStatusCode().value()); + assertTrue(e.getResponseBodyAsString().contains("The PIN is not valid")); + } + + private void handle(HttpExchange exchange) throws IOException { + exchange.getRequestBody().readAllBytes(); + byte[] bytes = response.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + exchange.close(); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerTlsTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerTlsTest.java new file mode 100644 index 0000000..06ab3be --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerTlsTest.java @@ -0,0 +1,202 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.time.Duration; +import java.util.Optional; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; + +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.client.ResourceAccessException; + +import tools.jackson.databind.json.JsonMapper; +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsServer; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; + +class ServerTlsTest { + + private static final char[] PASSWORD = "changeit".toCharArray(); + private static final String HEALTH = "{\"healthy\": true, \"backupInterval\": \"PT1H\"}"; + + @TempDir + Path tempDir; + + private HttpsServer server; + private Path certificate; + private String authorization; + + private void run(String... command) throws IOException, InterruptedException { + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + if (process.waitFor() != 0) { + throw new IOException(String.join(" ", command) + " failed: " + output); + } + } + + @BeforeEach + void startHttpsServer() throws Exception { + Path keystore = tempDir.resolve("server.p12"); + certificate = tempDir.resolve("ca.pem"); + String keytool = Path.of(System.getProperty("java.home"), "bin", "keytool").toString(); + run(keytool, "-genkeypair", "-alias", "server", "-keyalg", "RSA", "-keysize", "2048", "-validity", "2", "-dname", "CN=MediaGarrd Test CA", + "-ext", "san=ip:127.0.0.1", "-ext", "bc:c", "-keystore", keystore.toString(), "-storetype", "PKCS12", "-storepass", new String(PASSWORD)); + run(keytool, "-exportcert", "-rfc", "-alias", "server", "-keystore", keystore.toString(), "-storepass", new String(PASSWORD), "-file", certificate.toString()); + + KeyStore store = KeyStore.getInstance("PKCS12"); + try (InputStream in = Files.newInputStream(keystore)) { + store.load(in, PASSWORD); + } + KeyManagerFactory keys = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keys.init(store, PASSWORD); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(keys.getKeyManagers(), null, null); + server = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.setHttpsConfigurator(new HttpsConfigurator(context)); + server.createContext("/", exchange -> { + authorization = exchange.getRequestHeaders().getFirst("Authorization"); + byte[] body = HEALTH.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, body.length); + exchange.getResponseBody().write(body); + exchange.close(); + }); + server.start(); + } + + @AfterEach + void stopHttpsServer() { + server.stop(0); + } + + private String url() { + return "https://127.0.0.1:" + server.getAddress().getPort(); + } + + private ServerApiService api(ServerTls tls) { + return new ServerApiService(Duration.ofHours(1), serverUrl -> Optional.of("tok"), tls); + } + + @Test + void aSelfSignedServerIsRefusedWithoutTheCa() { + assertThrows(ResourceAccessException.class, () -> api(ServerTls.defaults()).health(url())); + } + + @Test + void theConfiguredCaMakesTheServerTrustedAndTheTokenTravelsOverTls() { + ServerApiService api = api(new ServerTls(certificate.toString())); + + assertTrue(api.health(url()).healthy()); + assertEquals("Bearer tok", authorization); + } + + @Test + void hostnameVerificationStaysOnEvenWithTheCa() { + String byName = "https://localhost:" + server.getAddress().getPort(); + + ResourceAccessException e = assertThrows(ResourceAccessException.class, () -> api(new ServerTls(certificate.toString())).health(byName)); + + StringBuilder chain = new StringBuilder(); + for (Throwable cause = e; cause != null; cause = cause.getCause()) { + chain.append(cause.getClass().getSimpleName()).append(": ").append(cause.getMessage()).append('\n'); + } + assertTrue(chain.toString().contains("SSLHandshakeException"), chain.toString()); + assertTrue(api(new ServerTls(certificate.toString())).health(url()).healthy()); + } + + @Test + void anUnrelatedCaDoesNotTrustTheServer() throws Exception { + Path other = tempDir.resolve("other.p12"); + Path otherPem = tempDir.resolve("other.pem"); + String keytool = Path.of(System.getProperty("java.home"), "bin", "keytool").toString(); + run(keytool, "-genkeypair", "-alias", "o", "-keyalg", "RSA", "-keysize", "2048", "-dname", "CN=Other", "-keystore", other.toString(), "-storetype", "PKCS12", "-storepass", new String(PASSWORD)); + run(keytool, "-exportcert", "-rfc", "-alias", "o", "-keystore", other.toString(), "-storepass", new String(PASSWORD), "-file", otherPem.toString()); + + assertThrows(ResourceAccessException.class, () -> api(new ServerTls(otherPem.toString())).health(url())); + } + + @Test + void theDefaultTrustStillWorksWhenAnUnrelatedCaIsConfigured() throws Exception { + Path otherPem = tempDir.resolve("other.pem"); + Path other = tempDir.resolve("other.p12"); + Path systemTrust = tempDir.resolve("system-trust.p12"); + String keytool = Path.of(System.getProperty("java.home"), "bin", "keytool").toString(); + run(keytool, "-genkeypair", "-alias", "o", "-keyalg", "RSA", "-keysize", "2048", "-dname", "CN=Other", "-keystore", other.toString(), "-storetype", "PKCS12", "-storepass", new String(PASSWORD)); + run(keytool, "-exportcert", "-rfc", "-alias", "o", "-keystore", other.toString(), "-storepass", new String(PASSWORD), "-file", otherPem.toString()); + run(keytool, "-importcert", "-noprompt", "-alias", "system-ca", "-file", certificate.toString(), "-keystore", systemTrust.toString(), "-storetype", "PKCS12", "-storepass", new String(PASSWORD)); + assertThrows(ResourceAccessException.class, () -> api(new ServerTls(otherPem.toString())).health(url())); + + String path = System.getProperty("javax.net.ssl.trustStore"); + String type = System.getProperty("javax.net.ssl.trustStoreType"); + String password = System.getProperty("javax.net.ssl.trustStorePassword"); + System.setProperty("javax.net.ssl.trustStore", systemTrust.toString()); + System.setProperty("javax.net.ssl.trustStoreType", "PKCS12"); + System.setProperty("javax.net.ssl.trustStorePassword", new String(PASSWORD)); + try { + assertTrue(api(new ServerTls(otherPem.toString())).health(url()).healthy()); + } finally { + restore("javax.net.ssl.trustStore", path); + restore("javax.net.ssl.trustStoreType", type); + restore("javax.net.ssl.trustStorePassword", password); + } + } + + private static void restore(String key, String value) { + if (value == null) { + System.clearProperty(key); + } else { + System.setProperty(key, value); + } + } + + @Test + void discoveryProbesAnHttpsAddressWithTheSharedTrust() { + MediaGarrdProperties configuration = new MediaGarrdProperties(); + configuration.setStateFile(tempDir.resolve("state.json").toString()); + ServerDiscoveryService discovery = new ServerDiscoveryService(configuration, mock(ClientStateService.class), JsonMapper.builder().build(), new ServerTls(certificate.toString())); + + Optional found = discovery.resolveServerByIp(url(), null); + + assertEquals(Optional.of(url()), found); + } + + @Test + void discoveryDoesNotTrustAnUnknownCertificate() { + MediaGarrdProperties configuration = new MediaGarrdProperties(); + ServerDiscoveryService discovery = new ServerDiscoveryService(configuration, mock(ClientStateService.class), JsonMapper.builder().build(), ServerTls.defaults()); + + assertTrue(discovery.resolveServerByIp(url(), null).isEmpty()); + } + + @Test + void anUnreadableCaFileIsAClearStartupError() { + IllegalStateException missing = assertThrows(IllegalStateException.class, () -> new ServerTls(tempDir.resolve("nope.pem").toString())); + Path junk = tempDir.resolve("junk.pem"); + try { + Files.writeString(junk, "not a certificate"); + } catch (IOException e) { + throw new IllegalStateException(e); + } + IllegalStateException invalid = assertThrows(IllegalStateException.class, () -> new ServerTls(junk.toString())); + + assertTrue(missing.getMessage().contains("MEDIAGARRD_SERVER_CA"), missing.getMessage()); + assertTrue(invalid.getMessage().contains("MEDIAGARRD_SERVER_CA"), invalid.getMessage()); + } + +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerUrlsTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerUrlsTest.java new file mode 100644 index 0000000..7d2981b --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerUrlsTest.java @@ -0,0 +1,34 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class ServerUrlsTest { + + @ParameterizedTest + @CsvSource({ + "http://server:38471, http://server:38471", + "HTTP://Server:38471/, http://server:38471", + "http://server:80, http://server", + "https://Garrd.Example.com:443/, https://garrd.example.com", + "https://garrd.example.com:8443, https://garrd.example.com:8443", + "https://garrd.example.com///, https://garrd.example.com", + "https://example.com/garrd/, https://example.com/garrd", + "http://[::1]:8080, http://[::1]:8080", + "http://user:pw@server:8080, http://server:8080" + }) + void normalizesUrls(String input, String expected) { + assertEquals(expected, ServerUrls.normalize(input)); + } + + @Test + void leavesNonUrlsAloneInsteadOfFailing() { + assertEquals("not a url", ServerUrls.normalize(" not a url/ ")); + assertEquals("", ServerUrls.normalize(" ")); + assertNull(ServerUrls.normalize(null)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServiceNamesTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServiceNamesTest.java new file mode 100644 index 0000000..770400f --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServiceNamesTest.java @@ -0,0 +1,23 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class ServiceNamesTest { + + @Test + void acceptsTheNamesTheServerAccepts() { + assertEquals("radarr", ServiceNames.require("radarr")); + assertEquals("Sonarr_4k.v2-x", ServiceNames.require("Sonarr_4k.v2-x")); + assertEquals("a".repeat(64), ServiceNames.require("a".repeat(64))); + } + + @Test + void refusesNamesThatCouldChangeThePath() { + for (String name : new String[] {null, "", ".", "..", ".hidden", "a/b", "a\\b", "a b", "%2e%2e", "a".repeat(65), "x?y", "x#y"}) { + assertThrows(InvalidRequestException.class, () -> ServiceNames.require(name), String.valueOf(name)); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/SessionServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/SessionServiceTest.java new file mode 100644 index 0000000..64ad14f --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/SessionServiceTest.java @@ -0,0 +1,104 @@ +package wellatleastitried.mediagarrdclient.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.assertTrue; + +import java.time.Duration; +import java.time.Instant; + +import org.junit.jupiter.api.Test; + +class SessionServiceTest { + + private final MutableClock clock = new MutableClock(Instant.parse("2026-11-19T12:00:00Z")); + private final SessionService sessions = new SessionService(clock, Duration.ofHours(1), Duration.ofHours(5), 3); + + @Test + void tellsListenersWhichSessionEndedOnLogoutClearAndExpiry() { + java.util.List ended = new java.util.ArrayList<>(); + sessions.addEndedListener(ended::add); + String first = sessions.create(); + String second = sessions.create(); + String third = sessions.create(); + + sessions.invalidate(first); + assertEquals(java.util.List.of(SessionService.keyOf(first)), ended); + assertFalse(sessions.validate(first)); + assertTrue(sessions.validate(third)); + sessions.invalidate(first); + assertEquals(1, ended.size()); + + clock.advance(Duration.ofHours(2)); + assertFalse(sessions.validate(second)); + assertEquals(SessionService.keyOf(second), ended.get(1)); + + sessions.clear(); + assertEquals(java.util.List.of(SessionService.keyOf(first), SessionService.keyOf(second), SessionService.keyOf(third)), ended); + assertFalse(sessions.validate(third)); + } + + @Test + void reportsWhetherASessionIsStillActiveWithoutExtendingIt() { + String token = sessions.create(); + String key = SessionService.keyOf(token); + + clock.advance(Duration.ofMinutes(59)); + assertTrue(sessions.isActive(key)); + clock.advance(Duration.ofMinutes(2)); + + assertFalse(sessions.isActive(key)); + assertFalse(sessions.isActive(null)); + assertFalse(sessions.isActive("unknown")); + } + + @Test + void acceptsOnlySessionsItCreated() { + String token = sessions.create(); + + assertTrue(sessions.validate(token)); + assertFalse(sessions.validate(token + "x")); + assertFalse(sessions.validate("")); + assertFalse(sessions.validate(null)); + assertEquals(43, token.length()); + } + + @Test + void sessionsExpireAfterBeingIdle() { + String token = sessions.create(); + + clock.advance(Duration.ofMinutes(59)); + assertTrue(sessions.validate(token)); + clock.advance(Duration.ofMinutes(59)); + assertTrue(sessions.validate(token)); + clock.advance(Duration.ofMinutes(61)); + assertFalse(sessions.validate(token)); + } + + @Test + void sessionsExpireAfterTheAbsoluteLimitEvenWhenActive() { + String token = sessions.create(); + + for (int i = 0; i < 5; i++) { + clock.advance(Duration.ofMinutes(59)); + assertTrue(sessions.validate(token)); + } + clock.advance(Duration.ofMinutes(59)); + assertFalse(sessions.validate(token)); + } + + @Test + void keepsAtMostTheConfiguredNumberOfSessionsDroppingTheOldest() { + String a = sessions.create(); + String b = sessions.create(); + String c = sessions.create(); + String d = sessions.create(); + + assertFalse(sessions.validate(a)); + assertTrue(sessions.validate(b)); + assertTrue(sessions.validate(c)); + assertTrue(sessions.validate(d)); + assertNotEquals(b, c); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/SseReaderTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/SseReaderTest.java new file mode 100644 index 0000000..7a781fa --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/SseReaderTest.java @@ -0,0 +1,97 @@ +package wellatleastitried.mediagarrdclient.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 java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.Test; + +class SseReaderTest { + + private static List read(String stream, AtomicInteger lines) throws IOException { + List events = new ArrayList<>(); + SseReader.read(new ByteArrayInputStream(stream.getBytes(StandardCharsets.UTF_8)), lines::incrementAndGet, (name, data) -> events.add(name + "=" + data)); + return events; + } + + @Test + void reportsWhetherAnyEventWasDispatched() throws IOException { + SseReader.Handler ignore = (name, data) -> { + }; + + assertTrue(SseReader.read(new ByteArrayInputStream("data: a\n\n".getBytes(StandardCharsets.UTF_8)), () -> { + }, ignore)); + assertFalse(SseReader.read(new ByteArrayInputStream(": ping\n\ndata: unfinished".getBytes(StandardCharsets.UTF_8)), () -> { + }, ignore)); + } + + @Test + void parsesNamedAndUnnamedEventsAndMultiLineData() throws IOException { + List events = read("event: state\ndata: {\"running\":true}\n\ndata: a\ndata: b\n\n", new AtomicInteger()); + + assertEquals(List.of("state={\"running\":true}", "message=a\nb"), events); + } + + @Test + void ignoresCommentsUnknownFieldsAndEventsWithoutData() throws IOException { + List events = read(": ping\nretry: 5000\nevent: lonely\n\nevent: state\ndata:x\n\n", new AtomicInteger()); + + assertEquals(List.of("state=x"), events); + } + + @Test + void dropsAnEventThatIsNotTerminatedByABlankLine() throws IOException { + assertEquals(List.of(), read("event: state\ndata: 1\n", new AtomicInteger())); + } + + @Test + void refusesALineLongerThanTheCap() { + assertThrows(IOException.class, () -> SseReader.read(new ByteArrayInputStream(("data: " + "x".repeat(100) + "\n\n").getBytes(StandardCharsets.UTF_8)), + () -> { }, (name, data) -> { }, 50, 1000)); + } + + @Test + void refusesAnEventLargerThanTheCapEvenWhenEveryLineIsSmall() { + String stream = "data: " + "x".repeat(30) + "\ndata: " + "y".repeat(30) + "\n\n"; + + assertThrows(IOException.class, () -> SseReader.read(new ByteArrayInputStream(stream.getBytes(StandardCharsets.UTF_8)), + () -> { }, (name, data) -> { }, 50, 40)); + } + + @Test + void acceptsLinesAndEventsWithinTheCapsAndAllLineEndings() throws IOException { + List events = new ArrayList<>(); + + SseReader.read(new ByteArrayInputStream("event: a\r\ndata: 1\r\r\ndata: 2\n\n".getBytes(StandardCharsets.UTF_8)), + () -> { }, (name, data) -> events.add(name + "=" + data), 50, 50); + + assertEquals(List.of("a=1", "message=2"), events); + } + + @Test + void aLargeLegitimateEventPassesTheDefaultCaps() throws IOException { + List events = new ArrayList<>(); + + SseReader.read(new ByteArrayInputStream(("event: backups-changed\ndata: " + "x".repeat(200_000) + "\n\n").getBytes(StandardCharsets.UTF_8)), + () -> { }, (name, data) -> events.add(name)); + + assertEquals(List.of("backups-changed"), events); + } + + @Test + void reportsActivityForEveryLine() throws IOException { + AtomicInteger lines = new AtomicInteger(); + + read(": a\nevent: x\ndata: 1\n\n", lines); + + assertEquals(4, lines.get()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/StateFileMissingFieldsGoldenTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/StateFileMissingFieldsGoldenTest.java new file mode 100644 index 0000000..971a4fa --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/StateFileMissingFieldsGoldenTest.java @@ -0,0 +1,80 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Optional; + +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.context.SpringBootTest; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +import wellatleastitried.mediagarrdclient.golden.Fixtures; + +class StateFileMissingFieldsGoldenTest { + + static void register(DynamicPropertyRegistry registry, Path dataDir, String fixture) throws IOException { + Files.writeString(dataDir.resolve("state.json"), Fixtures.read(fixture), StandardCharsets.UTF_8); + registry.add("mediagarrd.client.state-file", () -> dataDir.resolve("state.json").toString()); + registry.add("mediagarrd.client.download-directory", () -> dataDir.resolve("downloads").toString()); + registry.add("mediagarrd.client.preferred-server-ip", () -> ""); + registry.add("mediagarrd.client.github-api-base-url", () -> "http://127.0.0.1:1"); + registry.add("mediagarrd.client.password", () -> ""); + } + + static void assertPairingLoaded(ClientStateService state) { + assertEquals("http://192.168.1.20:38471", state.getActiveServer()); + assertEquals(Duration.ofHours(12), state.getPickupInterval()); + assertNull(state.getLastPickupAt()); + assertEquals(Optional.of(new StoredPairing("golden-token-one", "c0ffee00-0000-4000-8000-000000000001", "Golden Laptop")), + state.pairingFor("http://192.168.1.20:38471")); + } + + @SpringBootTest + static class MissingInterval { + + @TempDir + static Path dataDir; + + @Autowired + ClientStateService state; + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) throws IOException { + register(registry, dataDir, "disk/state-no-interval.json"); + } + + @Test + void stateWithoutPickupIntervalStillLoadsItsPairings() { + assertPairingLoaded(state); + } + } + + @SpringBootTest + static class NullInterval { + + @TempDir + static Path dataDir; + + @Autowired + ClientStateService state; + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) throws IOException { + register(registry, dataDir, "disk/state-null-interval.json"); + } + + @Test + void stateWithNullPickupIntervalStillLoadsItsPairings() { + assertPairingLoaded(state); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/StateFilesGoldenTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/StateFilesGoldenTest.java new file mode 100644 index 0000000..fbf1e9b --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/StateFilesGoldenTest.java @@ -0,0 +1,91 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +import wellatleastitried.mediagarrdclient.golden.Fixtures; + +@SpringBootTest +class StateFilesGoldenTest { + + @TempDir + static Path dataDir; + + @Autowired + ClientStateService state; + + @Autowired + PasswordService passwords; + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) throws IOException { + Files.writeString(dataDir.resolve("state.json"), Fixtures.read("disk/state.json"), StandardCharsets.UTF_8); + Files.writeString(dataDir.resolve("password.json"), Fixtures.read("disk/password.json"), StandardCharsets.UTF_8); + registry.add("mediagarrd.client.state-file", () -> dataDir.resolve("state.json").toString()); + registry.add("mediagarrd.client.download-directory", () -> dataDir.resolve("downloads").toString()); + registry.add("mediagarrd.client.preferred-server-ip", () -> ""); + registry.add("mediagarrd.client.github-api-base-url", () -> "http://127.0.0.1:1"); + registry.add("mediagarrd.client.password", () -> ""); + } + + @Test + void stateWrittenInTodaysFormatStillLoadsWithItsPairings() { + assertEquals("http://192.168.1.20:38471", state.getActiveServer()); + assertEquals(Duration.ofSeconds(5400), state.getPickupInterval()); + assertEquals(Instant.parse("2026-11-20T03:15:00Z"), state.getLastPickupAt()); + assertEquals(List.of("http://192.168.1.20:38471", "https://backup.example.net:38471"), state.getKnownServers()); + assertEquals(Optional.of("golden-token-one"), state.tokenFor("http://192.168.1.20:38471")); + assertEquals(Optional.of(new StoredPairing("golden-token-one", "c0ffee00-0000-4000-8000-000000000001", "Golden Laptop")), + state.pairingFor("http://192.168.1.20:38471")); + assertEquals(Optional.of(new StoredPairing("golden-token-two", "c0ffee00-0000-4000-8000-000000000002", null)), + state.pairingFor("https://backup.example.net:38471")); + } + + @Test + void savingWritesTheSameShapeAsToday() throws Exception { + state.setPickupInterval(Duration.ofSeconds(5400)); + + String written = Files.readString(dataDir.resolve("state.json")); + JSONAssert.assertEquals(Fixtures.read("disk/state.json"), written, JSONCompareMode.STRICT); + assertEquals(keys(Fixtures.read("disk/state.json")), keys(written)); + } + + private static List keys(String json) { + List keys = new ArrayList<>(); + Matcher matcher = Pattern.compile("\"([^\"]+)\"\\s*:").matcher(json); + while (matcher.find()) { + keys.add(matcher.group(1)); + } + return keys; + } + + @Test + void aStoredPasswordStillLoadsAndVerifies() { + assertTrue(passwords.isConfigured()); + assertFalse(passwords.isFromEnvironment()); + assertTrue(passwords.matches("golden password")); + assertFalse(passwords.matches("another password")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/UpdateCheckServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/UpdateCheckServiceTest.java new file mode 100644 index 0000000..af76343 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/UpdateCheckServiceTest.java @@ -0,0 +1,306 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; + +class UpdateCheckServiceTest { + + private static final Instant NOW = Instant.parse("2026-11-11T18:00:00Z"); + + private final List requests = new ArrayList<>(); + private final List userAgents = new ArrayList<>(); + private final MediaGarrdProperties properties = new MediaGarrdProperties(); + private HttpServer server; + private int status = 200; + private String rateLimitRemaining; + private String response = ""; + + @BeforeEach + void startServer() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", this::handle); + server.start(); + properties.setGithubApiBaseUrl("http://127.0.0.1:" + server.getAddress().getPort() + "/"); + properties.setUpdateRepository("MediaGarrd/Client"); + } + + @AfterEach + void stopServer() { + server.stop(0); + } + + private UpdateCheckService service(String currentVersion) { + return new UpdateCheckService(properties, currentVersion, Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private static String release(String tag) { + return "{\"tag_name\": \"" + tag + "\", \"html_url\": \"https://github.com/MediaGarrd/Client/releases/tag/" + tag + + "\", \"draft\": false, \"prerelease\": false, \"id\": 1}"; + } + + @Test + void reportsNotCheckedBeforeTheFirstRun() { + VersionStatusDto result = service("0.1.0").status(); + + assertEquals(new VersionStatusDto("0.1.0", null, null, false, CheckState.NOT_CHECKED, null, null), result); + assertTrue(requests.isEmpty()); + } + + @Test + void tellsListenersOnlyWhenTheStatusChanges() { + response = release("v0.2.0"); + UpdateCheckService service = service("0.1.0"); + List seen = new ArrayList<>(); + service.addStatusListener(seen::add); + + service.check(); + service.check(); + + assertEquals(1, seen.size()); + assertEquals(CheckState.OK, seen.get(0).checkState()); + assertTrue(seen.get(0).updateAvailable()); + + response = release("v0.3.0"); + service.check(); + + assertEquals(2, seen.size()); + assertEquals("0.3.0", seen.get(1).latestVersion()); + } + + @Test + void aFailingListenerDoesNotBreakTheCheckOrTheOthers() { + response = release("v0.2.0"); + UpdateCheckService service = service("0.1.0"); + List seen = new ArrayList<>(); + service.addStatusListener(ignored -> { + throw new IllegalStateException("boom"); + }); + service.addStatusListener(seen::add); + + service.check(); + + assertEquals(1, seen.size()); + assertEquals(CheckState.OK, service.status().checkState()); + } + + @Test + void reportsAnUpdateWhenTheLatestReleaseIsNewer() { + response = release("v0.2.0"); + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(new VersionStatusDto("0.1.0", "0.2.0", "https://github.com/MediaGarrd/Client/releases/tag/v0.2.0", true, CheckState.OK, NOW, null), service.status()); + assertEquals(List.of("/repos/MediaGarrd/Client/releases/latest"), requests); + assertEquals(List.of("MediaGarrd-Client/0.1.0"), userAgents); + } + + @ParameterizedTest + @CsvSource({"0.1.0,v0.1.0,0.1.0", "0.2.0,v0.1.0,0.1.0", "0.2.0,v0.2.0-rc.1,0.2.0-rc.1"}) + void reportsUpToDateWhenTheLatestReleaseIsTheSameOrOlder(String current, String tag, String latest) { + response = release(tag); + UpdateCheckService service = service(current); + + service.check(); + + assertEquals(CheckState.OK, service.status().checkState()); + assertEquals(latest, service.status().latestVersion()); + assertFalse(service.status().updateAvailable()); + } + + @Test + void reportsNoReleasesOnNotFound() { + status = 404; + response = "{\"message\": \"Not Found\"}"; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(new VersionStatusDto("0.1.0", null, null, false, CheckState.NO_RELEASES, NOW, null), service.status()); + } + + @Test + void reportsRateLimitingAsAnError() { + status = 403; + rateLimitRemaining = "0"; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("GitHub rate limit reached", service.status().message()); + assertFalse(service.status().updateAvailable()); + + status = 429; + rateLimitRemaining = null; + service.check(); + assertEquals("GitHub rate limit reached", service.status().message()); + } + + @Test + void reportsAForbiddenResponseWithoutAnExhaustedLimitAsAPlainHttpError() { + status = 403; + UpdateCheckService service = service("0.1.0"); + + service.check(); + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("GitHub returned HTTP 403", service.status().message()); + + rateLimitRemaining = "12"; + service.check(); + assertEquals("GitHub returned HTTP 403", service.status().message()); + } + + @Test + void rejectsCheckIntervalsBelowOneHour() { + properties.setUpdateCheckInterval(Duration.ofMinutes(59)); + + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> service("0.1.0")); + assertTrue(failure.getMessage().contains("at least PT1H")); + + properties.setUpdateCheckInterval(Duration.ZERO); + assertThrows(IllegalStateException.class, () -> service("0.1.0")); + + properties.setUpdateCheckInterval(Duration.ofHours(1)); + service("0.1.0"); + } + + @Test + void reportsServerErrorsAsAnError() { + status = 500; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("GitHub returned HTTP 500", service.status().message()); + assertEquals(NOW, service.status().checkedAt()); + } + + @Test + void reportsAnUnreachableGithubAsAnErrorWithoutThrowing() { + server.stop(0); + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("GitHub is unreachable", service.status().message()); + } + + @Test + void reportsMalformedResponsesAsAnError() { + response = "not json"; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertFalse(service.status().updateAvailable()); + } + + @Test + void reportsAnUnrecognizedTagAsAnError() { + response = release("nightly"); + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("Latest release has an unrecognized version tag", service.status().message()); + } + + @Test + void reportsAnErrorWithoutCallingGithubWhenTheCurrentVersionIsUnknown() { + response = release("v9.9.9"); + + for (String unknown : new String[] {null, "unspecified"}) { + UpdateCheckService service = service(unknown); + service.check(); + assertEquals(CheckState.ERROR, service.status().checkState()); + assertFalse(service.status().updateAvailable()); + assertEquals("Current version is unknown", service.status().message()); + } + assertTrue(requests.isEmpty()); + } + + @ParameterizedTest + @ValueSource(strings = {", \"html_url\": \"javascript:alert(1)\"", ", \"html_url\": \"https://github.com.evil.example/x\"", ""}) + void replacesAReleaseUrlThatIsNotOnGithub(String htmlUrl) { + response = "{\"tag_name\": \"v0.3.0\"" + htmlUrl + "}"; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals("https://github.com/MediaGarrd/Client/releases/tag/v0.3.0", service.status().releaseUrl()); + } + + @Test + void recoversOnTheNextCheckAfterAFailure() { + status = 500; + UpdateCheckService service = service("0.1.0"); + service.check(); + assertEquals(CheckState.ERROR, service.status().checkState()); + + status = 200; + response = release("v0.2.0"); + service.check(); + + assertEquals(CheckState.OK, service.status().checkState()); + assertTrue(service.status().updateAvailable()); + assertNull(service.status().message()); + } + + @Test + void usesTheConfiguredRepository() { + properties.setUpdateRepository("someone/else"); + response = release("v0.2.0"); + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(List.of("/repos/someone/else/releases/latest"), requests); + } + + private void handle(HttpExchange exchange) throws IOException { + requests.add(exchange.getRequestURI().getPath()); + userAgents.add(exchange.getRequestHeaders().getFirst("User-Agent")); + byte[] body = response.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + if (rateLimitRemaining != null) { + exchange.getResponseHeaders().add("X-RateLimit-Remaining", rateLimitRemaining); + } + exchange.sendResponseHeaders(status, body.length == 0 ? -1 : body.length); + if (body.length > 0) { + exchange.getResponseBody().write(body); + } + exchange.close(); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java new file mode 100644 index 0000000..85f64e2 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java @@ -0,0 +1,217 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Duration; +import java.time.Instant; + +import org.junit.jupiter.api.Test; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClientResponseException; + +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; +import wellatleastitried.mediagarrdclient.dto.VersionsDto; + +class VersionServiceTest { + + private static final Instant NOW = Instant.parse("2026-11-11T18:00:00Z"); + private static final VersionStatusDto CLIENT = new VersionStatusDto("0.1.0", "0.1.0", "https://github.com/MediaGarrd/Client/releases/tag/v0.1.0", false, CheckState.OK, NOW, null); + private static final VersionStatusDto SERVER = new VersionStatusDto("0.1.0", "0.2.0", "https://github.com/MediaGarrd/Server/releases/tag/v0.2.0", true, CheckState.OK, NOW, null); + private static final String URL = "http://server:38471"; + + private final MutableClock clock = new MutableClock(NOW); + private final UpdateCheckService updateCheckService = mock(UpdateCheckService.class); + private final ServerApiService serverApiService = mock(ServerApiService.class); + private final VersionService service = new VersionService(updateCheckService, serverApiService, clock); + + VersionServiceTest() { + when(updateCheckService.status()).thenReturn(CLIENT); + } + + @Test + void leavesTheServerOutUntilOneIsSelectedAndNeverCallsTheServerForIt() { + assertNull(service.versions().server()); + assertFalse(service.needsRefresh()); + assertFalse(service.refresh()); + service.select(" "); + + assertNull(service.versions().server()); + verify(serverApiService, never()).serverVersion(anyString()); + } + + @Test + void aSelectedServerIsPendingUntilItsVersionIsFetched() { + assertTrue(service.select(URL)); + + assertEquals(CheckState.NOT_CHECKED, service.versions().server().checkState()); + assertTrue(service.needsRefresh()); + assertFalse(service.select(URL)); + } + + @Test + void cachesTheFetchedVersionWithoutAskingTheServerAgain() { + when(serverApiService.serverVersion(URL)).thenReturn(SERVER); + service.select(URL); + + assertTrue(service.refresh()); + + assertEquals(new VersionsDto(CLIENT, SERVER), service.versions()); + assertEquals(new VersionsDto(CLIENT, SERVER), service.versions()); + assertFalse(service.needsRefresh()); + verify(serverApiService, times(1)).serverVersion(URL); + } + + @Test + void refetchesAtMostHourlyAndAtOnceAfterAnInvalidation() { + when(serverApiService.serverVersion(URL)).thenReturn(SERVER); + service.select(URL); + service.refresh(); + + clock.set(NOW.plus(Duration.ofMinutes(59))); + assertFalse(service.needsRefresh()); + clock.set(NOW.plus(Duration.ofHours(1))); + assertTrue(service.needsRefresh()); + + service.refresh(); + assertFalse(service.needsRefresh()); + assertFalse(service.invalidate(false)); + assertFalse(service.needsRefresh()); + clock.set(clock.instant().plus(Duration.ofMinutes(6))); + assertTrue(service.invalidate(false)); + assertTrue(service.needsRefresh()); + } + + @Test + void aServerThatHasNotCheckedYetIsAskedAgainAfterThirtySeconds() { + VersionStatusDto notChecked = new VersionStatusDto("0.1.0", null, null, false, CheckState.NOT_CHECKED, null, null); + when(serverApiService.serverVersion(URL)).thenReturn(notChecked).thenReturn(SERVER); + service.select(URL); + service.refresh(); + + clock.set(NOW.plus(Duration.ofSeconds(29))); + assertFalse(service.needsRefresh()); + clock.set(NOW.plus(Duration.ofSeconds(30))); + assertTrue(service.needsRefresh()); + assertTrue(service.refresh()); + + assertEquals(CheckState.OK, service.versions().server().checkState()); + clock.set(NOW.plus(Duration.ofMinutes(10))); + assertFalse(service.needsRefresh()); + } + + @Test + void aServerThatReportedAnErrorIsAskedAgainAfterFiveMinutes() { + VersionStatusDto failed = new VersionStatusDto("0.1.0", null, null, false, CheckState.ERROR, NOW, "GitHub is unreachable"); + when(serverApiService.serverVersion(URL)).thenReturn(failed); + service.select(URL); + service.refresh(); + + clock.set(NOW.plus(Duration.ofMinutes(4))); + assertFalse(service.needsRefresh()); + clock.set(NOW.plus(Duration.ofMinutes(5))); + assertTrue(service.needsRefresh()); + assertTrue(service.invalidate(false)); + } + + @Test + void aFailedFirstAttemptTurnsThePendingVersionIntoUnavailableOnce() { + assertFalse(service.markUnreachable()); + service.select(URL); + + assertTrue(service.markUnreachable()); + assertEquals(CheckState.UNAVAILABLE, service.versions().server().checkState()); + assertFalse(service.markUnreachable()); + assertTrue(service.invalidate(false)); + } + + @Test + void aFetchedVersionIsNotReplacedByAFailedLaterAttempt() { + when(serverApiService.serverVersion(URL)).thenReturn(SERVER); + service.select(URL); + service.refresh(); + + assertFalse(service.markUnreachable()); + assertEquals(SERVER, service.versions().server()); + } + + @Test + void reportsWhetherARefetchChangedAnything() { + when(serverApiService.serverVersion(URL)).thenReturn(SERVER); + service.select(URL); + + assertTrue(service.refresh()); + assertFalse(service.refresh()); + } + + @Test + void switchingServersDropsTheCachedVersionAndIgnoresAnInFlightAnswer() { + when(serverApiService.serverVersion(URL)).thenAnswer(call -> { + service.select("http://other:38471"); + return SERVER; + }); + service.select(URL); + + assertFalse(service.refresh()); + + assertEquals(CheckState.NOT_CHECKED, service.versions().server().checkState()); + } + + @Test + void reportsTheServerAsUnavailableWhenItCannotBeReachedAndRetriesSooner() { + when(serverApiService.serverVersion(URL)).thenThrow(new ResourceAccessException("refused")); + service.select(URL); + + service.refresh(); + + VersionsDto result = service.versions(); + assertEquals(CLIENT, result.client()); + assertEquals(CheckState.UNAVAILABLE, result.server().checkState()); + assertFalse(result.server().updateAvailable()); + clock.set(NOW.plus(Duration.ofMinutes(9))); + assertFalse(service.needsRefresh()); + clock.set(NOW.plus(Duration.ofMinutes(10))); + assertTrue(service.needsRefresh()); + } + + @Test + void reportsAnOlderServerWithoutTheEndpointAsUnavailable() { + when(serverApiService.serverVersion(URL)) + .thenThrow(new RestClientResponseException("Not Found", 404, "Not Found", null, null, null)); + service.select(URL); + + service.refresh(); + + assertEquals(CheckState.UNAVAILABLE, service.versions().server().checkState()); + } + + @Test + void reportsAnEmptyServerResponseAsUnavailable() { + when(serverApiService.serverVersion(URL)).thenReturn(null); + service.select(URL); + + service.refresh(); + + assertEquals(CheckState.UNAVAILABLE, service.versions().server().checkState()); + } + + @Test + void recoveringFromARealOutageRefetchesEvenWithinFiveMinutesOfAGoodAnswer() { + when(serverApiService.serverVersion(URL)).thenReturn(SERVER); + service.select(URL); + service.refresh(); + + assertFalse(service.invalidate(false)); + assertTrue(service.invalidate(true)); + assertTrue(service.needsRefresh()); + } +} diff --git a/src/test/java/wellatleastitried/mediaguardclient/api/ClientControllerTest.java b/src/test/java/wellatleastitried/mediaguardclient/api/ClientControllerTest.java deleted file mode 100644 index df656cc..0000000 --- a/src/test/java/wellatleastitried/mediaguardclient/api/ClientControllerTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package wellatleastitried.mediagarrdclient.api; - -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.nio.file.Path; -import java.time.Duration; -import java.util.List; - -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; - -import wellatleastitried.mediagarrdclient.dto.BackupDto; -import wellatleastitried.mediagarrdclient.service.BackupPickupService; -import wellatleastitried.mediagarrdclient.service.ClientStateService; -import wellatleastitried.mediagarrdclient.service.ServerApiService; -import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; - -@WebMvcTest(controllers = ClientController.class) -class ClientControllerTest { - - @Autowired - MockMvc mockMvc; - - @MockBean - ClientStateService stateService; - - @MockBean - ServerDiscoveryService discoveryService; - - @MockBean - ServerApiService serverApiService; - - @MockBean - BackupPickupService backupPickupService; - - @Test - void statusEndpointReturnsState() throws Exception { - when(stateService.getActiveServer()).thenReturn("http://server:8080"); - when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(45)); - when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); - - mockMvc.perform(get("/api/client/status")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.activeServer").value("http://server:8080")); - } - - @Test - void discoverEndpointUpdatesState() throws Exception { - when(discoveryService.discover()).thenReturn(List.of("http://server:8080")); - when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); - when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(30)); - when(stateService.getActiveServer()).thenReturn("http://server:8080"); - - mockMvc.perform(post("/api/client/discover")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.knownServers[0]").value("http://server:8080")); - } - - @Test - void listBackupsReturnsServerData() throws Exception { - when(stateService.getActiveServer()).thenReturn("http://server:8080"); - when(serverApiService.listBackups("http://server:8080")).thenReturn(List.of(new BackupDto("id", "file.zip", 10L, null))); - - mockMvc.perform(get("/api/client/backups")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$[0].id").value("id")); - } - - @Test - void setServerEndpointAcceptsUpdate() throws Exception { - when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); - when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(30)); - when(stateService.getActiveServer()).thenReturn("http://server:8080"); - - mockMvc.perform(put("/api/client/server") - .contentType(MediaType.APPLICATION_JSON) - .content("{\"serverUrl\":\"http://server:8080\"}")) - .andExpect(status().isOk()); - } - - @Test - void pickupEndpointReturnsPath() throws Exception { - when(backupPickupService.pickupLatest()).thenReturn(Path.of("/tmp/latest.zip")); - - mockMvc.perform(post("/api/client/pickup")) - .andExpect(status().isOk()); - } -} diff --git a/src/test/java/wellatleastitried/mediaguardclient/service/ClientStateServiceTest.java b/src/test/java/wellatleastitried/mediaguardclient/service/ClientStateServiceTest.java deleted file mode 100644 index e4ef030..0000000 --- a/src/test/java/wellatleastitried/mediaguardclient/service/ClientStateServiceTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.nio.file.Path; -import java.time.Duration; -import java.util.List; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import wellatleastitried.mediagarrdclient.Configuration; - -class ClientStateServiceTest { - - @TempDir - Path tempDir; - - @Test - void persistsAndLoadsState() { - Configuration cfg = new Configuration(); - cfg.setStateFile(tempDir.resolve("state.json").toString()); - cfg.setPickupInterval(Duration.ofHours(12)); - - ClientStateService state = new ClientStateService(cfg); - state.updateKnownServers(List.of("http://a:8080", "http://b:8080")); - state.setActiveServer("http://b:8080"); - state.setPickupInterval(Duration.ofMinutes(30)); - - ClientStateService reloaded = new ClientStateService(cfg); - assertEquals("http://b:8080", reloaded.getActiveServer()); - assertEquals(Duration.ofMinutes(30), reloaded.getPickupInterval()); - assertEquals(2, reloaded.getKnownServers().size()); - } -} diff --git a/src/test/js/api.test.mjs b/src/test/js/api.test.mjs new file mode 100644 index 0000000..3ad3d2a --- /dev/null +++ b/src/test/js/api.test.mjs @@ -0,0 +1,112 @@ +import assert from 'node:assert/strict'; +import { afterEach, test } from 'node:test'; +import { api, errorMessage, onLoginRequired, onPairingRequired, retryAfterSeconds, toApiError } from '../../main/resources/static/js/api.js'; + +const realFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = realFetch; + onLoginRequired(() => {}); + onPairingRequired(() => {}); +}); + +function respond(status, body, headers = {}) { + globalThis.fetch = async () => new Response(typeof body === 'string' ? body : JSON.stringify(body), { + status, + headers: new Headers(headers), + }); +} + +test('the error contract maps to its message and Spring default bodies prefer the detail message, then the reason phrase', () => { + assert.equal(errorMessage({ error: 'No active MediaGarrd server selected' }, 'x'), 'No active MediaGarrd server selected'); + const spring = { timestamp: 't', status: 400, error: 'Bad Request', path: '/x' }; + assert.equal(errorMessage({ ...spring, message: 'Name is required' }, 'x'), 'Name is required'); + assert.equal(errorMessage({ ...spring, message: '' }, 'x'), 'Bad Request'); + assert.equal(errorMessage(spring, 'x'), 'Bad Request'); +}); + +test('a missing, empty or non-object body falls back to the generic message', () => { + assert.equal(errorMessage({}, 'GET /x failed (500)'), 'GET /x failed (500)'); + assert.equal(errorMessage(null, 'fb'), 'fb'); + assert.equal(errorMessage('text', 'fb'), 'fb'); + assert.equal(errorMessage({ error: 42, message: ' ' }, 'fb'), 'fb'); +}); + +test('Retry-After accepts seconds and HTTP dates and rejects the rest', () => { + assert.equal(retryAfterSeconds('30'), 30); + assert.equal(retryAfterSeconds(' 7 '), 7); + assert.equal(retryAfterSeconds('0'), 0); + const now = Date.parse('2026-01-10T12:00:00Z'); + assert.equal(retryAfterSeconds('Sat, 10 Jan 2026 12:01:00 GMT', now), 60); + assert.equal(retryAfterSeconds('Sat, 10 Jan 2026 11:00:00 GMT', now), 0); + assert.equal(retryAfterSeconds('soon'), null); + assert.equal(retryAfterSeconds(''), null); + assert.equal(retryAfterSeconds(null), null); + assert.equal(retryAfterSeconds(undefined), null); +}); + +test('toApiError carries status, pairing flag and retry delay', () => { + const error = toApiError({ + method: 'POST', url: '/api/auth/login', status: 429, + data: { error: 'Too many login attempts, try again in 12 seconds' }, retryAfter: '12', + }); + assert.equal(error.message, 'Too many login attempts, try again in 12 seconds'); + assert.equal(error.status, 429); + assert.equal(error.retryAfter, 12); + assert.equal(error.pairing, undefined); + assert.equal(toApiError({ method: 'GET', url: '/x', status: 502, data: { error: 'm', pairing: 'required' } }).pairing, 'required'); + assert.equal(toApiError({ method: 'GET', url: '/x', status: 500, data: {} }).message, 'The client answered with an error (500).'); + assert.equal(toApiError({ method: 'POST', url: '/x', status: 504, data: {} }).message, 'The client or a proxy in front of it did not respond in time.'); + assert.equal(toApiError({ method: 'POST', url: '/x', status: 502, data: {} }).message, 'The client or a proxy in front of it did not respond in time.'); + assert.equal(toApiError({ status: 504, data: { error: 'Backup timed out' } }).message, 'Backup timed out'); +}); + +test('a 401 with login required fires the login hook once and still throws', async () => { + let fired = 0; + onLoginRequired(() => { fired++; }); + respond(401, { login: 'required', error: 'Sign in' }); + await assert.rejects(api.dashboard(), (error) => error.status === 401 && error.message === 'Sign in'); + assert.equal(fired, 1); +}); + +test('a 401 without the login marker does not fire the login hook', async () => { + let fired = 0; + onLoginRequired(() => { fired++; }); + respond(401, { error: 'Incorrect password' }); + await assert.rejects(api.login('x'), /Incorrect password/); + assert.equal(fired, 0); +}); + +test('a 502 pairing required fires the pairing hook', async () => { + let fired = 0; + onPairingRequired(() => { fired++; }); + respond(502, { error: 'Pair first', pairing: 'required' }); + await assert.rejects(api.listBackups(), /Pair first/); + assert.equal(fired, 1); +}); + +test('a non-JSON error body still produces a useful error with the Retry-After value', async () => { + respond(503, 'bad gateway', { 'Retry-After': '9' }); + await assert.rejects(api.status(), (error) => error.status === 503 && error.retryAfter === 9 && error.message === 'The client answered with an error (503).'); +}); + +test('successful empty and JSON responses are parsed', async () => { + respond(200, ''); + assert.equal(await api.logout(), null); + respond(200, { authenticated: true }); + assert.deepEqual(await api.authStatus(), { authenticated: true }); +}); + +test('requests send the CSRF header and JSON bodies', async () => { + let seen; + globalThis.fetch = async (url, init) => { + seen = { url, init }; + return new Response('{}', { status: 200 }); + }; + await api.pair('123456'); + assert.equal(seen.url, '/api/client/pairing'); + assert.equal(seen.init.method, 'POST'); + assert.equal(seen.init.headers['X-MediaGarrd-Request'], '1'); + assert.equal(seen.init.body, JSON.stringify({ pin: '123456' })); + await api.pickupById('a/b c'); + assert.equal(seen.url, '/api/client/pickup/a%2Fb%20c'); +}); diff --git a/src/test/js/auth-model.test.mjs b/src/test/js/auth-model.test.mjs new file mode 100644 index 0000000..dd94c74 --- /dev/null +++ b/src/test/js/auth-model.test.mjs @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { authScreen, passwordProblem } from '../../main/resources/static/js/auth-model.js'; + +test('the auth screen follows the auth status', () => { + const cases = [ + [null, 'loading'], + [undefined, 'loading'], + [{ passwordSet: true, authenticated: true }, 'none'], + [{ passwordSet: true, authenticated: false }, 'login'], + [{ passwordSet: false, authenticated: false }, 'set-password'], + ]; + for (const [status, screen] of cases) { + assert.equal(authScreen(status), screen); + } +}); + +test('a new password needs eight characters and a matching repeat', () => { + assert.match(passwordProblem('short', 'short'), /at least 8/); + assert.match(passwordProblem('long enough', 'different'), /do not match/); + assert.equal(passwordProblem('long enough', 'long enough'), null); +}); + +test('the lockout message counts seconds and disappears at zero', async () => { + const { lockoutMessage } = await import('../../main/resources/static/js/auth-model.js'); + assert.equal(lockoutMessage(1), 'Too many login attempts. Try again in 1 second.'); + assert.equal(lockoutMessage(30), 'Too many login attempts. Try again in 30 seconds.'); + assert.equal(lockoutMessage(0), null); +}); diff --git a/src/test/js/busy.test.mjs b/src/test/js/busy.test.mjs new file mode 100644 index 0000000..09e816e --- /dev/null +++ b/src/test/js/busy.test.mjs @@ -0,0 +1,50 @@ +import assert from 'node:assert/strict'; +import { afterEach, test } from 'node:test'; +import { withBusy } from '../../main/resources/static/js/busy.js'; + +const savedDocument = globalThis.document; +afterEach(() => { + if (savedDocument === undefined) delete globalThis.document; + else globalThis.document = savedDocument; +}); + +function button(focused) { + const element = { disabled: false, focused: 0, focus() { this.focused++; } }; + globalThis.document = { activeElement: focused ? element : null }; + return element; +} + +test('the button is disabled while the task runs and restored afterwards', async () => { + const element = button(false); + let during; + const result = await withBusy(element, async () => { during = element.disabled; return 7; }); + assert.equal(during, true); + assert.equal(element.disabled, false); + assert.equal(result, 7); +}); + +test('focus returns to a button that had it, and only then', async () => { + const focused = button(true); + await withBusy(focused, async () => {}); + assert.equal(focused.focused, 1); + const other = button(false); + await withBusy(other, async () => {}); + assert.equal(other.focused, 0); +}); + +test('a second activation while busy is ignored', async () => { + const element = button(false); + let runs = 0; + let release; + const first = withBusy(element, () => new Promise((resolve) => { runs++; release = resolve; })); + assert.equal(await withBusy(element, async () => { runs++; }), undefined); + release(); + await first; + assert.equal(runs, 1); +}); + +test('the button is restored when the task throws', async () => { + const element = button(true); + await assert.rejects(withBusy(element, async () => { throw new Error('boom'); }), /boom/); + assert.equal(element.disabled, false); +}); diff --git a/src/test/js/dashboard-model.test.mjs b/src/test/js/dashboard-model.test.mjs new file mode 100644 index 0000000..cfaf3c8 --- /dev/null +++ b/src/test/js/dashboard-model.test.mjs @@ -0,0 +1,215 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { applyEvent, canLoadBackups, changes, emptyState, reduce } from '../../main/resources/static/js/dashboard-model.js'; + +const snapshot = (overrides = {}) => ({ + activeServer: 'http://a:38471', + knownServers: ['http://a:38471'], + link: 'LIVE', + running: false, + health: { backupInterval: 'PT6H', backupRetentionCount: 5 }, + versions: { client: { checkState: 'OK' }, server: { checkState: 'OK' } }, + ...overrides, +}); + +const loaded = (overrides) => reduce(emptyState(), 'snapshot', snapshot(overrides)); + +test('a snapshot replaces the whole state and marks it loaded', () => { + const state = loaded(); + assert.equal(state.loaded, true); + assert.equal(state.activeServer, 'http://a:38471'); + assert.deepEqual(state.knownServers, ['http://a:38471']); + assert.equal(state.link, 'LIVE'); + assert.equal(state.running, false); + assert.deepEqual(state.health, { backupInterval: 'PT6H', backupRetentionCount: 5 }); + assert.equal(state.clientReachable, true); +}); + +test('a snapshot normalizes a missing server and unknown run state', () => { + const state = loaded({ activeServer: null, knownServers: undefined, running: null, health: null, versions: null }); + assert.equal(state.activeServer, null); + assert.deepEqual(state.knownServers, []); + assert.equal(state.running, null); + assert.equal(state.health, null); + assert.equal(state.versions, null); +}); + +test('events before the first snapshot are ignored', () => { + const state = emptyState(); + assert.equal(reduce(state, 'state', { running: true }), state); + assert.equal(reduce(state, 'link', { state: 'LIVE' }), state); +}); + +test('run events set the running flag', () => { + let state = loaded(); + state = reduce(state, 'run-started', { running: true, startedAt: 't' }); + assert.equal(state.running, true); + state = reduce(state, 'run-finished', { running: false, status: 'COMPLETED' }); + assert.equal(state.running, false); + state = reduce(state, 'state', { running: true }); + assert.equal(state.running, true); +}); + +test('a link event changes the link and a DOWN link forgets the run state', () => { + let state = loaded({ running: true }); + state = reduce(state, 'link', { server: 'http://a:38471', state: 'DEGRADED' }); + assert.equal(state.link, 'DEGRADED'); + assert.equal(state.running, true); + state = reduce(state, 'link', { server: 'http://a:38471', state: 'DOWN' }); + assert.equal(state.link, 'DOWN'); + assert.equal(state.running, null); +}); + +test('servers, config and versions events update their slices only', () => { + let state = loaded(); + state = reduce(state, 'servers', { knownServers: ['http://a:38471', 'http://b:38471'], activeServer: 'http://a:38471' }); + assert.deepEqual(state.knownServers, ['http://a:38471', 'http://b:38471']); + assert.equal(state.link, 'LIVE'); + state = reduce(state, 'config', { backupInterval: 'PT2H', backupRetentionCount: 9 }); + assert.deepEqual(state.health, { backupInterval: 'PT2H', backupRetentionCount: 9 }); + state = reduce(state, 'versions', { client: null, server: { checkState: 'UNAVAILABLE' } }); + assert.equal(state.versions.server.checkState, 'UNAVAILABLE'); + assert.equal(state.activeServer, 'http://a:38471'); +}); + +test('pings, backup announcements and unknown events leave the state alone', () => { + const state = loaded(); + assert.equal(reduce(state, 'ping', {}), state); + assert.equal(reduce(state, 'backups-changed', { at: 't' }), state); + assert.equal(reduce(state, 'surprise', {}), state); +}); + +test('the client being unreachable is tracked and cleared by any event from the stream', () => { + let state = loaded(); + state = reduce(state, 'client', { reachable: false }); + assert.equal(state.clientReachable, false); + assert.equal(reduce(state, 'client', { reachable: false }), state); + state = reduce(state, 'ping', {}); + assert.equal(state.clientReachable, true); + state = reduce(reduce(state, 'client', { reachable: false }), 'snapshot', snapshot()); + assert.equal(state.clientReachable, true); +}); + +test('nothing happens before the first snapshot', () => { + assert.deepEqual(changes(emptyState(), emptyState(), 'client'), { serverChanged: false, clearBackups: false, refreshBackups: false }); +}); + +test('the first snapshot of a reachable server loads the backups once', () => { + const next = loaded(); + assert.deepEqual(changes(emptyState(), next, 'snapshot'), { serverChanged: false, clearBackups: false, refreshBackups: true }); +}); + +test('the first snapshot of a server that is down waits for it to come up', () => { + const down = loaded({ link: 'DOWN' }); + assert.equal(changes(emptyState(), down, 'snapshot').refreshBackups, false); + const up = reduce(down, 'link', { state: 'DEGRADED' }); + assert.equal(changes(down, up, 'link').refreshBackups, true); +}); + +test('a first snapshot without a server loads no backups', () => { + assert.equal(changes(emptyState(), loaded({ activeServer: null, link: 'DOWN' }), 'snapshot').refreshBackups, false); +}); + +test('switching servers clears the table and reloads it only once the new server is up', () => { + const before = loaded(); + const switched = reduce(before, 'snapshot', snapshot({ activeServer: 'http://b:38471', link: 'DOWN', running: null, health: null })); + assert.deepEqual(changes(before, switched, 'snapshot'), { serverChanged: true, clearBackups: true, refreshBackups: false }); + const up = reduce(switched, 'link', { state: 'LIVE' }); + assert.deepEqual(changes(switched, up, 'link'), { serverChanged: false, clearBackups: false, refreshBackups: true }); +}); + +test('a switch noticed through an already-up snapshot reloads right away', () => { + const before = loaded(); + const switched = reduce(before, 'snapshot', snapshot({ activeServer: 'http://b:38471' })); + assert.deepEqual(changes(before, switched, 'snapshot'), { serverChanged: true, clearBackups: true, refreshBackups: true }); +}); + +test('clearing the server clears the table without reloading it', () => { + const before = loaded(); + const cleared = reduce(before, 'snapshot', snapshot({ activeServer: null, link: 'DOWN', running: null })); + assert.deepEqual(changes(before, cleared, 'snapshot'), { serverChanged: true, clearBackups: true, refreshBackups: false }); +}); + +test('a run finishing reloads the backups, however it was learned', () => { + const running = loaded({ running: true }); + const viaEvent = reduce(running, 'run-finished', { running: false }); + assert.equal(changes(running, viaEvent, 'run-finished').refreshBackups, true); + const viaState = reduce(running, 'state', { running: false }); + assert.equal(changes(running, viaState, 'state').refreshBackups, true); + const idle = loaded(); + assert.equal(changes(idle, reduce(idle, 'state', { running: false }), 'state').refreshBackups, false); + assert.equal(changes(idle, reduce(idle, 'run-started', {}), 'run-started').refreshBackups, false); +}); + +test('coming back from DOWN or from an unreachable client reloads the backups', () => { + const down = loaded({ link: 'DOWN' }); + assert.equal(changes(down, reduce(down, 'link', { state: 'LIVE' }), 'link').refreshBackups, true); + const live = loaded(); + const unreachable = reduce(live, 'client', { reachable: false }); + assert.equal(changes(live, unreachable, 'client').refreshBackups, false); + assert.equal(changes(unreachable, reduce(unreachable, 'client', { reachable: true }), 'client').refreshBackups, true); +}); + +test('a degraded to live move does not reload anything', () => { + const degraded = loaded({ link: 'DEGRADED' }); + assert.equal(changes(degraded, reduce(degraded, 'link', { state: 'LIVE' }), 'link').refreshBackups, false); +}); + +test('config, versions and server list updates never reload the backups', () => { + const state = loaded(); + assert.equal(changes(state, reduce(state, 'config', { backupInterval: 'PT1H', backupRetentionCount: 2 }), 'config').refreshBackups, false); + assert.equal(changes(state, reduce(state, 'versions', {}), 'versions').refreshBackups, false); + assert.equal(changes(state, reduce(state, 'servers', { knownServers: [], activeServer: 'http://a:38471' }), 'servers').refreshBackups, false); +}); + +test('a backups-changed announcement is an effect even though it leaves the state identical', () => { + const state = loaded(); + const result = applyEvent(state, 'backups-changed', { at: 't' }); + assert.equal(result.state, state); + assert.deepEqual(result.effects, { serverChanged: false, clearBackups: false, refreshBackups: true }); +}); + +test('a backups-changed announcement does nothing while the server is not up', () => { + for (const link of ['DOWN', 'CONNECTING']) { + const state = loaded({ link }); + assert.equal(applyEvent(state, 'backups-changed', { at: 't' }).effects.refreshBackups, false); + } +}); + +test('backups may be loaded only for a reachable client with an active server whose link is up', () => { + assert.equal(canLoadBackups(emptyState()), false); + assert.equal(canLoadBackups(loaded()), true); + assert.equal(canLoadBackups(loaded({ link: 'DEGRADED' })), true); + assert.equal(canLoadBackups(loaded({ link: 'DOWN' })), false); + assert.equal(canLoadBackups(loaded({ link: 'CONNECTING' })), false); + assert.equal(canLoadBackups(loaded({ activeServer: null })), false); + assert.equal(canLoadBackups(reduce(loaded(), 'client', { reachable: false })), false); +}); + +test('a connecting link forgets the run state and a first answer reloads the backups', () => { + const live = loaded({ running: true }); + const connecting = reduce(live, 'link', { state: 'CONNECTING' }); + assert.equal(connecting.running, null); + const up = reduce(connecting, 'link', { state: 'DEGRADED' }); + assert.equal(changes(connecting, up, 'link').refreshBackups, true); +}); + +test('a snapshot carries the pairing state and defaults to paired when it is missing', () => { + assert.equal(loaded({ pairing: 'REQUIRED' }).pairing, 'REQUIRED'); + assert.equal(loaded().pairing, 'PAIRED'); + assert.equal(loaded({ activeServer: null, pairing: 'NONE' }).pairing, 'NONE'); +}); + +test('a pairing event changes the pairing state', () => { + const state = reduce(loaded({ pairing: 'PAIRED' }), 'pairing', { state: 'REJECTED' }); + assert.equal(state.pairing, 'REJECTED'); + assert.equal(reduce(state, 'pairing', { state: 'PAIRED' }).pairing, 'PAIRED'); +}); + +test('archives are not loaded for a server that is not paired and load once pairing succeeds', () => { + assert.equal(canLoadBackups(loaded({ pairing: 'REQUIRED' })), false); + assert.equal(canLoadBackups(loaded({ pairing: 'REJECTED' })), false); + const rejected = loaded({ pairing: 'REJECTED' }); + const result = applyEvent(rejected, 'pairing', { state: 'PAIRED' }); + assert.equal(result.effects.refreshBackups, true); +}); diff --git a/src/test/js/events.test.mjs b/src/test/js/events.test.mjs new file mode 100644 index 0000000..96c2221 --- /dev/null +++ b/src/test/js/events.test.mjs @@ -0,0 +1,154 @@ +import assert from 'node:assert/strict'; +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join } from 'node:path'; +import { afterEach, beforeEach, test } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { EVENT_NAMES, initEvents } from '../../main/resources/static/js/events.js'; + +const JAVA_ROOT = fileURLToPath(new URL('../../main/java', import.meta.url)); + +function javaFiles(dir) { + return readdirSync(dir).flatMap((name) => { + const path = join(dir, name); + return statSync(path).isDirectory() ? javaFiles(path) : path.endsWith('.java') ? [path] : []; + }); +} + +function publishedByJava() { + const names = new Set(); + const sources = javaFiles(JAVA_ROOT).map((file) => readFileSync(file, 'utf8')); + for (const source of sources) { + for (const match of source.matchAll(/\b(?:publish|publishRaw)\(\s*"([a-z][a-z-]*)"/g)) names.add(match[1]); + for (const match of source.matchAll(/new ClientEvent\(\s*"([a-z][a-z-]*)"/g)) names.add(match[1]); + } + const stream = sources.find((source) => source.includes('FORWARDED_EVENTS = Set.of(')); + const forwarded = /FORWARDED_EVENTS = Set\.of\(([^)]*)\)/.exec(stream)[1].match(/"[a-z-]+"/g).map((quoted) => quoted.slice(1, -1)); + forwarded.filter((name) => name !== 'config-changed').forEach((name) => names.add(name)); + names.delete('close'); + return names; +} + +test('EVENT_NAMES covers every event the Java client publishes, and nothing else', () => { + const published = publishedByJava(); + assert.ok(published.size >= 10, `expected to find the published events, found ${[...published]}`); + assert.deepEqual([...EVENT_NAMES].sort(), [...published].sort()); +}); + +class FakeSource { + static CLOSED = 2; + static instances = []; + constructor(url) { + this.url = url; + this.readyState = 1; + this.listeners = {}; + this.closed = false; + FakeSource.instances.push(this); + } + addEventListener(name, handler) { (this.listeners[name] ||= []).push(handler); } + close() { this.closed = true; } + emit(name, event = {}) { (this.listeners[name] || []).forEach((handler) => handler(event)); } +} + +const saved = {}; +beforeEach(() => { + FakeSource.instances = []; + for (const key of ['EventSource', 'document', 'window', 'setInterval', 'setTimeout']) saved[key] = globalThis[key]; + globalThis.EventSource = FakeSource; + globalThis.document = { hidden: false, addEventListener() {} }; + globalThis.window = { addEventListener() {} }; + globalThis.setInterval = () => 0; + globalThis.setTimeout = () => 0; +}); +afterEach(() => { + for (const key of Object.keys(saved)) { + if (saved[key] === undefined) delete globalThis[key]; + else globalThis[key] = saved[key]; + } +}); + +test('every declared event name is subscribed, including pairing', () => { + initEvents({ onEvent() {}, onConnection() {} }); + const [source] = FakeSource.instances; + assert.deepEqual(EVENT_NAMES.filter((name) => !source.listeners[name]), []); + assert.ok(source.listeners.pairing); +}); + +test('a pairing event reaches the handler as parsed JSON and pings are swallowed', () => { + const seen = []; + initEvents({ onEvent: (name, payload) => seen.push([name, payload]), onConnection() {} }); + const [source] = FakeSource.instances; + source.emit('pairing', { data: '{"state":"REJECTED"}' }); + source.emit('ping', { data: '{}' }); + source.emit('link', { data: 'not json' }); + assert.deepEqual(seen, [['pairing', { state: 'REJECTED' }]]); +}); + +test('a stream refused before it ever opened checks the session', async () => { + let checks = 0; + const connection = []; + initEvents({ onEvent() {}, onConnection: (reachable) => connection.push(reachable), checkSession: async () => { checks++; } }); + const [source] = FakeSource.instances; + source.readyState = FakeSource.CLOSED; + source.emit('error'); + assert.equal(checks, 1); + assert.equal(source.closed, true); + assert.deepEqual(connection, [false]); +}); + +test('a stream that dropped after opening does not check the session', () => { + let checks = 0; + initEvents({ onEvent() {}, onConnection() {}, checkSession: async () => { checks++; } }); + const [source] = FakeSource.instances; + source.emit('open'); + source.readyState = FakeSource.CLOSED; + source.emit('error'); + assert.equal(checks, 0); +}); + +test('a refused reconnect after a stream that was open checks the session', () => { + let checks = 0; + initEvents({ onEvent() {}, onConnection() {}, checkSession: async () => { checks++; } }); + const [source] = FakeSource.instances; + source.emit('open'); + source.readyState = 0; + source.emit('error'); + assert.equal(checks, 0); + source.readyState = FakeSource.CLOSED; + source.emit('error'); + assert.equal(checks, 1); +}); + +test('a reconnect that opened again does not check the session when it later drops', () => { + let checks = 0; + initEvents({ onEvent() {}, onConnection() {}, checkSession: async () => { checks++; } }); + const [source] = FakeSource.instances; + source.emit('open'); + source.readyState = 0; + source.emit('error'); + source.readyState = 1; + source.emit('open'); + source.readyState = FakeSource.CLOSED; + source.emit('error'); + assert.equal(checks, 0); +}); + +test('a failing session check is swallowed and the stream is still reopened', async () => { + let checks = 0; + let reopens = 0; + const unhandled = []; + const onUnhandled = (reason) => unhandled.push(reason); + process.on('unhandledRejection', onUnhandled); + globalThis.setTimeout = () => { reopens++; return 1; }; + try { + initEvents({ onEvent() {}, onConnection() {}, checkSession: async () => { checks++; throw new Error('down'); } }); + const [source] = FakeSource.instances; + source.readyState = FakeSource.CLOSED; + source.emit('error'); + await new Promise((resolve) => setImmediate(resolve)); + } finally { + process.off('unhandledRejection', onUnhandled); + } + assert.equal(checks, 1); + assert.equal(reopens, 1); + assert.deepEqual(unhandled, []); +}); diff --git a/src/test/js/format.test.mjs b/src/test/js/format.test.mjs new file mode 100644 index 0000000..0ad5676 --- /dev/null +++ b/src/test/js/format.test.mjs @@ -0,0 +1,87 @@ +import assert from 'node:assert/strict'; +import { afterEach, test } from 'node:test'; +import { bytes, formatInterval, intervalProblem, percent, pickupProblem, relativeTime, seconds, toDuration, toHours } from '../../main/resources/static/js/format.js'; + +const realNow = Date.now; +afterEach(() => { Date.now = realNow; }); + +test('seconds reads ISO durations, plain numbers and garbage', () => { + assert.equal(seconds('PT6H'), 21600); + assert.equal(seconds('PT1H30M'), 5400); + assert.equal(seconds('PT45S'), 45); + assert.equal(seconds('pt0.5H'), 1800); + assert.equal(seconds(90), 90); + assert.equal(seconds('nonsense'), 0); + assert.equal(seconds(null), 0); + assert.equal(seconds(undefined), 0); +}); + +test('toDuration uses whole minutes when it can and seconds otherwise', () => { + assert.equal(toDuration(5), 'PT5M'); + assert.equal(toDuration(90), 'PT90M'); + assert.equal(toDuration(0.5), 'PT30S'); + assert.equal(toDuration(0.25 * 60), 'PT15M'); +}); + +test('toHours rounds to four decimals and survives a round trip', () => { + assert.equal(toHours('PT6H'), 6); + assert.equal(toHours('PT15M'), 0.25); + assert.equal(toHours('PT20M'), 0.3333); + assert.equal(seconds(toDuration(toHours('PT20M') * 60)), 1200); + assert.equal(seconds(toDuration(toHours('PT5M') * 60)), 300); +}); + +test('formatInterval is compact and shows a dash for zero or unknown', () => { + assert.equal(formatInterval('PT6H'), '6h'); + assert.equal(formatInterval('PT90M'), '1h 30m'); + assert.equal(formatInterval('PT45S'), '45s'); + assert.equal(formatInterval('PT0S'), '—'); + assert.equal(formatInterval(null), '—'); +}); + +test('bytes picks a unit and caps at TB', () => { + assert.equal(bytes(0), '0 B'); + assert.equal(bytes(undefined), '0 B'); + assert.equal(bytes(512), '512 B'); + assert.equal(bytes(1536), '1.5 KB'); + assert.equal(bytes(5 * 1024 ** 2), '5.0 MB'); + assert.equal(bytes(3 * 1024 ** 4), '3.0 TB'); + assert.equal(bytes(2048 * 1024 ** 4), '2048.0 TB'); +}); + +test('relativeTime buckets and clamps the future', () => { + Date.now = () => Date.parse('2026-01-10T12:00:00Z'); + assert.equal(relativeTime('2026-01-10T11:59:30Z'), '30s ago'); + assert.equal(relativeTime('2026-01-10T11:55:00Z'), '5m ago'); + assert.equal(relativeTime('2026-01-10T09:00:00Z'), '3h ago'); + assert.equal(relativeTime('2026-01-08T12:00:00Z'), '2d ago'); + assert.equal(relativeTime('2026-01-11T12:00:00Z'), '0s ago'); + assert.equal(relativeTime('not a date'), '—'); + assert.equal(relativeTime(undefined), '—'); +}); + +test('percent is clamped and safe for an unknown total', () => { + assert.equal(percent(50, 200), 25); + assert.equal(percent(300, 200), 100); + assert.equal(percent(-5, 200), 0); + assert.equal(percent(5, 0), 0); + assert.equal(percent(5, undefined), 0); +}); + +test('intervalProblem accepts 15 minutes to 365 days and names the bounds otherwise', () => { + const message = 'Backup interval must be between 15 minutes and 365 days'; + assert.equal(intervalProblem(0.25), null); + assert.equal(intervalProblem(12), null); + assert.equal(intervalProblem(8760), null); + for (const hours of [0, -1, 0.24, 8760.01, 1e9, NaN, Infinity]) assert.equal(intervalProblem(hours), message); +}); + +test('pickupProblem accepts 1 minute to 365 days and rejects the rest', () => { + assert.equal(pickupProblem(1), null); + assert.equal(pickupProblem(525600), null); + assert.ok(pickupProblem(525601)); + assert.ok(pickupProblem(0.5)); + assert.ok(pickupProblem(0)); + assert.ok(pickupProblem(NaN)); + assert.ok(pickupProblem(Infinity)); +}); diff --git a/src/test/js/notify.test.mjs b/src/test/js/notify.test.mjs new file mode 100644 index 0000000..596f3b4 --- /dev/null +++ b/src/test/js/notify.test.mjs @@ -0,0 +1,44 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { createNotifier } from '../../main/resources/static/js/notify.js'; + +function banner() { + const attributes = {}; + return { + textContent: '', + className: 'banner', + attributes, + scrolled: 0, + setAttribute(name, value) { attributes[name] = value; }, + scrollIntoView() { this.scrolled++; }, + }; +} + +test('errors are assertive and scrolled into view', () => { + const element = banner(); + createNotifier(element).error(new Error('Nope')); + assert.equal(element.textContent, 'Nope'); + assert.equal(element.className, 'banner visible error'); + assert.equal(element.attributes['aria-live'], 'assertive'); + assert.equal(element.scrolled, 1); +}); + +test('success is polite and does not scroll; warnings scroll', () => { + const element = banner(); + const notify = createNotifier(element); + notify.ok('Saved'); + assert.equal(element.className, 'banner visible ok'); + assert.equal(element.attributes['aria-live'], 'polite'); + assert.equal(element.scrolled, 0); + notify.warn('Careful'); + assert.equal(element.className, 'banner visible warn'); + assert.equal(element.scrolled, 1); + notify.clear(); + assert.equal(element.className, 'banner'); +}); + +test('a non-Error rejection is shown as text', () => { + const element = banner(); + createNotifier(element).error('plain'); + assert.equal(element.textContent, 'plain'); +}); diff --git a/src/test/js/pairing-model.test.mjs b/src/test/js/pairing-model.test.mjs new file mode 100644 index 0000000..0a5f410 --- /dev/null +++ b/src/test/js/pairing-model.test.mjs @@ -0,0 +1,51 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { emptyState, reduce } from '../../main/resources/static/js/dashboard-model.js'; +import { codeView, credentialProblem, pairingNote, pairingPanel } from '../../main/resources/static/js/pairing-model.js'; + +const loaded = (overrides = {}) => reduce(emptyState(), 'snapshot', { + activeServer: 'https://garrd.example.com', + knownServers: ['https://garrd.example.com'], + link: 'DEGRADED', + running: null, + health: null, + versions: null, + pairing: 'PAIRED', + ...overrides, +}); + +test('the pairing panel is hidden until a reachable server is selected', () => { + assert.equal(pairingPanel(emptyState()), 'hidden'); + assert.equal(pairingPanel(loaded({ activeServer: null, pairing: 'NONE' })), 'hidden'); + assert.equal(pairingPanel(loaded({ link: 'DOWN' })), 'hidden'); + assert.equal(pairingPanel(loaded({ link: 'CONNECTING', pairing: 'REQUIRED' })), 'hidden'); +}); + +test('an unpaired or rejected server asks for pairing and a paired one offers codes and unpairing', () => { + assert.equal(pairingPanel(loaded({ pairing: 'REQUIRED' })), 'pair'); + assert.equal(pairingPanel(loaded({ pairing: 'REJECTED' })), 'pair'); + assert.equal(pairingPanel(loaded({ pairing: 'PAIRED', link: 'LIVE' })), 'manage'); +}); + +test('a rejected token is explained differently from a missing one', () => { + const rejected = pairingNote(loaded({ pairing: 'REJECTED' })); + assert.match(rejected, /no longer accepts/); + assert.match(rejected, /^The server no longer accepts this client\. Enter a pairing code from a client that is still paired\./); + assert.match(rejected, /Pairing PIN.*only when no client is paired.*MEDIAGARRD_OPEN_PAIRING/); + assert.match(pairingNote(loaded({ pairing: 'REQUIRED' })), /Pairing PIN/); +}); + +test('an empty credential is refused before it is sent', () => { + assert.ok(credentialProblem(' ')); + assert.ok(credentialProblem(undefined)); + assert.equal(credentialProblem(' 123456 '), null); +}); + +test('a pairing code counts down and then reads as expired', () => { + const code = { code: 'ABCDE-FGHJK', expiresAt: '2026-11-19T12:10:00Z' }; + const start = Date.parse('2026-11-19T12:00:00Z'); + assert.deepEqual(codeView(code, start), { text: 'ABCDE-FGHJK', expires: 'Expires in 10:00' }); + assert.equal(codeView(code, start + 541_000).expires, 'Expires in 0:59'); + assert.equal(codeView(code, start + 600_000).expires, 'Expired'); + assert.equal(codeView(null, start), null); +}); diff --git a/src/test/js/reachability.test.mjs b/src/test/js/reachability.test.mjs new file mode 100644 index 0000000..5f62ad1 --- /dev/null +++ b/src/test/js/reachability.test.mjs @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { createReachability } from '../../main/resources/static/js/reachability.js'; + +function harness() { + const changes = []; + const timers = new Map(); + let next = 1; + const reachability = createReachability({ + graceMs: 8000, + onChange: (reachable) => changes.push(reachable), + setTimer: (callback, ms) => { + const id = next++; + timers.set(id, { callback, ms }); + return id; + }, + clearTimer: (id) => timers.delete(id), + }); + const fire = () => [...timers.values()].forEach((timer) => { timers.clear(); timer.callback(); }); + return { reachability, changes, timers, fire }; +} + +test('a transient error followed by open never declares the client unreachable', () => { + const { reachability, changes, timers, fire } = harness(); + reachability.failed(false); + assert.equal(timers.size, 1); + assert.deepEqual([...timers.values()].map((timer) => timer.ms), [8000]); + reachability.alive(); + fire(); + assert.deepEqual(changes, [true]); + assert.equal(timers.size, 0); +}); + +test('an error that is not followed by open declares the client unreachable after the grace period', () => { + const { reachability, changes, fire } = harness(); + reachability.failed(false); + assert.deepEqual(changes, []); + fire(); + assert.deepEqual(changes, [false]); + reachability.alive(); + assert.deepEqual(changes, [false, true]); +}); + +test('repeated errors during the grace period do not extend it', () => { + const { reachability, timers } = harness(); + reachability.failed(false); + reachability.failed(false); + reachability.failed(false); + assert.equal(timers.size, 1); +}); + +test('a closed stream is declared unreachable at once and cancels a pending grace timer', () => { + const { reachability, changes, timers } = harness(); + reachability.failed(false); + reachability.failed(true); + assert.deepEqual(changes, [false]); + assert.equal(timers.size, 0); +}); + +test('any sign of life after a pending error cancels it', () => { + const { reachability, changes, timers, fire } = harness(); + reachability.failed(false); + reachability.alive(); + reachability.failed(false); + assert.equal(timers.size, 1); + fire(); + assert.deepEqual(changes, [true, false]); +}); + +test('cancelling drops a pending grace timer without reporting anything', () => { + const { reachability, changes, timers, fire } = harness(); + reachability.failed(false); + reachability.cancel(); + fire(); + assert.equal(timers.size, 0); + assert.deepEqual(changes, []); +}); diff --git a/src/test/js/view-model.test.mjs b/src/test/js/view-model.test.mjs new file mode 100644 index 0000000..83b4949 --- /dev/null +++ b/src/test/js/view-model.test.mjs @@ -0,0 +1,178 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { emptyState, reduce } from '../../main/resources/static/js/dashboard-model.js'; +import { classifyVersion, configUnavailableMessage, linkView, listingError, planKnown, versionsView } from '../../main/resources/static/js/view-model.js'; + +const loaded = (overrides = {}) => reduce(emptyState(), 'snapshot', { + activeServer: 'http://a:38471', + knownServers: ['http://a:38471'], + link: 'LIVE', + running: false, + health: { backupInterval: 'PT6H', backupRetentionCount: 5 }, + versions: null, + ...overrides, +}); + +test('before the first snapshot the page says it is connecting', () => { + const view = linkView(emptyState()); + assert.deepEqual(view.badge, { kind: 'checking', label: 'Connecting…' }); + assert.equal(view.showDetails, false); +}); + +test('a live server shows its details and the host in the badge', () => { + const view = linkView(loaded({ running: true })); + assert.deepEqual(view.badge, { kind: 'ok', label: 'a:38471' }); + assert.equal(view.showDetails, true); + assert.equal(view.url, 'http://a:38471'); + assert.equal(view.interval, '6h'); + assert.equal(view.retention, '5 archives'); + assert.equal(view.running, true); + assert.equal(view.degraded, false); +}); + +test('a degraded server looks connected but says live updates are unavailable', () => { + const view = linkView(loaded({ link: 'DEGRADED' })); + assert.equal(view.badge.kind, 'degraded'); + assert.equal(view.showDetails, true); + assert.equal(view.degraded, true); +}); + +test('a live server with no health yet shows placeholders and idle', () => { + const view = linkView(loaded({ health: null, running: null })); + assert.equal(view.interval, '—'); + assert.equal(view.retention, '—'); + assert.equal(view.running, false); +}); + +test('a down server names itself and is not shown as connected', () => { + const view = linkView(loaded({ link: 'DOWN', running: null })); + assert.deepEqual(view.badge, { kind: 'down', label: 'Unreachable' }); + assert.equal(view.showDetails, false); + assert.equal(view.message, 'http://a:38471 is not responding.'); +}); + +test('no active server reads as not connected', () => { + const view = linkView(loaded({ activeServer: null, link: 'DOWN' })); + assert.deepEqual(view.badge, { kind: '', label: 'Not Connected' }); + assert.equal(view.message, 'No server connected.'); +}); + +test('an unreachable client is never reported as a missing server', () => { + for (const state of [reduce(loaded(), 'client', { reachable: false }), reduce(emptyState(), 'client', { reachable: false })]) { + const view = linkView(state); + assert.deepEqual(view.badge, { kind: 'down', label: 'Client unreachable' }); + assert.equal(view.showDetails, false); + assert.ok(!view.message.includes('No server connected')); + } +}); + +const plan = (overrides) => planKnown({ + shown: ['http://a:38471'], + knownServers: ['http://a:38471'], + activeServer: 'http://a:38471', + selected: 'http://a:38471', + focused: false, + switched: false, + ...overrides, +}); + +test('an unchanged list is left alone', () => { + assert.deepEqual(plan({}), { action: 'keep' }); +}); + +test('an empty list shows the placeholder once', () => { + assert.deepEqual(plan({ shown: [], knownServers: [], activeServer: null, selected: '' }), { action: 'render', values: [''], selected: null }); + assert.deepEqual(plan({ shown: [''], knownServers: [], activeServer: null, selected: '' }), { action: 'keep' }); +}); + +test('a changed list keeps the selection the user is on', () => { + const result = plan({ knownServers: ['http://a:38471', 'http://b:38471'], selected: 'http://b:38471' }); + assert.deepEqual(result, { action: 'render', values: ['http://a:38471', 'http://b:38471'], selected: 'http://b:38471' }); +}); + +test('a changed list falls back to the active server when the selection vanished', () => { + const result = plan({ shown: ['http://a:38471', 'http://c:38471'], selected: 'http://c:38471' }); + assert.deepEqual(result, { action: 'render', values: ['http://a:38471'], selected: 'http://a:38471' }); +}); + +test('a changed list is deferred while the select has focus', () => { + assert.deepEqual(plan({ knownServers: ['http://a:38471', 'http://b:38471'], focused: true }), { action: 'defer' }); + assert.deepEqual(plan({ focused: true }), { action: 'keep' }); +}); + +test('a switch of the active server selects it even with focus or an unchanged list', () => { + const result = plan({ shown: ['http://a:38471', 'http://b:38471'], knownServers: ['http://a:38471', 'http://b:38471'], activeServer: 'http://b:38471', selected: 'http://a:38471', focused: true, switched: true }); + assert.deepEqual(result, { action: 'render', values: ['http://a:38471', 'http://b:38471'], selected: 'http://b:38471' }); +}); + +test('versions are classified by update and check state', () => { + assert.equal(classifyVersion({ updateAvailable: true, checkState: 'OK' }), 'outdated'); + assert.equal(classifyVersion({ checkState: 'NOT_CHECKED' }), 'checking'); + assert.equal(classifyVersion({ checkState: 'OK' }), 'current'); + assert.equal(classifyVersion({ checkState: 'NO_RELEASES' }), 'current'); + assert.equal(classifyVersion({ checkState: 'ERROR' }), 'unknown'); + assert.equal(classifyVersion({ checkState: 'UNAVAILABLE' }), 'unknown'); + assert.equal(classifyVersion(null), 'unknown'); +}); + +test('the versions panel renders from the pushed versions', () => { + const view = versionsView({ + client: { currentVersion: '0.1.0', latestVersion: '0.2.0', updateAvailable: true, checkState: 'OK', releaseUrl: 'https://example.test/r' }, + server: null, + }); + assert.deepEqual(view.client, { kind: 'outdated', label: 'Update available: v0.2.0', version: 'v0.1.0', href: 'https://example.test/r' }); + assert.deepEqual(view.server, { kind: 'unknown', label: 'No server connected', version: '—', href: null }); +}); + +test('only http release links are rendered', () => { + const view = versionsView({ client: { currentVersion: '0.1.0', latestVersion: '0.2.0', updateAvailable: true, checkState: 'OK', releaseUrl: 'javascript:alert(1)' }, server: null }); + assert.equal(view.client.href, null); +}); + +test('versions that were never delivered read as unable to check', () => { + assert.equal(versionsView(null).server.label, 'Unable to check'); + assert.equal(versionsView(null).client.label, 'Unable to check'); +}); + +test('a server that has not answered yet is connecting, not unreachable', () => { + const view = linkView(loaded({ link: 'CONNECTING', running: null, health: null })); + assert.deepEqual(view.badge, { kind: 'checking', label: 'Connecting…' }); + assert.equal(view.showDetails, false); + assert.equal(view.message, 'Connecting to http://a:38471…'); +}); + +test('a reachable server that is not paired says pairing is required', () => { + const view = linkView(loaded({ pairing: 'REQUIRED', link: 'DEGRADED' })); + assert.deepEqual(view.badge, { kind: 'down', label: 'Pairing required' }); + assert.equal(view.showDetails, false); + assert.match(view.message, /not paired with http:\/\/a:38471/); +}); + +test('a rejected token is reported as such', () => { + const view = linkView(loaded({ pairing: 'REJECTED', link: 'DEGRADED' })); + assert.match(view.message, /rejected this client's token/); +}); + +test('an unreachable server is reported as unreachable before pairing is mentioned', () => { + const view = linkView(loaded({ pairing: 'REQUIRED', link: 'DOWN' })); + assert.equal(view.badge.label, 'Unreachable'); +}); + +test('a listing error only suggests connecting when no server is connected', () => { + const error = new Error('The server rejected this client\'s token, pair it again'); + assert.equal(listingError(error, true), 'The server rejected this client\'s token, pair it again.'); + assert.equal(listingError(error, false), 'The server rejected this client\'s token, pair it again. Connect to a server to view archives.'); +}); + +test('a message that already ends in punctuation gets no second full stop', () => { + const error = new Error('The client or a proxy in front of it did not respond in time.'); + assert.equal(listingError(error, true), 'The client or a proxy in front of it did not respond in time.'); + assert.equal(listingError(error, false), 'The client or a proxy in front of it did not respond in time. Connect to a server to view archives.'); + assert.match(configUnavailableMessage(error), /in time\. Connect to a MediaGarrd server/); +}); + +test('the server configuration message tells an unpaired client to pair and otherwise keeps the reason', () => { + const unpaired = Object.assign(new Error('This client is not paired with the server, pair it first'), { pairing: 'required' }); + assert.equal(configUnavailableMessage(unpaired), 'Pair this client with the server on the Dashboard to manage its configuration.'); + assert.match(configUnavailableMessage(new Error('No active MediaGarrd server selected')), /^No active MediaGarrd server selected\. Connect to a MediaGarrd server/); +}); diff --git a/src/test/js/webhook.test.mjs b/src/test/js/webhook.test.mjs new file mode 100644 index 0000000..96ee940 --- /dev/null +++ b/src/test/js/webhook.test.mjs @@ -0,0 +1,238 @@ +import assert from 'node:assert/strict'; +import { afterEach, beforeEach, test } from 'node:test'; +import { readFileSync } from 'node:fs'; +import { describeStatus, describeTest, initWebhook } from '../../main/resources/static/js/webhook.js'; + +const realFetch = globalThis.fetch; +const savedDocument = globalThis.document; +let calls; +let replies; + +beforeEach(() => { + calls = []; + replies = []; + globalThis.document = { activeElement: null }; + globalThis.fetch = async (url, init) => { + calls.push({ url, method: init.method, headers: init.headers, body: init.body }); + const reply = replies.shift() || { status: 200, body: {} }; + return new Response(JSON.stringify(reply.body), { status: reply.status, headers: new Headers(reply.headers || {}) }); + }; +}); + +afterEach(() => { + globalThis.fetch = realFetch; + if (savedDocument === undefined) delete globalThis.document; + else globalThis.document = savedDocument; +}); + +function button() { + const listeners = {}; + return { disabled: false, listeners, addEventListener(name, fn) { listeners[name] = fn; } }; +} + +function setup() { + const url = { value: '' }; + const label = { textContent: '' }; + const parts = { '[data-webhook-status]': label, '[data-webhook-test]': button(), '[data-webhook-clear]': button(), 'button[type="submit"]': button() }; + const form = { + elements: { url }, + listeners: {}, + addEventListener(name, fn) { this.listeners[name] = fn; }, + querySelector: (selector) => parts[selector], + }; + const messages = []; + const notify = { + ok: (message) => messages.push(['ok', message]), + error: (error) => messages.push(['error', error.message]), + clear: () => messages.push(['clear']), + }; + const view = initWebhook(form, notify); + return { form, url, label, parts, messages, view }; +} + +const submit = (form) => form.listeners.submit({ preventDefault() {} }); +const settled = (messages) => messages.filter((entry) => entry[0] !== 'clear'); + +test('a configured webhook shows only its target and an unset one says so', () => { + assert.equal(describeStatus({ configured: true, target: 'https://discord.com' }), 'Configured: https://discord.com'); + assert.equal(describeStatus({ configured: false, target: null }), 'Not configured'); + assert.equal(describeStatus(null), 'Not configured'); +}); + +test('a test result names the reason when it was not delivered', () => { + assert.deepEqual(describeTest({ delivered: true, status: 200, error: null }), { ok: true, message: 'Test message delivered' }); + assert.deepEqual(describeTest({ delivered: false, status: 404, error: 'Webhook answered 404' }), + { ok: false, message: 'Test message was not delivered: Webhook answered 404' }); + assert.equal(describeTest({ delivered: false }).ok, false); +}); + +test('loading shows the target and never fills the input', async () => { + const { url, label, view } = setup(); + replies.push({ status: 200, body: { configured: true, target: 'https://hooks.slack.com' } }); + await view.load(); + assert.equal(label.textContent, 'Configured: https://hooks.slack.com'); + assert.equal(url.value, ''); + assert.equal(calls[0].method, 'GET'); + assert.equal(calls[0].url, '/api/client/notifications/webhook'); +}); + +test('a failed load says it is unavailable instead of breaking the page', async () => { + const { label, view } = setup(); + replies.push({ status: 404, body: { error: 'Not Found' } }); + await view.load(); + assert.equal(label.textContent, 'Unavailable: Not Found'); +}); + +test('saving sends the typed URL with the CSRF header, clears the input and shows the target', async () => { + const { form, url, label, messages } = setup(); + url.value = ' https://discord.com/api/webhooks/1/SECRET '; + replies.push({ status: 200, body: { configured: true, target: 'https://discord.com' } }); + await submit(form); + assert.equal(calls[0].method, 'PUT'); + assert.equal(calls[0].url, '/api/client/notifications/webhook'); + assert.equal(calls[0].headers['X-MediaGarrd-Request'], '1'); + assert.deepEqual(JSON.parse(calls[0].body), { url: 'https://discord.com/api/webhooks/1/SECRET' }); + assert.equal(url.value, ''); + assert.equal(label.textContent, 'Configured: https://discord.com'); + assert.deepEqual(settled(messages), [['ok', 'Webhook saved']]); +}); + +test('saving an empty field makes no request and points to Clear', async () => { + const { form, messages } = setup(); + await submit(form); + assert.equal(calls.length, 0); + assert.equal(settled(messages)[0][0], 'error'); +}); + +test('a rejected URL shows the server message and keeps the typed text', async () => { + const { form, url, messages } = setup(); + url.value = 'ftp://example.com'; + replies.push({ status: 400, body: { error: 'Webhook URL must use http or https' } }); + await submit(form); + assert.equal(url.value, 'ftp://example.com'); + assert.deepEqual(settled(messages), [['error', 'Webhook URL must use http or https']]); +}); + +test('clearing sends an empty URL', async () => { + const { parts, label, messages } = setup(); + replies.push({ status: 200, body: { configured: false, target: null } }); + await parts['[data-webhook-clear]'].listeners.click(); + assert.deepEqual(JSON.parse(calls[0].body), { url: '' }); + assert.equal(label.textContent, 'Not configured'); + assert.deepEqual(settled(messages), [['ok', 'Webhook cleared']]); +}); + +test('Send test reports a delivered message', async () => { + const { parts, messages } = setup(); + replies.push({ status: 200, body: { delivered: true, status: 200, error: null } }); + await parts['[data-webhook-test]'].listeners.click(); + assert.equal(calls.length, 1); + assert.equal(calls[0].method, 'POST'); + assert.equal(calls[0].url, '/api/client/notifications/webhook/test'); + assert.equal(calls[0].headers['X-MediaGarrd-Request'], '1'); + assert.deepEqual(settled(messages), [['ok', 'Test message delivered']]); +}); + +test('Send test saves a typed URL first and reports a failed delivery', async () => { + const { parts, url, messages } = setup(); + url.value = 'https://example.com/hook'; + replies.push({ status: 200, body: { configured: true, target: 'https://example.com' } }); + replies.push({ status: 200, body: { delivered: false, status: 404, error: 'Webhook answered 404' } }); + await parts['[data-webhook-test]'].listeners.click(); + assert.deepEqual(calls.map((call) => call.method), ['PUT', 'POST']); + assert.deepEqual(settled(messages), [['error', 'Test message was not delivered: Webhook answered 404']]); +}); + +test('a test inside the cooldown shows the wait from the server', async () => { + const { parts, messages } = setup(); + replies.push({ status: 429, body: { error: 'Wait 7 seconds before sending another test' }, headers: { 'Retry-After': '7' } }); + await parts['[data-webhook-test]'].listeners.click(); + assert.deepEqual(settled(messages), [['error', 'Wait 7 seconds before sending another test']]); +}); + +test('the buttons are busy while a request runs and restored after', async () => { + const { parts } = setup(); + const test = parts['[data-webhook-test]']; + let during; + globalThis.fetch = async () => { + during = test.disabled; + return new Response(JSON.stringify({ delivered: true }), { status: 200 }); + }; + await test.listeners.click(); + assert.equal(during, true); + assert.equal(test.disabled, false); +}); + +test('the other buttons are disabled while one action runs and a second action is ignored', async () => { + const { parts } = setup(); + const test = parts['[data-webhook-test]']; + const clear = parts['[data-webhook-clear]']; + let release; + globalThis.fetch = () => new Promise((resolve) => { release = () => resolve(new Response(JSON.stringify({ delivered: true }), { status: 200 })); }); + const running = test.listeners.click(); + assert.equal(clear.disabled, true); + assert.equal(parts['button[type="submit"]'].disabled, true); + const ignored = await clear.listeners.click(); + assert.equal(ignored, undefined); + release(); + await running; + assert.equal(clear.disabled, false); + assert.equal(parts['button[type="submit"]'].disabled, false); +}); + +test('a save that finishes after a server switch does not change the new server label', async () => { + const { form, url, label, view } = setup(); + url.value = 'https://example.com/hook'; + let release; + globalThis.fetch = () => new Promise((resolve) => { release = () => resolve(new Response(JSON.stringify({ configured: true, target: 'https://example.com' }), { status: 200 })); }); + const pending = submit(form); + view.reset(); + release(); + await pending; + assert.equal(label.textContent, 'Checking…'); +}); + +test('switching servers drops the displayed state', () => { + const { url, label, view } = setup(); + url.value = 'https://x.example/y'; + view.reset(); + assert.equal(url.value, ''); + assert.equal(label.textContent, 'Checking…'); +}); + +test('the page has the webhook panel with a never-prefilled url input', () => { + const html = readFileSync(new URL('../../main/resources/static/index.html', import.meta.url), 'utf8'); + assert.match(html, /id="webhookForm"/); + assert.match(html, /id="webhookUrl" name="url" type="url" autocomplete="off"/); + assert.match(html, /data-webhook-test/); + assert.match(html, /data-webhook-clear/); + assert.doesNotMatch(html, /id="webhookUrl"[^>]*value=/); +}); + +test('a note followed by a field group gets the same gap as between field groups', () => { + const css = readFileSync(new URL('../../main/resources/static/css/mediagarrd.css', import.meta.url), 'utf8'); + assert.match(css, /\.note \+ \.field-group \{ margin-top: 0\.75rem; \}/); + const html = readFileSync(new URL('../../main/resources/static/index.html', import.meta.url), 'utf8'); + assert.match(html, /<\/p>\s*
\s*