From 6dbd1adb7e7d2d19fa592342994cedb7685e2d63 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Thu, 19 Nov 2026 15:36:13 -0600 Subject: [PATCH] Added auth, code quality refactors --- .dockerignore | 9 + CHANGELOG | 62 ++ CLAUDE.md | 1 + Dockerfile | 14 +- README.md | 9 +- build.gradle.kts | 7 +- docker-entrypoint.sh | 67 ++ docs/API.md | 43 +- docs/https.md | 94 +++ docs/network.md | 13 +- docs/settings.md | 29 +- docs/testing.md | 9 +- .../mediagarrdclient/MediaGarrd.java | 2 +- ...uration.java => MediaGarrdProperties.java} | 29 +- .../api/ApiExceptionHandler.java | 101 ++- .../mediagarrdclient/api/AuthController.java | 144 +++++ .../mediagarrdclient/api/BodyLimitFilter.java | 129 ++++ .../api/ClientController.java | 38 +- .../ClientEventBroadcaster.java | 54 +- .../api/ClientEventsController.java | 13 +- .../mediagarrdclient/api/CsrfCheck.java | 53 ++ .../api/PairingController.java | 39 ++ .../mediagarrdclient/api/PublicEndpoint.java | 13 + .../api/RequestTooLargeException.java | 10 + .../api/SecurityHeadersFilter.java | 33 + .../api/ServerConfigController.java | 20 +- .../mediagarrdclient/api/SessionGate.java | 71 +++ .../mediagarrdclient/api/WebMvcConfig.java | 20 + .../api/WebhookController.java | 52 ++ .../mediagarrdclient/dto/AuthStatusDto.java | 4 + .../mediagarrdclient/dto/DashboardState.java | 3 +- .../mediagarrdclient/dto/PairRequest.java | 9 + .../mediagarrdclient/dto/PairingCodeDto.java | 6 + .../dto/PairingResultDto.java | 4 + .../mediagarrdclient/dto/PairingState.java | 8 + .../mediagarrdclient/dto/PasswordRequest.java | 9 + .../mediagarrdclient/dto/UnpairResultDto.java | 4 + .../dto/WebhookStatusDto.java | 4 + .../mediagarrdclient/dto/WebhookTestDto.java | 4 + .../dto/WebhookUpdateRequest.java | 9 + .../{api => protocol}/Endpoints.java | 9 +- .../service/BackupPickupService.java | 257 ++++++-- .../service/BackupRunFailedException.java | 8 + .../service/BackupWatcher.java | 109 ++++ .../service/ClientEventPublisher.java | 6 + .../service/ClientPairingService.java | 133 ++++ .../service/ClientStateService.java | 255 ++++++-- .../service/CoalescedRefresh.java | 63 ++ .../service/ConfirmationRefusedException.java | 8 + .../ConfirmationUnavailableException.java | 8 + .../service/ConflictException.java | 8 + .../service/DashboardEvents.java | 31 + .../service/DashboardService.java | 311 ++++----- .../service/DownloadFailedException.java | 12 + .../service/InvalidRequestException.java | 8 + .../service/LinkStateMachine.java | 69 ++ .../service/LoginAttempts.java | 131 ++++ .../service/NoBackupsException.java | 8 + .../service/NotFoundException.java | 8 + .../service/OwnerOnlyFiles.java | 50 ++ .../service/PairingRequiredException.java | 8 + .../service/PairingStatus.java | 56 ++ .../service/PasswordService.java | 158 +++++ .../service/PickupSchedule.java | 49 ++ .../mediagarrdclient/service/QuietFiles.java | 25 + .../service/ReconnectPolicy.java | 47 ++ .../service/ServerApiService.java | 349 ++++++++-- .../service/ServerDiscoveryService.java | 107 +++- .../service/ServerEventStreamService.java | 264 ++++---- .../service/ServerRedirectException.java | 17 + .../service/ServerSelectionService.java | 39 ++ .../mediagarrdclient/service/ServerTls.java | 175 +++++ .../service/ServerTokens.java | 9 + .../mediagarrdclient/service/ServerUrls.java | 55 ++ .../service/ServiceNames.java | 18 + .../service/SessionService.java | 188 ++++++ .../mediagarrdclient/service/SseReader.java | 88 +++ .../service/StoredPairing.java | 9 + .../service/UpdateCheckService.java | 15 +- .../service/UpstreamResponseException.java | 8 + src/main/resources/application.yml | 6 + src/main/resources/static/css/mediagarrd.css | 108 +++- src/main/resources/static/index.html | 187 ++++-- src/main/resources/static/js/api.js | 69 +- src/main/resources/static/js/auth-model.js | 17 + src/main/resources/static/js/auth.js | 151 +++++ src/main/resources/static/js/backups.js | 102 ++- src/main/resources/static/js/busy.js | 11 + src/main/resources/static/js/connection.js | 2 + .../resources/static/js/dashboard-model.js | 11 +- src/main/resources/static/js/events.js | 17 +- src/main/resources/static/js/format.js | 29 +- src/main/resources/static/js/main.js | 106 +++- src/main/resources/static/js/notify.js | 3 + src/main/resources/static/js/pairing-model.js | 31 + src/main/resources/static/js/pairing.js | 94 +++ .../resources/static/js/pickup-interval.js | 7 +- src/main/resources/static/js/server-config.js | 13 +- src/main/resources/static/js/services.js | 20 +- src/main/resources/static/js/settings.js | 9 +- src/main/resources/static/js/view-model.js | 22 +- src/main/resources/static/js/webhook.js | 103 +++ .../mediagarrdclient/MediaGarrdTest.java | 74 --- .../api/ApiExceptionHandlerTest.java | 130 ++++ .../api/AuthControllerConcurrencyTest.java | 151 +++++ .../api/AuthGateFullContextTest.java | 333 ++++++++++ .../api/ClientApiGoldenTest.java | 251 ++++++++ .../api/ClientControllerTest.java | 121 ++-- .../ClientEventBroadcasterTest.java | 85 +-- .../api/ClientEventsControllerTest.java | 28 +- .../mediagarrdclient/api/CsrfCheckTest.java | 94 +++ .../FirstVisitPasswordFullContextTest.java | 108 ++++ .../api/PairingControllerTest.java | 76 +++ .../api/RecordingEmitter.java | 52 ++ .../api/RunningServerTest.java | 163 +++++ .../api/ServerConfigControllerTest.java | 102 +-- .../mediagarrdclient/api/TestCsrfHeader.java | 16 + .../mediagarrdclient/api/TestSession.java | 25 + .../api/WebhookControllerTest.java | 128 ++++ .../mediagarrdclient/golden/Fixtures.java | 23 + .../service/BackupPickupServiceTest.java | 169 +++-- .../service/ClientPairingServiceTest.java | 360 +++++++++++ .../service/ClientStateServiceTest.java | 255 +++++++- .../service/DashboardServiceTest.java | 240 ++++--- .../service/LoginAttemptsTest.java | 191 ++++++ .../service/MutableClock.java | 43 ++ .../service/PasswordServiceTest.java | 152 +++++ .../service/PickupScheduleTest.java | 68 ++ .../service/ReconnectPolicyTest.java | 58 ++ .../service/RecordingPublisher.java | 68 ++ .../service/ScheduledPickupTest.java | 599 ++++++++++++++++++ .../mediagarrdclient/service/SemVerTest.java | 7 +- .../service/ServerApiServiceTest.java | 403 +++++++++++- .../service/ServerDiscoveryServiceTest.java | 94 ++- .../service/ServerEventStreamServiceTest.java | 468 ++++++++++++-- .../service/ServerPayloadGoldenTest.java | 174 +++++ .../service/ServerTlsTest.java | 202 ++++++ .../service/ServerUrlsTest.java | 34 + .../service/ServiceNamesTest.java | 23 + .../service/SessionServiceTest.java | 104 +++ .../service/SseReaderTest.java | 97 +++ .../StateFileMissingFieldsGoldenTest.java | 80 +++ .../service/StateFilesGoldenTest.java | 91 +++ .../service/UpdateCheckServiceTest.java | 46 +- .../service/VersionServiceTest.java | 41 +- src/test/js/api.test.mjs | 112 ++++ src/test/js/auth-model.test.mjs | 29 + src/test/js/busy.test.mjs | 50 ++ src/test/js/dashboard-model.test.mjs | 27 +- src/test/js/events.test.mjs | 154 +++++ src/test/js/format.test.mjs | 87 +++ src/test/js/notify.test.mjs | 44 ++ src/test/js/pairing-model.test.mjs | 51 ++ src/test/js/view-model.test.mjs | 40 +- src/test/js/webhook.test.mjs | 238 +++++++ .../resources/golden/client/auth-status.json | 1 + src/test/resources/golden/client/backups.json | 1 + .../resources/golden/client/dashboard.json | 1 + .../resources/golden/client/error-4xx.json | 1 + .../resources/golden/client/pairing-code.json | 1 + .../client/pairing-result-deferred.json | 1 + .../golden/client/pairing-result.json | 1 + .../golden/client/pickup-progress.json | 1 + .../resources/golden/client/pickup-start.json | 1 + .../golden/client/server-config.json | 1 + .../resources/golden/client/services.json | 1 + src/test/resources/golden/client/status.json | 1 + .../golden/client/unpair-result.json | 1 + .../golden/client/webhook-status.json | 1 + .../resources/golden/client/webhook-test.json | 1 + .../golden/client/webhook-unset.json | 1 + src/test/resources/golden/disk/password.json | 5 + .../golden/disk/state-no-interval.json | 11 + .../golden/disk/state-null-interval.json | 12 + src/test/resources/golden/disk/state.json | 18 + src/test/resources/golden/server/backups.json | 1 + src/test/resources/golden/server/config.json | 1 + .../resources/golden/server/error-4xx.json | 1 + .../golden/server/error-spring-default.json | 1 + .../golden/server/health-public.json | 1 + .../golden/server/health-status.json | 1 + .../golden/server/pair-response.json | 1 + .../resources/golden/server/pairing-code.json | 1 + .../resources/golden/server/services.json | 1 + src/test/resources/golden/server/version.json | 1 + .../golden/server/webhook-status.json | 1 + .../resources/golden/server/webhook-test.json | 1 + 187 files changed, 11186 insertions(+), 1283 deletions(-) create mode 100644 CLAUDE.md create mode 100755 docker-entrypoint.sh create mode 100644 docs/https.md rename src/main/java/wellatleastitried/mediagarrdclient/{Configuration.java => MediaGarrdProperties.java} (79%) create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/AuthController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/BodyLimitFilter.java rename src/main/java/wellatleastitried/mediagarrdclient/{service => api}/ClientEventBroadcaster.java (77%) create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/CsrfCheck.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/PairingController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/PublicEndpoint.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/RequestTooLargeException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/SecurityHeadersFilter.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/SessionGate.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/WebMvcConfig.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/WebhookController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/AuthStatusDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/PairRequest.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/PairingCodeDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/PairingResultDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/PairingState.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/PasswordRequest.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/UnpairResultDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookStatusDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookTestDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookUpdateRequest.java rename src/main/java/wellatleastitried/mediagarrdclient/{api => protocol}/Endpoints.java (58%) create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunFailedException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/BackupWatcher.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventPublisher.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ClientPairingService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/CoalescedRefresh.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationRefusedException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationUnavailableException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ConflictException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/DashboardEvents.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/DownloadFailedException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/InvalidRequestException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/LinkStateMachine.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/LoginAttempts.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/NoBackupsException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/NotFoundException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/OwnerOnlyFiles.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/PairingRequiredException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/PairingStatus.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/PasswordService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/PickupSchedule.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/QuietFiles.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicy.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServerRedirectException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServerSelectionService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServerTls.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServerTokens.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServerUrls.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServiceNames.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/SessionService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/SseReader.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/StoredPairing.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/UpstreamResponseException.java create mode 100644 src/main/resources/static/js/auth-model.js create mode 100644 src/main/resources/static/js/auth.js create mode 100644 src/main/resources/static/js/busy.js create mode 100644 src/main/resources/static/js/pairing-model.js create mode 100644 src/main/resources/static/js/pairing.js create mode 100644 src/main/resources/static/js/webhook.js delete mode 100644 src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandlerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/AuthControllerConcurrencyTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/AuthGateFullContextTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/ClientApiGoldenTest.java rename src/test/java/wellatleastitried/mediagarrdclient/{service => api}/ClientEventBroadcasterTest.java (81%) create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/CsrfCheckTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/FirstVisitPasswordFullContextTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/PairingControllerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/RecordingEmitter.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/RunningServerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/TestCsrfHeader.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/TestSession.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/WebhookControllerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/golden/Fixtures.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ClientPairingServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/LoginAttemptsTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/MutableClock.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/PasswordServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/PickupScheduleTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicyTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/RecordingPublisher.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ScheduledPickupTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ServerPayloadGoldenTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ServerTlsTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ServerUrlsTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ServiceNamesTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/SessionServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/SseReaderTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/StateFileMissingFieldsGoldenTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/StateFilesGoldenTest.java create mode 100644 src/test/js/api.test.mjs create mode 100644 src/test/js/auth-model.test.mjs create mode 100644 src/test/js/busy.test.mjs create mode 100644 src/test/js/events.test.mjs create mode 100644 src/test/js/format.test.mjs create mode 100644 src/test/js/notify.test.mjs create mode 100644 src/test/js/pairing-model.test.mjs create mode 100644 src/test/js/webhook.test.mjs create mode 100644 src/test/resources/golden/client/auth-status.json create mode 100644 src/test/resources/golden/client/backups.json create mode 100644 src/test/resources/golden/client/dashboard.json create mode 100644 src/test/resources/golden/client/error-4xx.json create mode 100644 src/test/resources/golden/client/pairing-code.json create mode 100644 src/test/resources/golden/client/pairing-result-deferred.json create mode 100644 src/test/resources/golden/client/pairing-result.json create mode 100644 src/test/resources/golden/client/pickup-progress.json create mode 100644 src/test/resources/golden/client/pickup-start.json create mode 100644 src/test/resources/golden/client/server-config.json create mode 100644 src/test/resources/golden/client/services.json create mode 100644 src/test/resources/golden/client/status.json create mode 100644 src/test/resources/golden/client/unpair-result.json create mode 100644 src/test/resources/golden/client/webhook-status.json create mode 100644 src/test/resources/golden/client/webhook-test.json create mode 100644 src/test/resources/golden/client/webhook-unset.json create mode 100644 src/test/resources/golden/disk/password.json create mode 100644 src/test/resources/golden/disk/state-no-interval.json create mode 100644 src/test/resources/golden/disk/state-null-interval.json create mode 100644 src/test/resources/golden/disk/state.json create mode 100644 src/test/resources/golden/server/backups.json create mode 100644 src/test/resources/golden/server/config.json create mode 100644 src/test/resources/golden/server/error-4xx.json create mode 100644 src/test/resources/golden/server/error-spring-default.json create mode 100644 src/test/resources/golden/server/health-public.json create mode 100644 src/test/resources/golden/server/health-status.json create mode 100644 src/test/resources/golden/server/pair-response.json create mode 100644 src/test/resources/golden/server/pairing-code.json create mode 100644 src/test/resources/golden/server/services.json create mode 100644 src/test/resources/golden/server/version.json create mode 100644 src/test/resources/golden/server/webhook-status.json create mode 100644 src/test/resources/golden/server/webhook-test.json diff --git a/.dockerignore b/.dockerignore index dbeb426..5b09deb 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,12 @@ .git +.jj +.claude +.env +ref +bin +.settings +.classpath +.project .github .vscode build @@ -15,4 +23,5 @@ secrets LICENSE README.md CHANGELOG +docker-compose.yml docker-compose.example.yml diff --git a/CHANGELOG b/CHANGELOG index 500ed68..ff7948a 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,67 @@ # 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 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 3be39cf..9b86100 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,8 +3,18 @@ WORKDIR /workspace COPY . . 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/README.md b/README.md index 6b80349..1f6d51b 100644 --- a/README.md +++ b/README.md @@ -6,13 +6,16 @@ Full documentation is on the [MediaGarrd website](https://mediagarrd.github.io/M ## 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 that has finished its first-time setup +- 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 @@ -22,7 +25,9 @@ cp docker-compose.example.yml docker-compose.yml docker compose up --build -d ``` -Then open `http://:8081` and connect to your server by IP or with "Scan Local Network". To connect automatically, add `MEDIAGARRD_SERVER_IP=` to `environment` in `docker-compose.yml`. +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 diff --git a/build.gradle.kts b/build.gradle.kts index 3a1bf34..58d8f94 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,7 +1,7 @@ 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" @@ -13,7 +13,8 @@ repositories { 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") } 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 index 5cf2628..d44ddb4 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1,27 +1,49 @@ # Client API -All endpoints are under `/api/client`. Endpoints that act on the connected server need a server to be selected. Errors are returned as `{"error": "..."}` with a matching status code. +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. | +| `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. | +| `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. | -| `POST /pickup/{id}` | A task id and the archive's details after starting a download of one archive. | +| `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. | @@ -29,8 +51,17 @@ All endpoints are under `/api/client`. Endpoints that act on the connected serve | 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. | +| `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 index deaa7e1..7ef4053 100644 --- a/docs/network.md +++ b/docs/network.md @@ -9,15 +9,20 @@ The client can find MediaGarrd servers in three ways. - 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. +- 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 `:`. 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. +"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 `:`) 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. +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. +- 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 index ba8ef22..19da442 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -5,16 +5,37 @@ Set these in `environment` in `docker-compose.yml`. Durations use ISO-8601, for | 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. Only the initial value: once it is saved in the dashboard, the stored value is used. | +| `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 `:`. See [network.md](./network.md). | +| `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, and pickup interval, inside the container. | -| `CLIENT_DOWNLOAD_DIRECTORY` | `/var/lib/mediagarrd/downloads` | Where downloaded archives are saved, inside the container. | +| `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 index 3b33b9a..adefa5e 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -3,17 +3,18 @@ `make test` runs both the Java tests and the browser tests. ## Browser tests -The browser tests cover the pure modules in `src/main/resources/static/js`: -- `dashboard-model.js`: how events change the dashboard state, and when the archive list reloads. -- `view-model.js`: how the connection state, known servers, and versions are rendered. -- `reachability.js`: when the client counts as unreachable. +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/src/main/java/wellatleastitried/mediagarrdclient/MediaGarrd.java b/src/main/java/wellatleastitried/mediagarrdclient/MediaGarrd.java index 5db0cd5..36304ee 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/MediaGarrd.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/MediaGarrd.java @@ -7,7 +7,7 @@ @SpringBootApplication @EnableScheduling -@EnableConfigurationProperties(Configuration.class) +@EnableConfigurationProperties(MediaGarrdProperties.class) public class MediaGarrd { public static void main(String[] args) { diff --git a/src/main/java/wellatleastitried/mediagarrdclient/Configuration.java b/src/main/java/wellatleastitried/mediagarrdclient/MediaGarrdProperties.java similarity index 79% rename from src/main/java/wellatleastitried/mediagarrdclient/Configuration.java rename to src/main/java/wellatleastitried/mediagarrdclient/MediaGarrdProperties.java index 29bba9a..fb983fc 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/Configuration.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/MediaGarrdProperties.java @@ -5,7 +5,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "mediagarrd.client") -public class Configuration { +public class MediaGarrdProperties { private String stateFile = "/var/lib/mediagarrd/client/state.json"; private String downloadDirectory = "/var/lib/mediagarrd/downloads"; @@ -16,6 +16,9 @@ public class Configuration { private String githubApiBaseUrl = "https://api.github.com"; private Duration updateCheckInterval = Duration.ofHours(24); private Duration backupRunTimeout = Duration.ofHours(6); + private String serverCa = ""; + private String password = ""; + private boolean resetPassword; public String getStateFile() { return stateFile; @@ -88,4 +91,28 @@ public Duration getBackupRunTimeout() { public void setBackupRunTimeout(Duration backupRunTimeout) { this.backupRunTimeout = backupRunTimeout; } + + public String getServerCa() { + return serverCa; + } + + public void setServerCa(String serverCa) { + this.serverCa = serverCa; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public boolean isResetPassword() { + return resetPassword; + } + + public void setResetPassword(boolean resetPassword) { + this.resetPassword = resetPassword; + } } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandler.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandler.java index 4108c86..dc815e7 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandler.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandler.java @@ -5,18 +5,28 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.ErrorResponse; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestClientResponseException; -import org.springframework.web.server.ResponseStatusException; +import jakarta.servlet.ServletException; + +import wellatleastitried.mediagarrdclient.service.BackupRunFailedException; import wellatleastitried.mediagarrdclient.service.BackupRunTimeoutException; +import wellatleastitried.mediagarrdclient.service.ConflictException; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; +import wellatleastitried.mediagarrdclient.service.NotFoundException; +import wellatleastitried.mediagarrdclient.service.PairingRequiredException; import wellatleastitried.mediagarrdclient.service.RequestTimeouts; +import wellatleastitried.mediagarrdclient.service.ServerRedirectException; +import wellatleastitried.mediagarrdclient.service.UpstreamResponseException; @RestControllerAdvice public class ApiExceptionHandler { @@ -28,17 +38,50 @@ record ServerError(String error) { @ExceptionHandler(RestClientResponseException.class) public ResponseEntity> serverRejected(RestClientResponseException e) { + int status = e.getStatusCode().value(); String message = null; - try { - ServerError body = e.getResponseBodyAs(ServerError.class); - message = body == null ? null : body.error(); - } catch (RuntimeException ignored) { + 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 " + e.getStatusCode().value() : message; + 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()); @@ -55,27 +98,51 @@ public ResponseEntity> serverUnreachable(ResourceAccessExcep return error(HttpStatus.BAD_GATEWAY, "MediaGarrd server is unreachable"); } - @ExceptionHandler(ResponseStatusException.class) - public ResponseEntity> rejected(ResponseStatusException e) { - LOGGER.warn("Rejected request: {}", e.getReason()); - return error(e.getStatusCode(), e.getReason()); + @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({IllegalArgumentException.class, IllegalStateException.class}) - public ResponseEntity> failed(RuntimeException e) { - HttpStatus status = e instanceof IllegalArgumentException ? HttpStatus.BAD_REQUEST : HttpStatus.INTERNAL_SERVER_ERROR; - if (status.is5xxServerError()) { - LOGGER.error("Request failed: {}", e.getMessage()); - } else { + @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 error(status, e.getMessage()); + return false; } private static ResponseEntity> error(HttpStatusCode status, String message) { 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 index f1ea456..f6ca375 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java @@ -1,6 +1,5 @@ package wellatleastitried.mediagarrdclient.api; -import java.net.URI; import java.util.List; import org.springframework.web.bind.annotation.GetMapping; @@ -23,6 +22,7 @@ import wellatleastitried.mediagarrdclient.service.DashboardService; import wellatleastitried.mediagarrdclient.service.ServerApiService; import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; +import wellatleastitried.mediagarrdclient.service.ServerSelectionService; @RestController @RequestMapping("/api/client") @@ -33,19 +33,22 @@ public class ClientController { 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 + DashboardService dashboardService, + ServerSelectionService selectionService ) { this.stateService = stateService; this.discoveryService = discoveryService; this.serverApiService = serverApiService; this.pickupService = pickupService; this.dashboardService = dashboardService; + this.selectionService = selectionService; } @GetMapping("/status") @@ -67,20 +70,7 @@ public List discover() { @PutMapping("/server") public ClientStatusDto setServer(@RequestBody ServerSelectionRequest request) { - if (!isBlank(request.serverUrl())) { - stateService.setActiveServer(normalizeServerUrl(request.serverUrl())); - return currentStatus(); - } - if (isBlank(request.serverIp())) { - throw new IllegalArgumentException("Either serverUrl or serverIp must be provided"); - } - Integer port = request.serverPort(); - if (port != null && (port < 1 || port > 65535)) { - throw new IllegalArgumentException("serverPort must be between 1 and 65535"); - } - String resolved = discoveryService.resolveServerByIp(request.serverIp(), port) - .orElseThrow(() -> new IllegalArgumentException("No MediaGarrd server found at " + request.serverIp().trim())); - stateService.setActiveServer(resolved); + selectionService.select(request); return currentStatus(); } @@ -118,20 +108,4 @@ public ClientStatusDto updatePickupInterval(@RequestBody IntervalUpdateRequest r private ClientStatusDto currentStatus() { return new ClientStatusDto(stateService.getActiveServer(), stateService.getPickupInterval(), stateService.getKnownServers()); } - - static String normalizeServerUrl(String serverUrl) { - String trimmed = serverUrl.trim().replaceAll("/+$", ""); - try { - URI uri = URI.create(trimmed); - if (("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) && !isBlank(uri.getHost())) { - return trimmed; - } - } catch (IllegalArgumentException ignored) { - } - throw new IllegalArgumentException("serverUrl must be an http:// or https:// URL: " + serverUrl); - } - - private static boolean isBlank(String value) { - return value == null || value.isBlank(); - } } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcaster.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcaster.java similarity index 77% rename from src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcaster.java rename to src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcaster.java index 15d38e1..dcc4ad3 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcaster.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcaster.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrdclient.service; +package wellatleastitried.mediagarrdclient.api; import java.io.IOException; import java.time.Duration; @@ -12,6 +12,7 @@ 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; @@ -19,11 +20,13 @@ 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 { +public class ClientEventBroadcaster implements ClientEventPublisher { private static final Logger LOGGER = LoggerFactory.getLogger(ClientEventBroadcaster.class); private static final Duration PING_INTERVAL = Duration.ofSeconds(20); @@ -40,11 +43,13 @@ public class ClientEventBroadcaster { 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) { + private Subscriber(SseEmitter emitter, String sessionKey) { this.emitter = emitter; + this.sessionKey = sessionKey; } private boolean offer(ClientEvent message) { @@ -70,7 +75,7 @@ private void run() { if (closed || polled == CLOSE) { break; } - if (polled == null && System.nanoTime() >= deadline) { + if (polled == null && (System.nanoTime() >= deadline || sessionKey != null && !sessionActive.test(sessionKey))) { break; } ClientEvent message = polled == null ? PING : polled; @@ -106,13 +111,15 @@ private void run() { 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() { - this(PING_INTERVAL, MAX_SUBSCRIBERS, QUEUE_CAPACITY, STREAM_LIFETIME, EMITTER_TIMEOUT, writerThreads(), SseEmitter::new); + 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( @@ -124,6 +131,20 @@ public ClientEventBroadcaster() { 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; @@ -139,8 +160,12 @@ private static ThreadFactory writerThreads() { } 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); + Subscriber subscriber = new Subscriber(emitter, sessionKey); Thread writer = threadFactory.newThread(subscriber::run); synchronized (lock) { if (shutdown || subscribers.size() >= maxSubscribers) { @@ -156,12 +181,25 @@ public Optional subscribe(List initial) { 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(); diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java index cb8d71f..1f2890d 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java @@ -4,7 +4,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.http.CacheControl; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; @@ -15,7 +14,9 @@ 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") @@ -24,16 +25,18 @@ public class ClientEventsController { private static final Logger LOGGER = LoggerFactory.getLogger(ClientEventsController.class); private final DashboardService dashboard; + private final ClientEventBroadcaster broadcaster; - public ClientEventsController(DashboardService dashboard) { + public ClientEventsController(DashboardService dashboard, ClientEventBroadcaster broadcaster) { this.dashboard = dashboard; + this.broadcaster = broadcaster; } @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) - public ResponseEntity events() { - return dashboard.subscribe() + public ResponseEntity events(HttpServletRequest request) { + String sessionKey = SessionService.keyOf(SessionGate.sessionToken(request)); + return dashboard.subscribe(initial -> broadcaster.subscribe(sessionKey, initial)) .map(emitter -> ResponseEntity.ok() - .cacheControl(CacheControl.noCache()) .header("X-Accel-Buffering", "no") .body(emitter)) .orElseGet(() -> ResponseEntity.status(503).build()); 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 index 642ca4d..7fd7361 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java @@ -1,5 +1,6 @@ package wellatleastitried.mediagarrdclient.api; +import java.time.Duration; import java.util.List; import org.slf4j.Logger; @@ -19,7 +20,9 @@ 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") @@ -27,6 +30,10 @@ 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; @@ -38,13 +45,14 @@ public ServerConfigController(ClientStateService stateService, ServerApiService @GetMapping("/server-config") public ServerConfigDto serverConfig() { String activeServer = stateService.requireActiveServer(); - LOGGER.info("GET /api/client/server-config, forwarding to {}", activeServer); + 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) { @@ -54,10 +62,16 @@ public ServerConfigDto updateServerConfig(@RequestBody ServerConfigDto request) 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.info("GET /api/client/services, forwarding to {}", activeServer); + LOGGER.debug("GET /api/client/services, forwarding to {}", activeServer); return serverApiService.listServices(activeServer); } @@ -71,6 +85,7 @@ public ServiceDto addService(@RequestBody ServiceDto 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); @@ -79,6 +94,7 @@ public ServiceDto updateService(@PathVariable String name, @RequestBody ServiceD @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/mediagarrdclient/dto/DashboardState.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/DashboardState.java index b961cec..7018c9e 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/dto/DashboardState.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/DashboardState.java @@ -8,6 +8,7 @@ public record DashboardState( LinkState link, Boolean running, HealthSummary health, - VersionsDto versions + VersionsDto versions, + PairingState pairing ) { } 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/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/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/api/Endpoints.java b/src/main/java/wellatleastitried/mediagarrdclient/protocol/Endpoints.java similarity index 58% rename from src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java rename to src/main/java/wellatleastitried/mediagarrdclient/protocol/Endpoints.java index 798318a..f59adf9 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/protocol/Endpoints.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrdclient.api; +package wellatleastitried.mediagarrdclient.protocol; public enum Endpoints { @@ -9,7 +9,12 @@ public enum Endpoints { SERVER_SCHEDULE("/api/v1/schedule"), SERVER_CONFIG("/api/v1/config"), SERVER_SERVICES("/api/v1/services"), - SERVER_EVENTS("/api/v1/events"); + 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; diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java index cee0e67..7b379c1 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java @@ -2,6 +2,7 @@ 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; @@ -9,21 +10,26 @@ 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.http.HttpStatus; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; -import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClientResponseException; +import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; import wellatleastitried.mediagarrdclient.dto.BackupDto; import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; import wellatleastitried.mediagarrdclient.dto.PickupStartDto; @@ -34,13 +40,16 @@ 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; @@ -48,8 +57,9 @@ private final class PickupTask { private volatile String error; private volatile Instant finishedAt; - private PickupTask(BackupDto backup) { + private PickupTask(BackupDto backup, boolean latest) { this.backup = backup; + this.latest = latest; this.totalBytes = backup.sizeBytes(); } @@ -81,70 +91,127 @@ private PickupProgressDto progress() { } } - private final Configuration configuration; + 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 volatile Instant nextPickup; + private final PickupSchedule schedule; @Autowired - public BackupPickupService(Configuration configuration, ClientStateService clientStateService, ServerApiService serverApiService) { + public BackupPickupService(MediaGarrdProperties configuration, ClientStateService clientStateService, ServerApiService serverApiService) { this(configuration, clientStateService, serverApiService, Clock.systemUTC()); } - BackupPickupService(Configuration configuration, ClientStateService clientStateService, ServerApiService serverApiService, Clock clock) { + BackupPickupService(MediaGarrdProperties configuration, ClientStateService clientStateService, ServerApiService serverApiService, Clock clock) { this.configuration = configuration; this.clientStateService = clientStateService; this.serverApiService = serverApiService; this.clock = clock; - this.nextPickup = clock.instant().plus(clientStateService.getPickupInterval()); + this.schedule = new PickupSchedule(clock); + clientStateService.addActiveServerListener(server -> noBackupsReported.set(false)); + } + + @PostConstruct + void removeStalePartFilesAtStartup() { + removeStalePartFiles(downloadsDirectory()); } @Scheduled(fixedDelay = 60_000) public void scheduledPickup() { - Instant now = clock.instant(); - if (now.isBefore(nextPickup)) { + if (!paired() || !schedule.due(clientStateService.getLastPickupAt(), clientStateService.getPickupInterval()) + || !scheduledRunning.compareAndSet(false, true)) { return; } - nextPickup = now.plus(clientStateService.getPickupInterval()); try { - LOGGER.info("Scheduled pickup saved {}, next pickup at {}", pickupLatestAuto(), nextPickup); + 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) { - LOGGER.warn("Scheduled pickup failed, next attempt at {}: {}", nextPickup, e.getMessage()); + 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); - nextPickup = clock.instant().plus(updated); + 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))); + return startPickupTask(server, latest(serverApiService.listBackups(server)), true); } public PickupStartDto startPickupByIdTask(String backupId) { String server = clientStateService.requireActiveServer(); - BackupDto backup = serverApiService.listBackups(server).stream() + List backups = serverApiService.listBackups(server); + BackupDto backup = backups.stream() .filter(candidate -> candidate.id().equals(backupId)) .findFirst() - .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Backup not found: " + backupId)); - return startPickupTask(server, backup); + .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 ResponseStatusException(HttpStatus.NOT_FOUND, "Pickup task not found: " + taskId); + throw new NotFoundException("Pickup task not found: " + taskId); } return task.progress(); } - private synchronized PickupStartDto startPickupTask(String server, BackupDto backup) { + 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())) @@ -155,20 +222,37 @@ private synchronized PickupStartDto startPickupTask(String server, BackupDto bac return running.started(); } - PickupTask task = new PickupTask(backup); - tasks.put(task.taskId, task); 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 { - executor.submit(() -> download(server, inside(downloads, backup.fileName()), task)); + 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) -> { @@ -177,14 +261,31 @@ private void download(String server, Path destination, PickupTask task) { 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(e.getMessage()); - LOGGER.warn("Pickup task {} failed for backup {}: {}", task.taskId, task.backup.id(), e.getMessage()); + 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)); @@ -194,19 +295,72 @@ 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 downloaded = serverApiService.downloadById(server, latest.id(), inside(downloads, autoFileName(latest)), null); - deleteIfSameSize(inside(downloads, latest.fileName()), latest); - if (backups.size() > 1) { - deleteQuietly(inside(downloads, autoFileName(backups.get(1)))); + 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()); } - return downloaded; } private Path existingCopy(Path downloads, BackupDto backup) { @@ -217,9 +371,29 @@ private Path existingCopy(Path downloads, BackupDto backup) { .orElse(null); } - private void deleteIfSameSize(Path path, BackupDto backup) { - if (hasSize(path, backup.sizeBytes())) { - deleteQuietly(path); + 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); } } @@ -232,19 +406,9 @@ private static boolean hasSize(Path path, long size) { } } - private static void deleteQuietly(Path path) { - try { - if (Files.deleteIfExists(path)) { - LOGGER.info("Removed superseded download {}", path.getFileName()); - } - } catch (IOException e) { - LOGGER.warn("Could not remove {}: {}", path, e.getMessage()); - } - } - private static BackupDto latest(List backups) { if (backups.isEmpty()) { - throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No backups found on server"); + throw new NoBackupsException(); } return backups.getFirst(); } @@ -259,7 +423,7 @@ private static String autoFileName(BackupDto backup) { private static Path inside(Path downloads, String fileName) { Path path = downloads.resolve(fileName).normalize(); if (!downloads.equals(path.getParent())) { - throw new IllegalArgumentException("Backup file name must not leave the download directory: " + fileName); + throw new InvalidRequestException("Backup file name must not leave the download directory: " + fileName); } return path; } @@ -271,5 +435,6 @@ private Path downloadsDirectory() { @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/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/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 index d6cb990..3c07c59 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java @@ -4,34 +4,44 @@ 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.http.HttpStatus; import org.springframework.stereotype.Service; -import org.springframework.web.server.ResponseStatusException; +import org.springframework.util.StringUtils; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.core.JacksonException; +import tools.jackson.core.exc.JacksonIOException; +import tools.jackson.databind.ObjectMapper; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; @Service -public class ClientStateService { +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, List knownServers) { + record ClientState(String activeServer, long pickupIntervalSeconds, Instant lastPickupAt, List knownServers, Map pairings) { } private final Path statePath; @@ -39,15 +49,24 @@ record ClientState(String activeServer, long pickupIntervalSeconds, List 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(Configuration configuration, ObjectMapper mapper) { + public ClientStateService(MediaGarrdProperties configuration, ObjectMapper mapper) { this.statePath = Path.of(configuration.getStateFile()).toAbsolutePath().normalize(); this.mapper = mapper; - this.pickupInterval = valid(configuration.getPickupInterval()) ? configuration.getPickupInterval() : DEFAULT_PICKUP_INTERVAL; + 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={}", activeServer, pickupInterval, knownServers); + LOGGER.info("Client state: activeServer={}, pickupInterval={}, knownServers={}, pairedServers={}", activeServer, pickupInterval, knownServers, pairings.size()); } public synchronized String getActiveServer() { @@ -55,8 +74,8 @@ public synchronized String getActiveServer() { } public synchronized String requireActiveServer() { - if (isBlank(activeServer)) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No active MediaGarrd server selected"); + if (!StringUtils.hasText(activeServer)) { + throw new InvalidRequestException("No active MediaGarrd server selected"); } return activeServer; } @@ -65,6 +84,19 @@ 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); } @@ -78,17 +110,22 @@ public void updateKnownServers(List servers) { synchronized (this) { before = activeServer; listBefore = List.copyOf(knownServers); - knownServers.clear(); - knownServers.addAll(servers); - if (isBlank(activeServer)) { - activeServer = knownServers.stream().findFirst().orElse(null); + 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 { - knownServers.add(activeServer); + 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); - save(); } } finally { if (!Objects.equals(before, after)) { @@ -100,18 +137,24 @@ public void updateKnownServers(List servers) { } } - public void setActiveServer(String serverUrl) { + public void setActiveServer(String requested) { + String serverUrl = ServerUrls.normalize(requested); boolean changed = false; boolean listChanged = false; try { synchronized (this) { - LOGGER.info("Active server changed: {} -> {}", activeServer, serverUrl); changed = !Objects.equals(activeServer, serverUrl); - activeServer = serverUrl; - if (!isBlank(serverUrl)) { - listChanged = knownServers.add(serverUrl); + Set nextKnown = new LinkedHashSet<>(knownServers); + if (StringUtils.hasText(serverUrl)) { + listChanged = nextKnown.add(serverUrl); } - save(); + 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) { @@ -123,19 +166,25 @@ public void setActiveServer(String serverUrl) { } } - public void setActiveServerIfBlank(String serverUrl) { + public void setActiveServerIfBlank(String requested) { + String serverUrl = ServerUrls.normalize(requested); boolean changed = false; boolean listChanged = false; try { synchronized (this) { - if (!isBlank(activeServer) || isBlank(serverUrl)) { + 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; - listChanged = knownServers.add(serverUrl); - save(); + knownServers.clear(); + knownServers.addAll(nextKnown); } } finally { if (changed) { @@ -147,6 +196,10 @@ public void setActiveServerIfBlank(String serverUrl) { } } + public synchronized boolean isKnownServer(String serverUrl) { + return knownServers.contains(ServerUrls.normalize(serverUrl)); + } + public void addActiveServerListener(Consumer listener) { activeServerListeners.add(listener); } @@ -155,6 +208,78 @@ 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 { @@ -176,12 +301,15 @@ private void notifyActiveServerListeners(String serverUrl) { } public synchronized Duration setPickupInterval(Duration interval) { - if (!valid(interval)) { - throw new IllegalArgumentException("Pickup interval must be a positive duration"); + 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); - save(); return interval; } @@ -190,38 +318,75 @@ private void load() { 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) { - knownServers.addAll(state.knownServers()); + state.knownServers().stream().map(ServerUrls::normalize).forEach(knownServers::add); } - activeServer = isBlank(state.activeServer()) ? knownServers.stream().findFirst().orElse(null) : state.activeServer(); + 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); } - } catch (IOException e) { - LOGGER.warn("Could not read state from {}, starting with defaults: {}", statePath, e.getMessage()); + 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 save() { + private void moveAside(Exception cause) { + Path aside = statePath.resolveSibling(statePath.getFileName() + ".corrupt-" + ASIDE_STAMP.format(Instant.now())); try { - Files.createDirectories(statePath.getParent()); - Path temp = statePath.resolveSibling(statePath.getFileName() + ".tmp"); - ClientState state = new ClientState(activeServer == null ? "" : activeServer, pickupInterval.toSeconds(), new ArrayList<>(knownServers)); - mapper.writerWithDefaultPrettyPrinter().writeValue(temp.toFile(), state); - Files.move(temp, statePath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + 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) { - throw new IllegalStateException("Failed to save client state to " + statePath, 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 static boolean valid(Duration duration) { - return duration != null && duration.isPositive(); + 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 isBlank(String value) { - return value == null || value.isBlank(); + 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 index a20689b..9984534 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardService.java @@ -8,10 +8,12 @@ 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.RejectedExecutionException; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; @@ -19,17 +21,15 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; -import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.databind.ObjectMapper; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; -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.ServerStatusDto; @Service @@ -39,82 +39,30 @@ public class DashboardService { private static final Duration POLL_INTERVAL = Duration.ofSeconds(7); private static final Duration CATCH_ALL_INTERVAL = Duration.ofSeconds(60); - private final class Refresh { - - private final Runnable work; - private boolean inFlight; - private boolean again; - - private Refresh(Runnable work) { - this.work = work; - } - - private void request() { - synchronized (lock) { - if (inFlight) { - again = true; - return; - } - inFlight = true; - } - try { - executor.execute(this::loop); - } catch (RejectedExecutionException e) { - synchronized (lock) { - inFlight = false; - } - } - } - - 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); - } - - private boolean busy() { - return inFlight; - } - } - private final ClientStateService stateService; - private final ClientEventBroadcaster broadcaster; - private final ServerApiService serverApiService; private final VersionService versionService; private final UpdateCheckService updateCheckService; - private final ObjectMapper mapper; + private final ServerApiService serverApiService; private final Executor executor; private final Clock clock; private final Object lock = new Object(); - private final Refresh healthRefresh = new Refresh(this::fetchHealth); - private final Refresh versionRefresh = new Refresh(this::fetchVersion); - private final Refresh backupsRefresh = new Refresh(this::fetchBackups); + 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 LinkState link = LinkState.DOWN; - private Boolean running; private HealthSummary health; private Instant healthFetchedAt; - private List backupsSeen; - private Instant backupsCheckedAt; private long epoch; @Autowired public DashboardService( ClientStateService stateService, - ClientEventBroadcaster broadcaster, + ClientEventPublisher broadcaster, ServerApiService serverApiService, VersionService versionService, UpdateCheckService updateCheckService, @@ -125,7 +73,7 @@ public DashboardService( DashboardService( ClientStateService stateService, - ClientEventBroadcaster broadcaster, + ClientEventPublisher broadcaster, ServerApiService serverApiService, VersionService versionService, UpdateCheckService updateCheckService, @@ -134,13 +82,17 @@ public DashboardService( Clock clock ) { this.stateService = stateService; - this.broadcaster = broadcaster; this.serverApiService = serverApiService; this.versionService = versionService; this.updateCheckService = updateCheckService; - this.mapper = mapper; 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() { @@ -151,6 +103,9 @@ private static ExecutorService refreshThreads() { @PostConstruct void start() { stateService.addKnownServersListener(this::sync); + stateService.addActiveServerListener(ignored -> sync()); + stateService.addPairingListener(this::pairingChanged); + serverApiService.addTokenRejectedListener(this::pairingRejected); updateCheckService.addStatusListener(ignored -> publishVersions()); sync(); } @@ -168,31 +123,19 @@ public DashboardState state() { } } - public Optional subscribe() { + public Optional subscribe(Function, Optional> registration) { synchronized (lock) { - return broadcaster.subscribe(List.of(new ClientEvent("snapshot", json(snapshot())))); + return registration.apply(List.of(new ClientEvent("snapshot", events.json(snapshot())))); } } void sync() { synchronized (lock) { - String active = normalize(stateService.getActiveServer()); + String active = ServerUrls.nullIfBlank(stateService.getActiveServer()); List known = stateService.getKnownServers(); if (!Objects.equals(active, activeServer)) { - activeServer = active; knownServers = known; - link = active == null ? LinkState.DOWN : LinkState.CONNECTING; - running = null; - health = null; - healthFetchedAt = null; - backupsSeen = null; - backupsCheckedAt = null; - epoch++; - versionService.select(active); - broadcaster.publish("snapshot", json(snapshot())); - if (active != null) { - healthRefresh.request(); - } + reset(active); } else if (!known.equals(knownServers)) { knownServers = known; publishServers(); @@ -200,12 +143,44 @@ void sync() { } } + 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 = link == LinkState.DOWN; + boolean wasDown = links.link() == LinkState.DOWN; setLink(LinkState.LIVE); healthRefresh.request(); if (versionService.invalidate(wasDown)) { @@ -229,15 +204,15 @@ void runEvent(String server, String name, String data, boolean runningNow) { if (!Objects.equals(server, activeServer)) { return; } - running = runningNow; - broadcaster.publish(name, data); + links.setRunning(runningNow); + events.publishRaw(name, data); } } void backupsChanged(String server, String data) { synchronized (lock) { if (Objects.equals(server, activeServer)) { - broadcaster.publish("backups-changed", data); + events.publishRaw("backups-changed", data); } } } @@ -256,20 +231,24 @@ void tick() { if (activeServer == null) { return; } - Duration limit = link == LinkState.LIVE ? CATCH_ALL_INTERVAL : POLL_INTERVAL; + 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 (reachable() && !versionRefresh.busy() && versionService.needsRefresh()) { + if (links.reachable() && !versionRefresh.busy() && versionService.needsRefresh()) { versionRefresh.request(); } - if (link == LinkState.DEGRADED && !backupsRefresh.busy() && (backupsCheckedAt == null || Duration.between(backupsCheckedAt, clock.instant()).compareTo(CATCH_ALL_INTERVAL) >= 0)) { - backupsRefresh.request(); + if (links.link() == LinkState.DEGRADED) { + backups.requestWhenDue(); } } } + public void addRecoveryListener(Consumer listener) { + recoveryListeners.add(listener); + } + private void fetchHealth() { String server; long expected; @@ -281,80 +260,68 @@ private void fetchHealth() { 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); + applyHealth(expected, status, tokenRejected); } - private void applyHealth(long expected, ServerStatusDto status) { + private void applyHealth(long expected, ServerStatusDto status, boolean tokenRejected) { + String cleared; synchronized (lock) { - if (expected != epoch) { - return; - } - healthFetchedAt = clock.instant(); - if (status == null) { - if (link != LinkState.LIVE) { - setLink(LinkState.DOWN); - if (versionService.markUnreachable()) { - broadcaster.publish("versions", json(versionService.versions())); - } - } - return; - } - HealthSummary summary = new HealthSummary(status.backupInterval(), status.backupRetentionCount()); - if (!summary.equals(health)) { - health = summary; - broadcaster.publish("config", json(summary)); - } - if (link != LinkState.LIVE) { - boolean recovered = link != LinkState.DEGRADED; - boolean wasDown = link == LinkState.DOWN; - setLink(LinkState.DEGRADED); - setPolledRunning(status.running()); - if (recovered && versionService.invalidate(wasDown)) { - versionRefresh.request(); - } + cleared = applyHealthLocked(expected, status, tokenRejected); + } + if (cleared != null) { + for (Consumer listener : recoveryListeners) { + listener.accept(cleared); } } } - private void fetchBackups() { - String server; - long expected; - synchronized (lock) { - server = activeServer; - expected = epoch; + private String applyHealthLocked(long expected, ServerStatusDto status, boolean tokenRejected) { + String cleared = null; + if (expected != epoch) { + return null; } - if (server == null) { - return; + healthFetchedAt = clock.instant(); + if (status != null && pairingStatus.observe(tokenRejected, activeServer)) { + cleared = activeServer; } - List listed; - try { - listed = serverApiService.listBackups(server); - } catch (RuntimeException e) { - LOGGER.debug("{} did not list its backups: {}", server, e.getMessage()); - listed = null; + 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; } - synchronized (lock) { - if (expected != epoch || link != LinkState.DEGRADED) { - return; + if (detailed) { + HealthSummary summary = new HealthSummary(status.backupInterval(), status.backupRetentionCount()); + if (!summary.equals(health)) { + health = summary; + events.publish("config", summary); } - backupsCheckedAt = clock.instant(); - if (listed == null) { - return; + } + 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 (backupsSeen != null && !listed.equals(backupsSeen)) { - broadcaster.publish("backups-changed", json(Map.of("at", clock.instant().toString()))); + if (recovered && versionService.invalidate(wasDown)) { + versionRefresh.request(); } - backupsSeen = listed; } - } - - private boolean reachable() { - return link == LinkState.LIVE || link == LinkState.DEGRADED; + return cleared; } private void fetchVersion() { @@ -365,7 +332,7 @@ private void fetchVersion() { private void publishVersions() { synchronized (lock) { - broadcaster.publish("versions", json(versionService.versions())); + events.publish("versions", versionService.versions()); } } @@ -373,54 +340,16 @@ private void publishServers() { Map payload = new LinkedHashMap<>(); payload.put("knownServers", knownServers); payload.put("activeServer", activeServer); - broadcaster.publish("servers", json(payload)); + events.publish("servers", payload); } private void setLink(LinkState next) { - if (link == next) { - return; + if (links.setLink(next, activeServer) && next != LinkState.DEGRADED) { + backups.forget(); } - link = next; - if (!reachable()) { - running = null; - } - if (next != LinkState.DEGRADED) { - backupsSeen = null; - backupsCheckedAt = null; - } - Map payload = new LinkedHashMap<>(); - payload.put("server", activeServer == null ? "" : activeServer); - payload.put("state", next); - broadcaster.publish("link", json(payload)); - } - - private void setPolledRunning(boolean polled) { - if (Boolean.valueOf(polled).equals(running)) { - return; - } - if (Boolean.TRUE.equals(running) && !polled) { - backupsSeen = null; - } - running = polled; - Map payload = new LinkedHashMap<>(); - payload.put("running", polled); - payload.put("at", clock.instant().toString()); - broadcaster.publish("state", json(payload)); } private DashboardState snapshot() { - return new DashboardState(activeServer, knownServers, link, running, health, versionService.versions()); - } - - private String json(Object payload) { - try { - return mapper.writeValueAsString(payload); - } catch (JsonProcessingException e) { - throw new IllegalStateException(e); - } - } - - private static String normalize(String url) { - return url == null || url.isBlank() ? null : url; + 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/ServerApiService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java index afa9eb8..1b623cd 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java @@ -15,25 +15,44 @@ 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 wellatleastitried.mediagarrdclient.Configuration; -import wellatleastitried.mediagarrdclient.api.Endpoints; +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 { @@ -44,25 +63,44 @@ public interface DownloadProgressListener { } 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 final HttpClient httpClient = HttpClient.newBuilder() - .connectTimeout(CONNECT_TIMEOUT) - .followRedirects(HttpClient.Redirect.NORMAL) - .build(); - private final RestClient healthClient = restClient(HEALTH_TIMEOUT); - private final RestClient restClient = restClient(REQUEST_TIMEOUT); + 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(Configuration properties) { - this(checked(properties.getBackupRunTimeout())); + public ServerApiService(MediaGarrdProperties properties, ClientStateService stateService, ServerTls tls) { + this(checked(properties.getBackupRunTimeout()), stateService, tls); } private static Duration checked(Duration backupRunTimeout) { @@ -72,8 +110,25 @@ private static Duration checked(Duration backupRunTimeout) { return backupRunTimeout; } - ServerApiService(Duration 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); } @@ -82,29 +137,29 @@ private RestClient restClient(Duration readTimeout) { if (readTimeout != null) { requestFactory.setReadTimeout(readTimeout); } - return RestClient.builder().requestFactory(requestFactory).build(); + return RestClient.builder().requestFactory(requestFactory).configureMessageConverters(converters -> converters.withJsonConverter(JSON)).build(); } public ServerStatusDto health(String serverUrl) { - ServerStatusDto status = healthClient.get() - .uri(serverUrl + Endpoints.SERVER_HEALTH.getPath()) - .retrieve() - .body(ServerStatusDto.class); + 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 healthClient.get() + return checked(healthClient.get() .uri(serverUrl + Endpoints.SERVER_VERSION.getPath()) - .retrieve() + .retrieve()) .body(VersionStatusDto.class); } public List listBackups(String serverUrl) { - List backups = restClient.get() - .uri(serverUrl + Endpoints.SERVER_BACKUPS.getPath()) - .retrieve() + 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; @@ -113,9 +168,7 @@ public List listBackups(String serverUrl) { public void triggerBackup(String serverUrl) { LOGGER.info("Triggering backup on {}", serverUrl); try { - backupRunClient.post() - .uri(serverUrl + Endpoints.SERVER_BACKUP_RUN.getPath()) - .retrieve() + authed(backupRunClient.post().uri(serverUrl + Endpoints.SERVER_BACKUP_RUN.getPath()), serverUrl) .toBodilessEntity(); } catch (ResourceAccessException e) { if (RequestTimeouts.isReadTimeout(e)) { @@ -124,24 +177,37 @@ public void triggerBackup(String serverUrl) { + " 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 restClient.put() + return authed(restClient.put() .uri(serverUrl + Endpoints.SERVER_SCHEDULE.getPath()) .contentType(MediaType.APPLICATION_JSON) - .body(Map.of("backupInterval", interval.toString())) - .retrieve() + .body(Map.of("backupInterval", interval.toString())), serverUrl) .body(ServerStatusDto.class); } public ServerConfigDto serverConfig(String serverUrl) { - return restClient.get() - .uri(serverUrl + Endpoints.SERVER_CONFIG.getPath()) - .retrieve() + return authed(restClient.get().uri(serverUrl + Endpoints.SERVER_CONFIG.getPath()), serverUrl) .body(ServerConfigDto.class); } @@ -150,95 +216,261 @@ public ServerConfigDto updateServerConfig(String serverUrl, String backupLocatio Map body = new HashMap<>(); body.put("backupLocation", backupLocation); body.put("retentionCount", retentionCount); - return restClient.put() + return authed(restClient.put() .uri(serverUrl + Endpoints.SERVER_CONFIG.getPath()) .contentType(MediaType.APPLICATION_JSON) - .body(body) - .retrieve() + .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 = restClient.get() - .uri(serverUrl + Endpoints.SERVER_SERVICES.getPath()) - .retrieve() + 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 restClient.post() + return authed(restClient.post() .uri(serverUrl + Endpoints.SERVER_SERVICES.getPath()) .contentType(MediaType.APPLICATION_JSON) - .body(service) - .retrieve() + .body(service), serverUrl) .body(ServiceDto.class); } public ServiceDto updateService(String serverUrl, String name, ServiceDto service) { LOGGER.info("Updating service {} on {}", name, serverUrl); - return restClient.put() + return authed(restClient.put() .uri(serverUrl + SERVICE_PATH, name) .contentType(MediaType.APPLICATION_JSON) - .body(service) - .retrieve() + .body(service), serverUrl) .body(ServiceDto.class); } public void removeService(String serverUrl, String name) { LOGGER.info("Removing service {} from {}", name, serverUrl); - restClient.delete() - .uri(serverUrl + SERVICE_PATH, name) - .retrieve() + 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 { - HttpResponse response = httpClient.send(HttpRequest.newBuilder(uri).GET().build(), HttpResponse.BodyHandlers.ofInputStream()); + 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 IllegalStateException("Download of backup " + backupId + " failed with HTTP " + response.statusCode()); + throw new DownloadFailedException("Download of backup " + backupId + " failed with HTTP " + response.statusCode()); } - Files.createDirectories(destination.getParent()); + OwnerOnlyFiles.createDirectories(destination.getParent()); long totalBytes = response.headers().firstValueAsLong("Content-Length").orElse(-1L); copy(body, temp, totalBytes, progressListener); } if (!looksLikeZip(temp)) { - throw new IllegalStateException("Server returned non-zip content for backup " + backupId); + 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 IllegalStateException("Download of backup " + backupId + " was interrupted", e); + 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 IllegalStateException("Failed to save backup " + backupId + ": " + e.getMessage(), e); + throw new DownloadFailedException("Failed to download backup " + backupId, e); } finally { - deleteQuietly(temp); + QuietFiles.delete(temp); } } - private static void copy(InputStream in, Path target, long totalBytes, DownloadProgressListener progressListener) throws IOException { - try (OutputStream out = Files.newOutputStream(target)) { + 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); } } @@ -253,11 +485,8 @@ private static boolean looksLikeZip(Path path) throws IOException { && ((header[2] == 3 && header[3] == 4) || (header[2] == 5 && header[3] == 6) || (header[2] == 7 && header[3] == 8)); } - private static void deleteQuietly(Path path) { - try { - Files.deleteIfExists(path); - } catch (IOException e) { - LOGGER.warn("Could not delete {}: {}", path, e.getMessage()); - } + @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 index 83b35db..1086fe9 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java @@ -1,6 +1,7 @@ package wellatleastitried.mediagarrdclient.service; import java.io.IOException; +import java.io.InputStream; import java.net.ConnectException; import java.net.Inet4Address; import java.net.InetAddress; @@ -40,12 +41,13 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; import jakarta.annotation.PreDestroy; -import wellatleastitried.mediagarrdclient.Configuration; -import wellatleastitried.mediagarrdclient.api.Endpoints; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.protocol.Endpoints; @Service public class ServerDiscoveryService { @@ -57,7 +59,9 @@ public class ServerDiscoveryService { 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); @@ -68,13 +72,22 @@ public class ServerDiscoveryService { enum Probe { OPEN, REFUSED, UNREACHABLE } - record Candidate(String host, InetAddress address, int port) { + record Candidate(String scheme, String host, InetAddress address, int port) { + Candidate(String host, InetAddress address, int port) { + this("http", host, address, port); + } + String url() { - return "http://" + (host.contains(":") ? "[" + host + "]" : host) + ":" + port; + String authority = host.contains(":") ? "[" + host + "]" : host; + boolean defaultPort = "https".equals(scheme) && port == HTTPS_PORT; + return scheme + "://" + authority + (defaultPort ? "" : ":" + port); } } - record HostInput(String host, Integer port) { + record HostInput(String scheme, String host, Integer port) { + boolean https() { + return "https".equals(scheme); + } } private record ProbeResult(Probe probe, String server) { @@ -83,24 +96,26 @@ private record ProbeResult(Probe probe, String server) { private record QuickResult(Optional server, boolean hostAlive) { } - private final Configuration configuration; + private final MediaGarrdProperties configuration; private final ClientStateService stateService; private final ObjectMapper mapper; - private final HttpClient httpClient = HttpClient.newBuilder() - .connectTimeout(CONNECT_TIMEOUT.multipliedBy(2)) - .followRedirects(HttpClient.Redirect.NEVER) - .build(); + 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(Configuration configuration, ClientStateService stateService, ObjectMapper mapper) { - this(configuration, stateService, mapper, Executors.newVirtualThreadPerTaskExecutor(), PREFERRED_ATTEMPT_DEADLINE); + public ServerDiscoveryService(MediaGarrdProperties configuration, ClientStateService stateService, ObjectMapper mapper, ServerTls tls) { + this(configuration, stateService, mapper, tls, Executors.newVirtualThreadPerTaskExecutor(), PREFERRED_ATTEMPT_DEADLINE); } - ServerDiscoveryService(Configuration configuration, ClientStateService stateService, ObjectMapper mapper, ExecutorService executor, Duration preferredDeadline) { + 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; @@ -175,7 +190,24 @@ public Optional resolvePreferredServer() { } HostInput input = parseHost(preferred); InetAddress address = input == null ? null : resolve(input.host()); - return address == null ? Optional.empty() : quickResolve(input.host(), address, input.port(), deadline()).server(); + 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) { @@ -186,6 +218,9 @@ public Optional resolveServerByIp(String input, Integer port) { 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()) { @@ -257,22 +292,37 @@ private Probe connect(Candidate candidate, long deadline) { } boolean isMediaGarrdServer(Candidate candidate) { - HttpRequest request = HttpRequest.newBuilder(URI.create(candidate.url() + Endpoints.SERVER_HEALTH.getPath())) - .timeout(HEALTH_TIMEOUT) - .GET() - .build(); + return isMediaGarrdServer(candidate.url()); + } + + public boolean isMediaGarrdServer(String serverUrl) { + HttpRequest request; try { - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - if (response.statusCode() != 200) { - return false; + 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"); } - JsonNode health = mapper.readTree(response.body()); - return health.path("healthy").isBoolean() && health.has("backupInterval"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; - } catch (IOException | IllegalArgumentException e) { - LOGGER.debug("{} is not a MediaGarrd server: {}", candidate.url(), e.getMessage()); + } catch (IOException | IllegalArgumentException | JacksonException e) { + LOGGER.debug("{} is not a MediaGarrd server: {}", serverUrl, e.getMessage()); return false; } } @@ -332,7 +382,8 @@ static HostInput parseHost(String input) { return null; } String host = uri.getHost().startsWith("[") ? uri.getHost().substring(1, uri.getHost().length() - 1) : uri.getHost(); - return new HostInput(host, uri.getPort() > 0 ? uri.getPort() : null); + String scheme = "https".equalsIgnoreCase(uri.getScheme()) ? "https" : "http"; + return new HostInput(scheme, host, uri.getPort() > 0 ? uri.getPort() : null); } catch (IllegalArgumentException e) { return null; } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java index 02a0711..9e53c9f 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java @@ -1,39 +1,40 @@ package wellatleastitried.mediagarrdclient.service; -import java.io.BufferedReader; import java.io.IOException; 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.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 com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; +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.api.Endpoints; +import wellatleastitried.mediagarrdclient.protocol.Endpoints; @Service public class ServerEventStreamService { @@ -51,24 +52,19 @@ public class ServerEventStreamService { public record Timing(Duration headerTimeout, Duration watchdog, Duration initialBackoff, Duration maxBackoff, Duration unsupportedRetry, Duration minStreamLifetime) { } - private enum Outcome { - ROLLOVER, - UNSUPPORTED, - FAILED - } - - private final class Stream implements Runnable { + 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 Stream(String serverUrl) { + private Subscription(String serverUrl) { this.serverUrl = serverUrl; } @@ -110,39 +106,32 @@ private boolean pause(Duration delay) { @Override public void run() { - Duration backoff = timing.initialBackoff(); + ReconnectPolicy policy = new ReconnectPolicy(timing.initialBackoff(), timing.maxBackoff(), timing.unsupportedRetry(), timing.minStreamLifetime()); try { while (!isCancelled()) { - Outcome outcome; + ReconnectPolicy.Outcome outcome; long startedNanos = System.nanoTime(); try { outcome = connectAndRead(); } catch (RuntimeException e) { LOGGER.warn("Event stream of {} failed: {}", serverUrl, e.getMessage()); - outcome = Outcome.FAILED; + outcome = ReconnectPolicy.Outcome.FAILED; } if (isCancelled()) { break; } - boolean shortLived = System.nanoTime() - startedNanos < timing.minStreamLifetime().toNanos(); - if (eventsSeen) { - eventsSeen = false; - if (!shortLived) { - backoff = timing.initialBackoff(); - } - } - if (outcome == Outcome.ROLLOVER && shortLived) { - outcome = Outcome.FAILED; - } - if (outcome == Outcome.ROLLOVER) { + ReconnectPolicy.Decision decision = policy.next(outcome, eventsSeen, System.nanoTime() - startedNanos); + eventsSeen = false; + if (decision.outcome() == ReconnectPolicy.Outcome.ROLLOVER) { continue; } reportLink(false); - Duration delay = outcome == Outcome.UNSUPPORTED ? timing.unsupportedRetry() : backoff; - if (outcome == Outcome.FAILED) { - backoff = min(backoff.multipliedBy(2), timing.maxBackoff()); + if (decision.outcome() == ReconnectPolicy.Outcome.REJECTED) { + rejected = true; + reportRejected(); + break; } - if (pause(delay)) { + if (pause(decision.delay())) { break; } } @@ -151,93 +140,80 @@ public void run() { } } - private Outcome connectAndRead() { + 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 Outcome.FAILED; + return ReconnectPolicy.Outcome.FAILED; } HttpResponse response; try { response = future.get(); } catch (InterruptedException | CancellationException e) { - return Outcome.FAILED; + 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 Outcome.FAILED; + return ReconnectPolicy.Outcome.FAILED; } body = response.body(); if (isCancelled()) { closeBody(); - return Outcome.FAILED; + 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.info("{} has no event stream, falling back to polling and retrying in {}", serverUrl, timing.unsupportedRetry()); - return Outcome.UNSUPPORTED; + 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 Outcome.FAILED; + return ReconnectPolicy.Outcome.FAILED; } return read(response.body()); } - private Outcome read(InputStream input) { + private ReconnectPolicy.Outcome read(InputStream input) { lastActivityNanos = System.nanoTime(); ScheduledFuture watchdog = scheduler.scheduleWithFixedDelay(this::checkWatchdog, checkPeriodMillis(), checkPeriodMillis(), TimeUnit.MILLISECONDS); - boolean sawEvent = false; - String name = null; - StringBuilder data = new StringBuilder(); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) { - String line; - while ((line = reader.readLine()) != null) { - lastActivityNanos = System.nanoTime(); - if (line.isEmpty()) { - if (data.length() > 0) { - if (!sawEvent) { - sawEvent = true; - eventsSeen = true; - reportLink(true); - } - dispatch(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'); - } - data.append(value); - } + try { + boolean sawEvent = SseReader.read(input, () -> lastActivityNanos = System.nanoTime(), (name, data) -> { + if (!eventsSeen) { + eventsSeen = true; + reportLink(true); } - } - return sawEvent ? Outcome.ROLLOVER : Outcome.FAILED; + 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 Outcome.FAILED; + return ReconnectPolicy.Outcome.FAILED; } finally { watchdog.cancel(false); } @@ -270,6 +246,14 @@ private void reportLink(boolean connected) { } } + private void reportRejected() { + synchronized (lock) { + if (current == this) { + dashboard.pairingRejected(serverUrl); + } + } + } + private void dispatch(String name, String data) { if (!FORWARDED_EVENTS.contains(name)) { return; @@ -279,80 +263,145 @@ private void dispatch(String name, String 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, data); + case "backups-changed" -> dashboard.backupsChanged(serverUrl, forwarded); case "config-changed" -> dashboard.configChanged(serverUrl); - default -> dashboard.runEvent(serverUrl, name, data, running); + default -> dashboard.runEvent(serverUrl, name, forwarded, running); } } - } catch (IOException e) { + } catch (JacksonException e) { LOGGER.debug("Ignoring malformed {} event from {}", name, serverUrl); } } } - private static Duration min(Duration a, Duration b) { - return a.compareTo(b) <= 0 ? a : b; - } - private final ClientStateService stateService; private final DashboardService dashboard; private final ObjectMapper mapper; private final Timing timing; - private final HttpClient httpClient = HttpClient.newBuilder() - .version(HttpClient.Version.HTTP_1_1) - .connectTimeout(CONNECT_TIMEOUT) - .build(); + private final HttpClient httpClient; private final ThreadFactory threadFactory; private final ScheduledExecutorService scheduler; + private final LongSupplier nanoTime; private final Object lock = new Object(); - private Stream current; + private Subscription current; + private long lastRecoveryRestartNanos; + private boolean recoveryRestarted; + private ScheduledFuture deferredRecovery; @Autowired - public ServerEventStreamService(ClientStateService stateService, DashboardService dashboard, ObjectMapper mapper) { - this(stateService, dashboard, mapper, new Timing(HEADER_TIMEOUT, WATCHDOG, INITIAL_BACKOFF, MAX_BACKOFF, UNSUPPORTED_RETRY, MIN_STREAM_LIFETIME)); + 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, Timing timing) { + 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 = Executors.newSingleThreadScheduledExecutor( - runnable -> Thread.ofPlatform().daemon().name("server-event-watchdog").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 target = normalize(stateService.getActiveServer()); + 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; } - if (current != null) { - current.cancel(); - current = null; - } + dropCurrent(); dashboard.sync(); if (target != null) { - Stream stream = new Stream(target); + Subscription stream = new Subscription(target); stream.thread = threadFactory.newThread(stream); current = stream; stream.thread.start(); - LOGGER.info("Subscribing to live events of {}", target); + LOGGER.debug("Subscribing to live events of {}", target); } } } @@ -360,16 +409,9 @@ void reconcile() { @PreDestroy void shutdown() { synchronized (lock) { - if (current != null) { - current.cancel(); - current = null; - } + dropCurrent(); } scheduler.shutdownNow(); httpClient.shutdownNow(); } - - private static String normalize(String url) { - return url == null || url.isBlank() ? null : url; - } } 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 index f4a5f2d..bbe670b 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/UpdateCheckService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/UpdateCheckService.java @@ -1,6 +1,7 @@ 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; @@ -24,11 +25,12 @@ 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.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; import wellatleastitried.mediagarrdclient.dto.CheckState; import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; @@ -43,6 +45,7 @@ record GithubRelease(@JsonProperty("tag_name") String tagName, @JsonProperty("ht 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; @@ -54,11 +57,11 @@ record GithubRelease(@JsonProperty("tag_name") String tagName, @JsonProperty("ht private final List> listeners = new CopyOnWriteArrayList<>(); @Autowired - public UpdateCheckService(Configuration properties, ObjectProvider buildProperties) { + public UpdateCheckService(MediaGarrdProperties properties, ObjectProvider buildProperties) { this(properties, versionOf(buildProperties), Clock.systemUTC()); } - UpdateCheckService(Configuration properties, String currentVersion, Clock clock) { + 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); @@ -133,9 +136,9 @@ private VersionStatusDto fromRelease(GithubRelease release) { if (latest.isEmpty()) { return result(CheckState.ERROR, null, null, "Latest release has an unrecognized version tag"); } - String url = release.htmlUrl() == null || release.htmlUrl().isBlank() - ? "https://github.com/" + repository + "/releases/tag/" + release.tagName().strip() - : release.htmlUrl(); + 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); } 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/resources/application.yml b/src/main/resources/application.yml index aaa3289..e37934f 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -2,6 +2,9 @@ server: port: ${CLIENT_PORT:8081} spring: + jackson: + deserialization: + fail-on-null-for-primitives: false task: scheduling: pool: @@ -22,3 +25,6 @@ mediagarrd: 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 index f9d15f6..839bfd1 100644 --- a/src/main/resources/static/css/mediagarrd.css +++ b/src/main/resources/static/css/mediagarrd.css @@ -3,7 +3,7 @@ --surface: #0a0a0a; --surface-raised: #111; --ink: #f5f5f5; - --muted: #737373; + --muted: #8a8a8a; --subtle: #404040; --border: #1f1f1f; --border-mid: #2e2e2e; @@ -63,7 +63,9 @@ body { 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; @@ -76,21 +78,24 @@ body { .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 1fr; + grid-template-columns: 360px minmax(0, 1fr); gap: 1rem; align-items: start; } -@media (max-width: 900px) { .workspace { grid-template-columns: 1fr; } } +.workspace > * { min-width: 0; } +.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; } -.stack { display: flex; flex-direction: column; gap: 1rem; } .panel-header { display: flex; align-items: center; @@ -112,24 +117,29 @@ body { .field-group { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 0.75rem; } .field-label { font-size: 0.7rem; color: var(--muted); letter-spacing: 0.04em; } -.note { font-size: 0.72rem; color: var(--muted); margin-top: 0.45rem; } -.input-row { display: grid; grid-template-columns: 1fr auto; gap: 0.5rem; } -.input-row-2 { display: grid; grid-template-columns: 1fr 110px; gap: 0.5rem; } +.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; - outline: none; 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 { @@ -148,7 +158,20 @@ button { } 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 { cursor: not-allowed; opacity: 0.62; transform: none; } +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; } @@ -197,8 +220,8 @@ button.small { padding: 0.3rem 0.65rem; font-size: 0.7rem; } .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: 1fr 1fr; gap: 1rem; padding: 1rem; } -@media (max-width: 900px) { .version-list { grid-template-columns: 1fr; } } +.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; @@ -252,6 +275,7 @@ button.small { padding: 0.3rem 0.65rem; font-size: 0.7rem; } 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; @@ -264,6 +288,17 @@ thead th { 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); } @@ -279,8 +314,8 @@ tbody td { padding: 0.55rem 0.75rem; vertical-align: middle; } .empty-state { padding: 2.5rem 1rem; text-align: center; color: var(--muted); font-size: 0.83rem; } .icon-btn { - min-width: 34px; - height: 28px; + min-width: 44px; + height: 36px; padding: 0; font-size: 0.95rem; line-height: 1; @@ -314,6 +349,8 @@ tbody td { padding: 0.55rem 0.75rem; vertical-align: middle; } 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 { @@ -325,3 +362,48 @@ tbody td { padding: 0.55rem 0.75rem; vertical-align: middle; } 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 621da1e..082b5e7 100644 --- a/src/main/resources/static/index.html +++ b/src/main/resources/static/index.html @@ -17,14 +17,43 @@ -
- - Connecting… +
+
+ + Connecting… +
+
+ +
- +
@@ -34,7 +63,7 @@
- +
@@ -80,6 +109,29 @@
+ +
@@ -98,7 +150,7 @@
- +
@@ -109,18 +161,20 @@ Backup Archives
+
- - - - - + + + + +
File Size Created ID GetGet
+

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

@@ -153,7 +207,7 @@ -
+
- +
- +
-
-
Add Service
-
-
- - -
-
- Host paths to back up -
- -
-
- - -
-
+
+
+
Add Service
+
+
+ + +
+
+ Host paths to back up +
+ +
+
+ + +
+
+ + - +

No services configured yet.

+
- - -
Configured Services
- - - -
NamePaths
-

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 index 83933a1..b62c675 100644 --- a/src/main/resources/static/js/api.js +++ b/src/main/resources/static/js/api.js @@ -1,12 +1,67 @@ +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 ? {} : { 'Content-Type': 'application/json' }, + 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(() => ({})); - throw new Error(data.error || data.message || `${method} ${url} failed (${response.status})`); + 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; @@ -15,6 +70,13 @@ async function request(method, url, body) { 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'), @@ -27,6 +89,9 @@ export const api = { 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), 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 index 19eee41..7384650 100644 --- a/src/main/resources/static/js/backups.js +++ b/src/main/resources/static/js/backups.js @@ -1,7 +1,12 @@ 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'); @@ -16,17 +21,22 @@ export function initBackups({ root, actions }, notify) { 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; + 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); + 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 = @@ -37,7 +47,7 @@ export function initBackups({ root, actions }, notify) { const button = rowButtons.get(id); if (!button) return; const task = rowTasks.get(id); - button.disabled = Boolean(task); + button.disabled = Boolean(task) || !available; if (!task) { button.textContent = '↓'; return; @@ -70,10 +80,12 @@ export function initBackups({ root, actions }, notify) { return row; } - function renderTable(emptyMessage = 'No backup archives found on server.') { + 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(); @@ -88,11 +100,11 @@ export function initBackups({ root, actions }, notify) { const loaded = await api.listBackups() || []; if (request !== latestRequest) return; backups = loaded; - renderTable(); + renderTable(EMPTY_DEFAULT); } catch (error) { if (request !== latestRequest) return; backups = []; - renderTable(`${error.message}. Connect to a server to view archives.`); + renderTable(listingError(error, available)); } } @@ -108,56 +120,80 @@ export function initBackups({ root, actions }, notify) { } async function poll() { - const tasks = [...rowTasks].map(([id, task]) => ({ id, task })); + 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(); - pollTimer = setTimeout(poll, POLL_INTERVAL_MS); + pollDelay = Math.min(Math.round(pollDelay * 1.3), POLL_MAX_INTERVAL_MS); + pollTimer = setTimeout(poll, pollDelay); } function startPolling() { - if (!pollTimer) pollTimer = setTimeout(poll, POLL_INTERVAL_MS); + if (pollTimer) return; + pollDelay = POLL_INTERVAL_MS; + pollTimer = setTimeout(poll, pollDelay); } - const toTask = (started) => ({ taskId: started.taskId, bytesWritten: 0, totalBytes: started.totalBytes || 0 }); + 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)) return; + if (rowTasks.has(id) || !available) return; notify.clear(); + const mine = generation; + rowTasks.set(id, { taskId: null, bytesWritten: 0, totalBytes: 0 }); + renderRowButton(id); try { - rowTasks.set(id, toTask(await api.pickupById(id))); - renderRowButton(id); + 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) return; + if (latestTask || !available) return; notify.clear(); + const mine = generation; latestTask = { taskId: null, bytesWritten: 0, totalBytes: 0 }; renderActions(); try { - latestTask = toTask(await api.pickupLatest()); + const task = toTask(await api.pickupLatest()); + if (mine !== generation) return; + latestTask = task; startPolling(); } catch (error) { + if (mine !== generation) return; latestTask = null; notify.error(error); } @@ -165,7 +201,7 @@ export function initBackups({ root, actions }, notify) { }); runButton.addEventListener('click', async () => { - if (serverRunning || runInFlight) return; + if (serverRunning || runInFlight || !available) return; notify.clear(); runInFlight = true; renderActions(); @@ -179,7 +215,7 @@ export function initBackups({ root, actions }, notify) { } }); - headers.forEach((header) => header.addEventListener('click', () => { + headers.forEach((header) => header.querySelector('button').addEventListener('click', () => { const key = header.dataset.sortKey; if (sort.key === key) { sort.dir = sort.dir === 'asc' ? 'desc' : 'asc'; @@ -195,16 +231,38 @@ export function initBackups({ root, actions }, notify) { refresh(); }); - renderTable('No backups loaded. Connect to a server to view archives.'); + renderTable(EMPTY_DISCONNECTED); renderActions(); + function clear() { + latestRequest++; + backups = []; + renderTable(pairingNeeded ? EMPTY_UNPAIRED : EMPTY_DISCONNECTED); + } + return { refresh, rerender: () => renderTable(), - clear() { - latestRequest++; - backups = []; - renderTable('No backups loaded. Connect to a server to view archives.'); + 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; 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 index 47a8896..19456cf 100644 --- a/src/main/resources/static/js/connection.js +++ b/src/main/resources/static/js/connection.js @@ -62,6 +62,7 @@ export function initConnection({ root, statusPanel, badge }, notify, { resync }) 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; }); @@ -74,6 +75,7 @@ export function initConnection({ root, statusPanel, badge }, notify, { resync }) busy = false; scanBar.classList.remove('active'); controls.forEach((control) => { control.disabled = false; }); + if (focused) focused.focus(); if (latest) render(latest); await resync(); return result; diff --git a/src/main/resources/static/js/dashboard-model.js b/src/main/resources/static/js/dashboard-model.js index 15fbf25..37dfa0c 100644 --- a/src/main/resources/static/js/dashboard-model.js +++ b/src/main/resources/static/js/dashboard-model.js @@ -2,8 +2,12 @@ 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); + return state.loaded && state.clientReachable && state.activeServer !== null && reachableLink(state.link) && !needsPairing(state); } export function emptyState() { @@ -16,6 +20,7 @@ export function emptyState() { running: null, health: null, versions: null, + pairing: 'NONE', }; } @@ -29,6 +34,7 @@ function fromSnapshot(payload) { running: payload.running ?? null, health: payload.health || null, versions: payload.versions || null, + pairing: payload.pairing || 'PAIRED', }; } @@ -57,6 +63,8 @@ export function reduce(state, name, payload) { 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; } @@ -71,6 +79,7 @@ export function changes(prev, next, eventName) { 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'; diff --git a/src/main/resources/static/js/events.js b/src/main/resources/static/js/events.js index 566bccf..743ba7e 100644 --- a/src/main/resources/static/js/events.js +++ b/src/main/resources/static/js/events.js @@ -1,18 +1,19 @@ import { createReachability } from './reachability.js'; const EVENTS_URL = '/api/client/events'; -const EVENT_NAMES = ['snapshot', 'link', 'state', 'run-started', 'run-finished', 'servers', 'config', 'backups-changed', 'versions', 'ping']; +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 }) { +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) { @@ -45,7 +46,9 @@ export function initEvents({ onEvent, onConnection }) { 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(); @@ -54,8 +57,13 @@ export function initEvents({ onEvent, onConnection }) { if (source !== created) return; const closed = created.readyState === EventSource.CLOSED; reachability.failed(closed); - if (!closed) return; + if (!closed) { + opened = false; + return; + } + const neverOpened = !opened; close(); + if (neverOpened) checkSession().catch(() => {}); scheduleReopen(); }); EVENT_NAMES.forEach((name) => created.addEventListener(name, (event) => { @@ -81,11 +89,10 @@ export function initEvents({ onEvent, onConnection }) { setInterval(() => { if (source && Date.now() - lastMessageAt > SILENCE_LIMIT_MS) { close(); + reachability.failed(true); open(); } }, SILENCE_CHECK_MS); open(); - - return { open, close }; } diff --git a/src/main/resources/static/js/format.js b/src/main/resources/static/js/format.js index 68a82b6..4f38ece 100644 --- a/src/main/resources/static/js/format.js +++ b/src/main/resources/static/js/format.js @@ -6,7 +6,30 @@ export function seconds(duration) { return Number(hours) * 3600 + Number(minutes) * 60 + Number(secs); } -export const toDuration = (minutes) => `PT${Math.round(minutes)}M`; +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); @@ -30,7 +53,9 @@ export function bytes(size) { } export function relativeTime(iso) { - const elapsed = Math.max(0, Math.floor((Date.now() - new Date(iso).getTime()) / 1000)); + 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`; diff --git a/src/main/resources/static/js/main.js b/src/main/resources/static/js/main.js index 6925e08..307ea51 100644 --- a/src/main/resources/static/js/main.js +++ b/src/main/resources/static/js/main.js @@ -1,9 +1,11 @@ +import { initAuth } from './auth.js'; import { initBackups } from './backups.js'; import { initConnection } from './connection.js'; -import { applyEvent, canLoadBackups, emptyState } from './dashboard-model.js'; +import { applyEvent, canLoadBackups, emptyState, needsPairing } from './dashboard-model.js'; import { initEvents } from './events.js'; -import { api } from './api.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'; @@ -13,6 +15,12 @@ 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({ @@ -28,6 +36,8 @@ const connection = initConnection({ let state = emptyState(); let pushes = 0; let pickupLoad = 'idle'; +let snapshots = 0; +let backupsAvailable = false; function loadPickupInterval() { if (pickupLoad !== 'idle') return; @@ -47,37 +57,50 @@ function dispatch(name, payload) { 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.clear(); + 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) dispatch('snapshot', snapshot); + if (pushes === startedAt && mine === snapshots) dispatch('snapshot', snapshot); } catch (error) { - if (error instanceof TypeError && pushes === startedAt) dispatch('client', { reachable: false }); + 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(); } -initEvents({ - onEvent: (name, payload) => { - pushes++; - dispatch(name, payload); - }, - onConnection: (reachable) => dispatch('client', { reachable }), -}); - document.addEventListener('click', (event) => { const button = event.target.closest('button'); if (!button) return; @@ -85,29 +108,42 @@ document.addEventListener('click', (event) => { setTimeout(() => button.classList.remove('clicked'), 140); }); -let viewShown = false; -initViews((view) => { - notify.clear(); - if (view === 'config') serverConfig.load(); - else if (viewShown) { - resync(); - refreshBackupsIfUp(); - } - viewShown = true; -}); +function start() { + initEvents({ + onEvent: (name, payload) => { + pushes++; + dispatch(name, payload); + }, + onConnection: (reachable) => dispatch('client', { reachable }), + checkSession, + }); -loadPickupInterval(); -resync(); + let viewShown = false; + initViews((view) => { + notify.clear(); + if (view === 'config') serverConfig.load(); + else if (viewShown) { + resync(); + refreshBackupsIfUp(); + } + viewShown = true; + }); -setInterval(() => { - if (document.hidden) return; + loadPickupInterval(); resync(); - if (location.hash === '#config') return; - backups.rerender(); -}, DASHBOARD_REFRESH_MS); -document.addEventListener('visibilitychange', () => { - if (document.hidden) return; - resync(); - if (location.hash !== '#config') refreshBackupsIfUp(); -}); + 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 index ddbe743..b77b08f 100644 --- a/src/main/resources/static/js/notify.js +++ b/src/main/resources/static/js/notify.js @@ -2,10 +2,13 @@ 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 index 342980b..6ce52e0 100644 --- a/src/main/resources/static/js/pickup-interval.js +++ b/src/main/resources/static/js/pickup-interval.js @@ -1,5 +1,5 @@ import { api } from './api.js'; -import { seconds, toDuration } from './format.js'; +import { pickupProblem, seconds, toDuration } from './format.js'; export function initPickupInterval(form, notify) { const minutes = form.elements.minutes; @@ -10,6 +10,11 @@ export function initPickupInterval(form, notify) { 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; diff --git a/src/main/resources/static/js/server-config.js b/src/main/resources/static/js/server-config.js index 9a46998..027edda 100644 --- a/src/main/resources/static/js/server-config.js +++ b/src/main/resources/static/js/server-config.js @@ -1,25 +1,33 @@ 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 = - `${error.message}. Connect to a MediaGarrd server that has finished setup on the Dashboard to manage its configuration.`; + unavailable.querySelector('[data-reason]').textContent = configUnavailableMessage(error); } } @@ -27,6 +35,7 @@ export function initServerConfig(root, notify) { 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 index 0c0ab09..ebfa8e5 100644 --- a/src/main/resources/static/js/services.js +++ b/src/main/resources/static/js/services.js @@ -46,10 +46,19 @@ export function initServices(root, notify) { try { await api.removeService(service.name); if (editing === service.name) resetForm(); - notify.ok(`Removed ${service.name}`); - await refresh(); } 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}`); } } @@ -78,14 +87,15 @@ export function initServices(root, notify) { name: form.elements.name.value, paths: [...paths.querySelectorAll('input')].map((input) => input.value), }; + let saved; try { - const saved = editing ? await api.updateService(editing, service) : await api.addService(service); - notify.ok(`Saved ${saved.name}`); + saved = editing ? await api.updateService(editing, service) : await api.addService(service); resetForm(); - await refresh(); } catch (error) { notify.error(error); + return; } + await refreshThen(`Saved ${saved.name}`); }); root.querySelector('[data-add-path]').addEventListener('click', () => addPathInput()); diff --git a/src/main/resources/static/js/settings.js b/src/main/resources/static/js/settings.js index cd2cf08..7602b25 100644 --- a/src/main/resources/static/js/settings.js +++ b/src/main/resources/static/js/settings.js @@ -1,18 +1,23 @@ import { api } from './api.js'; -import { seconds, toDuration } from './format.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 = seconds(config.backupInterval) / 3600; + 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, diff --git a/src/main/resources/static/js/view-model.js b/src/main/resources/static/js/view-model.js index 6f385ab..f7057cf 100644 --- a/src/main/resources/static/js/view-model.js +++ b/src/main/resources/static/js/view-model.js @@ -1,7 +1,21 @@ +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) { @@ -19,8 +33,14 @@ export function linkView(state) { 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: 'ok', label: state.activeServer.replace(/^https?:\/\//, '') }, + badge: { kind: state.link === 'DEGRADED' ? 'degraded' : 'ok', label: state.activeServer.replace(/^https?:\/\//, '') }, message: '', showDetails: true, url: state.activeServer, 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/MediaGarrdTest.java b/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java deleted file mode 100644 index 4080d24..0000000 --- a/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package wellatleastitried.mediagarrdclient; - -import static org.junit.jupiter.api.Assertions.assertEquals; -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.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.nio.file.Path; -import java.time.Duration; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.DynamicPropertyRegistry; -import org.springframework.test.context.DynamicPropertySource; -import org.springframework.test.web.servlet.MockMvc; - -@SpringBootTest -@AutoConfigureMockMvc -class MediaGarrdTest { - - @TempDir - static Path dataDir; - - @Autowired - MockMvc mockMvc; - - @Autowired - Configuration configuration; - - @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"); - } - - @Test - void bindsTheBackupRunTimeoutDefault() { - assertEquals(Duration.ofHours(6), configuration.getBackupRunTimeout()); - } - - @Test - void servesTheWebPageAndItsAssets() throws Exception { - mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(forwardedUrl("index.html")); - mockMvc.perform(get("/css/mediagarrd.css")) - .andExpect(status().isOk()) - .andExpect(header().string("Cache-Control", "no-store")); - mockMvc.perform(get("/js/main.js")).andExpect(status().isOk()); - } - - @Test - void reportsStatusWithoutAServer() throws Exception { - mockMvc.perform(get("/api/client/status")) - .andExpect(status().isOk()) - .andExpect(content().json("{\"activeServer\":null,\"knownServers\":[]}")); - } - - @Test - void reportsTheDashboardWithTheClientVersionAndNoServer() throws Exception { - mockMvc.perform(get("/api/client/dashboard")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.link").value("DOWN")) - .andExpect(jsonPath("$.activeServer").doesNotExist()) - .andExpect(jsonPath("$.versions.client.checkState").exists()) - .andExpect(jsonPath("$.versions.server").doesNotExist()); - } -} 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 index 2106231..b398819 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java @@ -18,46 +18,52 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; import org.springframework.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.server.ResponseStatusException; +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; - @MockBean + @MockitoBean ClientStateService stateService; - @MockBean + @MockitoBean ServerDiscoveryService discoveryService; - @MockBean + @MockitoBean ServerApiService serverApiService; - @MockBean + @MockitoBean BackupPickupService backupPickupService; - @MockBean + @MockitoBean DashboardService dashboardService; @Test @@ -72,14 +78,14 @@ void mapsABackupRunTimeoutToAGatewayTimeoutWithAnErrorBody() throws Exception { } @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")); + 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(get("/api/client/status")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.activeServer").value("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 @@ -95,38 +101,6 @@ void discoverEndpointReturnsOnlyTheServersFoundByTheScan() throws Exception { verify(stateService).updateKnownServers(List.of("http://server:8080")); } - @Test - void listBackupsReturnsServerData() throws Exception { - when(stateService.requireActiveServer()).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 pickupEndpointStartsTask() throws Exception { - when(backupPickupService.startPickupLatestTask()).thenReturn(new PickupStartDto("task-1", "id", "file.zip", 10L)); - - mockMvc.perform(post("/api/client/pickup")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.taskId").value("task-1")) - .andExpect(jsonPath("$.backupId").value("id")); - } - @Test void statusHasNoNetworkSideEffect() throws Exception { mockMvc.perform(get("/api/client/status")).andExpect(status().isOk()); @@ -142,7 +116,8 @@ void dashboardEndpointReturnsTheStoredStateWithoutContactingTheServer() throws E LinkState.DEGRADED, true, new HealthSummary(Duration.ofHours(6), 5), - new VersionsDto(null, null))); + new VersionsDto(null, null), + PairingState.PAIRED)); mockMvc.perform(get("/api/client/dashboard")) .andExpect(status().isOk()) @@ -158,12 +133,35 @@ void dashboardEndpointReturnsTheStoredStateWithoutContactingTheServer() throws E @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\"}")) @@ -192,16 +190,39 @@ void reportsWhenNoServerAnswersAtTheGivenAddress() throws Exception { @Test void rejectsInvalidPickupIntervals() throws Exception { - when(backupPickupService.updatePickupInterval(Duration.ZERO)).thenThrow(new IllegalArgumentException("Pickup interval must be a positive duration")); + 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 ResponseStatusException(HttpStatus.NOT_FOUND, "Pickup task not found: gone")); + when(backupPickupService.pickupProgress("gone")).thenThrow(new NotFoundException("Pickup task not found: gone")); mockMvc.perform(get("/api/client/pickup/progress/gone")) .andExpect(status().isNotFound()) diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcasterTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcasterTest.java similarity index 81% rename from src/test/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcasterTest.java rename to src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcasterTest.java index c511d84..670ef83 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcasterTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcasterTest.java @@ -1,8 +1,7 @@ -package wellatleastitried.mediagarrdclient.service; +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.assertNull; import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -11,10 +10,8 @@ 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.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.function.LongFunction; @@ -22,54 +19,15 @@ 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.ResponseBodyEmitter; 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 RecordingEmitter extends SseEmitter { - - final BlockingQueue sent = new LinkedBlockingQueue<>(); - final CountDownLatch completed = new CountDownLatch(1); - - 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(); - } - - 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 class FailingEmitter extends RecordingEmitter { FailingEmitter(Long timeout) { @@ -140,24 +98,43 @@ private static RecordingEmitter subscribe(ClientEventBroadcaster broadcaster) { } @Test - void sendsTheInitialEventsFirstAndTellsTheBrowserHowLongToWaitBeforeReconnecting() throws Exception { + 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(); - RecordingEmitter emitter = subscribe(broadcaster); + broadcaster.endSession("session-a"); - assertEquals("retry:5000\nevent:snapshot\ndata:{\"link\":\"DOWN\"}\n\n", emitter.next()); - assertNull(emitter.sent.poll(200, TimeUnit.MILLISECONDS)); + assertTrue(ending.completed.await(5, TimeUnit.SECONDS)); + assertEquals(1, broadcaster.subscriberCount()); + broadcaster.publish("state", "{}"); + assertTrue(staying.next().contains("event:state")); } @Test - void theReconnectHintIsSentOnlyOnce() throws Exception { - ClientEventBroadcaster broadcaster = broadcaster(); - RecordingEmitter emitter = subscribe(broadcaster); + 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(); - broadcaster.publish("run-started", "{\"running\":true}"); + active.set(false); - assertEquals("event:run-started\ndata:{\"running\":true}\n\n", emitter.next()); + 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 diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java index f19e41e..2097831 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java @@ -1,5 +1,6 @@ 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; @@ -9,40 +10,53 @@ 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.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; import org.springframework.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; - @MockBean + @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(dashboard.subscribe()).thenReturn(Optional.of(emitter)); + 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("Cache-Control", "no-cache")) .andExpect(header().string("X-Accel-Buffering", "no")) .andExpect(content().string("event:link\ndata:{}\n\n")); @@ -51,7 +65,7 @@ void opensAnUnbufferedEventStream() throws Exception { @Test void answers503WhenTooManyBrowsersAreSubscribed() throws Exception { - when(dashboard.subscribe()).thenReturn(Optional.empty()); + when(broadcaster.subscribe(any(), any())).thenReturn(Optional.empty()); mockMvc.perform(get("/api/client/events").accept(MediaType.TEXT_EVENT_STREAM)) .andExpect(status().isServiceUnavailable()) @@ -62,7 +76,7 @@ void answers503WhenTooManyBrowsersAreSubscribed() throws Exception { void aBrowserThatWentAwayEndsTheStreamWithoutAnError() throws Exception { SseEmitter emitter = new SseEmitter(60_000L); emitter.send(SseEmitter.event().name("link").data("{}")); - when(dashboard.subscribe()).thenReturn(Optional.of(emitter)); + 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(); 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 index de33936..7f8e313 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java @@ -18,14 +18,15 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; import org.springframework.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 org.springframework.web.server.ResponseStatusException; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; @@ -34,6 +35,7 @@ import wellatleastitried.mediagarrdclient.service.ServerApiService; @WebMvcTest(controllers = ServerConfigController.class) +@Import(TestSession.class) class ServerConfigControllerTest { private static final String SERVER = "http://server:8080"; @@ -45,10 +47,10 @@ class ServerConfigControllerTest { @Autowired MockMvc mockMvc; - @MockBean + @MockitoBean ClientStateService stateService; - @MockBean + @MockitoBean ServerApiService serverApiService; @BeforeEach @@ -57,45 +59,45 @@ void setUp() { } @Test - void returnsServerConfig() throws Exception { - when(serverApiService.serverConfig(SERVER)).thenReturn(new ServerConfigDto("/backups", 4, Duration.ofHours(6))); + void leavesScheduleAloneWhenIntervalIsOmitted() throws Exception { + when(serverApiService.updateServerConfig(SERVER, null, 5)).thenReturn(new ServerConfigDto("/backups", 5, Duration.ofHours(6))); - mockMvc.perform(get("/api/client/server-config")) + mockMvc.perform(json(put("/api/client/server-config"), "{\"retentionCount\": 5}")) .andExpect(status().isOk()) - .andExpect(jsonPath("$.backupLocation").value("/backups")) - .andExpect(jsonPath("$.retentionCount").value(4)) .andExpect(jsonPath("$.backupInterval").value("PT6H")); + + verify(serverApiService, never()).updateServerSchedule(anyString(), any()); } @Test - void updatesConfigAndScheduleTogether() throws Exception { - when(serverApiService.updateServerConfig(SERVER, "/new", 3)).thenReturn(new ServerConfigDto("/new", 3, Duration.ofHours(6))); - when(serverApiService.updateServerSchedule(SERVER, Duration.ofMinutes(90))) - .thenReturn(new ServerStatusDto(true, false, 3, Duration.ofMinutes(90))); - - mockMvc.perform(json(put("/api/client/server-config"), "{\"backupLocation\": \"/new\", \"retentionCount\": 3, \"backupInterval\": \"PT90M\"}")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.backupLocation").value("/new")) - .andExpect(jsonPath("$.retentionCount").value(3)) - .andExpect(jsonPath("$.backupInterval").value("PT1H30M")); + 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 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()); + 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, "old name", RADARR)).thenReturn(RADARR); + when(serverApiService.updateService(SERVER, "radarr-4k", RADARR)).thenReturn(RADARR); mockMvc.perform(get("/api/client/services")) .andExpect(status().isOk()) @@ -104,7 +106,7 @@ void forwardsServiceChanges() throws Exception { mockMvc.perform(json(post("/api/client/services"), RADARR_JSON)) .andExpect(status().isCreated()) .andExpect(jsonPath("$.name").value("radarr")); - mockMvc.perform(json(put("/api/client/services/old name"), RADARR_JSON)) + mockMvc.perform(json(put("/api/client/services/radarr-4k"), RADARR_JSON)) .andExpect(status().isOk()); mockMvc.perform(delete("/api/client/services/radarr")) .andExpect(status().isNoContent()); @@ -113,15 +115,41 @@ void forwardsServiceChanges() throws Exception { } @Test - void rejectsRequestsWithoutAnActiveServer() throws Exception { - when(stateService.requireActiveServer()) - .thenThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "No active MediaGarrd server selected")); - - mockMvc.perform(get("/api/client/services")) + 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").value("No active MediaGarrd server selected")); + .andExpect(jsonPath("$.error").exists()); - verify(serverApiService, never()).listServices(anyString()); + 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 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 index 4c39aa4..916225c 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java @@ -2,11 +2,13 @@ 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; @@ -14,22 +16,19 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.time.Clock; import java.time.Duration; import java.time.Instant; -import java.time.ZoneOffset; 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 org.springframework.http.HttpStatus; -import org.springframework.web.server.ResponseStatusException; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; import wellatleastitried.mediagarrdclient.dto.BackupDto; import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; import wellatleastitried.mediagarrdclient.dto.PickupStartDto; @@ -50,9 +49,11 @@ class BackupPickupServiceTest { @BeforeEach void setUp() { - Configuration configuration = new Configuration(); + 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); @@ -103,7 +104,7 @@ void reusesAnExistingDownload() throws Exception { @Test void reportsDownloadFailures() throws Exception { - when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenThrow(new IllegalStateException("disk full")); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenThrow(new DownloadFailedException("disk full")); PickupProgressDto progress = awaitFinished(pickup.startPickupLatestTask().taskId()); @@ -119,22 +120,80 @@ void forgetsFinishedTasksAfterTheRetentionPeriod() throws Exception { clock.advance(BackupPickupService.FINISHED_TASK_RETENTION.plusSeconds(1)); pickup.startPickupByIdTask("b1"); - assertStatus(HttpStatus.NOT_FOUND, () -> pickup.pickupProgress(taskId)); + assertThrows(NotFoundException.class, () -> pickup.pickupProgress(taskId)); } @Test void rejectsUnknownBackupsAndTasks() { - assertStatus(HttpStatus.NOT_FOUND, () -> pickup.startPickupByIdTask("missing")); - assertStatus(HttpStatus.NOT_FOUND, () -> pickup.pickupProgress("missing")); + assertThrows(NotFoundException.class, () -> pickup.startPickupByIdTask("missing")); + assertThrows(NotFoundException.class, () -> pickup.pickupProgress("missing")); when(api.listBackups(SERVER)).thenReturn(List.of()); - assertStatus(HttpStatus.NOT_FOUND, () -> pickup.startPickupLatestTask()); + assertThrows(NotFoundException.class, () -> pickup.startPickupLatestTask()); } @Test void refusesFileNamesThatLeaveTheDownloadDirectory() { when(api.listBackups(SERVER)).thenReturn(List.of(new BackupDto("evil", "../evil.zip", 4, Instant.EPOCH))); - assertThrows(IllegalArgumentException.class, () -> pickup.startPickupLatestTask()); + 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 @@ -148,11 +207,68 @@ void scheduledPickupKeepsOnlyTheLatestAutomaticDownload() throws IOException { }); clock.advance(Duration.ofHours(2)); - pickup.scheduledPickup(); + 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); @@ -169,31 +285,4 @@ private List fileNames() throws IOException { return files.map(path -> path.getFileName().toString()).sorted().toList(); } } - - private static void assertStatus(HttpStatus status, Runnable action) { - assertEquals(status, assertThrows(ResponseStatusException.class, action::run).getStatusCode()); - } - - private static final class MutableClock extends Clock { - private Instant now = Instant.parse("2026-10-26T00:00:00Z"); - - void advance(Duration duration) { - now = now.plus(duration); - } - - @Override - public Instant instant() { - return now; - } - - @Override - public java.time.ZoneId getZone() { - return ZoneOffset.UTC; - } - - @Override - public Clock withZone(java.time.ZoneId zone) { - return this; - } - } } 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 index d0b9362..a7b33f0 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java @@ -1,6 +1,7 @@ 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; @@ -8,6 +9,7 @@ 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; @@ -17,20 +19,19 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; -import org.springframework.web.server.ResponseStatusException; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; class ClientStateServiceTest { - private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final JsonMapper MAPPER = JsonMapper.builder().build(); @TempDir Path tempDir; - private final Configuration configuration = new Configuration(); + private final MediaGarrdProperties configuration = new MediaGarrdProperties(); @BeforeEach void setUp() { @@ -52,6 +53,78 @@ void persistsAndLoadsState() { 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); @@ -76,7 +149,31 @@ void keepsTheActiveServerWhenARescanDoesNotFindIt() { state.updateKnownServers(List.of("http://b:8080")); assertEquals("http://a:8080", state.getActiveServer()); - assertEquals(List.of("http://b:8080", "http://a:8080"), state.getKnownServers()); + 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 @@ -93,24 +190,69 @@ void selectsTheFirstDiscoveredServerWhenNoneIsActive() { void rejectsNonPositivePickupIntervals() { ClientStateService state = new ClientStateService(configuration, MAPPER); - assertThrows(IllegalArgumentException.class, () -> state.setPickupInterval(Duration.ZERO)); - assertThrows(IllegalArgumentException.class, () -> state.setPickupInterval(null)); + assertThrows(InvalidRequestException.class, () -> state.setPickupInterval(Duration.ZERO)); + assertThrows(InvalidRequestException.class, () -> state.setPickupInterval(null)); assertEquals(Duration.ofHours(12), state.getPickupInterval()); } @Test - void requiresAnActiveServer() { - assertThrows(ResponseStatusException.class, () -> new ClientStateService(configuration, MAPPER).requireActiveServer()); + 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 startsWithDefaultsWhenTheStateFileIsUnreadable() throws IOException { - Files.writeString(tempDir.resolve("state.json"), "{not json"); + void anOutOfRangeStoredOrConfiguredIntervalFallsBackToTheDefault() throws IOException { + Files.writeString(tempDir.resolve("state.json"), "{\"activeServer\":\"http://a:8080\",\"pickupIntervalSeconds\":999999999,\"knownServers\":[\"http://a:8080\"]}"); - ClientStateService state = new ClientStateService(configuration, MAPPER); + ClientStateService stored = new ClientStateService(configuration, MAPPER); + assertEquals(Duration.ofHours(12), stored.getPickupInterval()); + assertEquals("http://a:8080", stored.getActiveServer()); - assertNull(state.getActiveServer()); - assertEquals(Duration.ofHours(12), state.getPickupInterval()); + 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() { @@ -221,4 +363,87 @@ void notifiesKnownServersListenersWithoutHoldingTheStateLock() { 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 index 9847b27..4860911 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/DashboardServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/DashboardServiceTest.java @@ -15,20 +15,16 @@ import static org.mockito.Mockito.when; import java.nio.file.Path; -import java.time.Clock; import java.time.Duration; import java.time.Instant; -import java.time.ZoneId; 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.concurrent.atomic.AtomicReference; import java.util.function.Consumer; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -36,25 +32,25 @@ import org.mockito.ArgumentCaptor; import org.springframework.web.client.ResourceAccessException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.databind.json.JsonMapper; +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.Configuration; +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; -import wellatleastitried.mediagarrdclient.service.ClientEventBroadcasterTest.RecordingEmitter; @Timeout(30) class DashboardServiceTest { private static final ObjectMapper MAPPER = JsonMapper.builder() .findAndAddModules() - .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) + .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"; @@ -67,50 +63,30 @@ class DashboardServiceTest { @TempDir Path tempDir; - private final AtomicReference now = new AtomicReference<>(START); - private final Clock clock = new Clock() { - @Override - public ZoneId getZone() { - return ZoneId.of("UTC"); - } - - @Override - public Clock withZone(ZoneId zone) { - return this; - } - - @Override - public Instant instant() { - return now.get(); - } - }; + private final MutableClock clock = new MutableClock(START); private final Queue queued = new ArrayDeque<>(); - private final List broadcasters = new ArrayList<>(); private final ServerApiService serverApi = mock(ServerApiService.class); private final UpdateCheckService updateCheck = mock(UpdateCheckService.class); private ClientStateService state; - private ClientEventBroadcaster broadcaster; + private RecordingPublisher publisher; private DashboardService dashboard; @BeforeEach void setUp() { - Configuration configuration = new Configuration(); + 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) { - broadcaster = new ClientEventBroadcaster(Duration.ofMinutes(10), 8, 64, Duration.ofMinutes(5), Duration.ofMinutes(6), runnable -> { - Thread thread = new Thread(runnable); - thread.setDaemon(true); - return thread; - }, RecordingEmitter::new); - broadcasters.add(broadcaster); - dashboard = new DashboardService(state, broadcaster, serverApi, new VersionService(updateCheck, serverApi, clock), updateCheck, MAPPER, executor, clock); + publisher = new RecordingPublisher(); + dashboard = new DashboardService(state, publisher, serverApi, new VersionService(updateCheck, serverApi, clock), updateCheck, MAPPER, executor, clock); dashboard.start(); } @@ -118,16 +94,11 @@ private void create() { create(Runnable::run); } - @AfterEach - void tearDown() { - broadcasters.forEach(ClientEventBroadcaster::shutdown); - } - - private RecordingEmitter subscribe() { - return (RecordingEmitter) dashboard.subscribe().orElseThrow(); + private RecordingPublisher subscribe() { + return dashboard.subscribe(publisher::subscribe).orElseThrow(); } - private static List drain(RecordingEmitter emitter) throws InterruptedException { + private static List drain(RecordingPublisher emitter) throws InterruptedException { List events = new ArrayList<>(); String next; while ((next = emitter.sent.poll(150, TimeUnit.MILLISECONDS)) != null) { @@ -136,6 +107,12 @@ private static List drain(RecordingEmitter emitter) throws InterruptedEx 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:")) { @@ -150,7 +127,7 @@ private static List names(List events) { } private void advance(Duration duration) { - now.set(now.get().plus(duration)); + clock.advance(duration); } @Test @@ -174,17 +151,19 @@ void aFirstSubscriberGetsOneFullSnapshotThatReflectsEverythingTheModelHolds() th state.setActiveServer(A); create(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); String snapshot = browser.next(); assertEquals("snapshot", nameOf(snapshot)); - assertTrue(snapshot.contains("\"activeServer\":\"" + A + "\""), snapshot); - assertTrue(snapshot.contains("\"knownServers\":[\"" + A + "\"]"), snapshot); - assertTrue(snapshot.contains("\"link\":\"DEGRADED\""), snapshot); - assertTrue(snapshot.contains("\"running\":false"), snapshot); - assertTrue(snapshot.contains("\"health\":{\"backupInterval\":\"PT6H\",\"backupRetentionCount\":5}"), snapshot); - assertTrue(snapshot.contains("\"versions\":{\"client\":{"), snapshot); - assertTrue(snapshot.contains("\"latestVersion\":\"0.2.0\""), 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()); } @@ -195,12 +174,14 @@ void aLateSubscriberGetsTheLatestSnapshotFollowedByGranularEvents() throws Excep dashboard.streamUp(A); dashboard.runEvent(A, "run-started", "{\"running\":true,\"startedAt\":\"t\"}", true); - RecordingEmitter browser = subscribe(); + 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)); - assertTrue(events.get(0).contains("\"link\":\"LIVE\"") && events.get(0).contains("\"running\":true"), events.get(0)); + 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)); } @@ -235,7 +216,7 @@ void theLinkIsLiveWhileTheStreamIsUpDegradedWhenOnlyHealthAnswersAndDownOtherwis void linkChangesArePushedOnlyWhenTheStateChanges() throws Exception { state.setActiveServer(A); create(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); dashboard.streamUp(A); @@ -244,16 +225,17 @@ void linkChangesArePushedOnlyWhenTheStateChanges() throws Exception { List links = drain(browser).stream().filter(event -> nameOf(event).equals("link")).toList(); assertEquals(3, links.size()); - assertTrue(links.get(0).contains("\"state\":\"LIVE\"") && links.get(0).contains("\"server\":\"" + A + "\"")); - assertTrue(links.get(1).contains("\"state\":\"CONNECTING\"")); - assertTrue(links.get(2).contains("\"state\":\"DEGRADED\"")); + 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(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); clearInvocations(serverApi); @@ -273,7 +255,7 @@ void pollsHealthEverySevenToEightSecondsWhileNotLiveAndFeedsTheState() throws Ex dashboard.tick(); List events = drain(browser); assertEquals(List.of("state"), names(events)); - assertTrue(events.get(0).contains("\"running\":false")); + assertFalse(RecordingPublisher.data(events.get(0)).path("running").asBoolean(true)); assertEquals(false, dashboard.state().running()); advance(Duration.ofSeconds(8)); @@ -285,7 +267,7 @@ void pollsHealthEverySevenToEightSecondsWhileNotLiveAndFeedsTheState() throws Ex void aFailedPollMakesTheLinkDownAndASuccessfulOneRecoversIt() throws Exception { state.setActiveServer(A); create(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); doThrow(new ResourceAccessException("refused")).when(serverApi).health(A); @@ -327,7 +309,7 @@ void aLiveLinkIgnoresPollResultsForLinkAndRunningButKeepsTheHealthSummary() thro create(); dashboard.streamUp(A); dashboard.runEvent(A, "state", "{\"running\":false}", false); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); doReturn(new ServerStatusDto(true, true, 9, Duration.ofHours(1))).when(serverApi).health(A); @@ -346,7 +328,7 @@ void streamEventsAreForwardedAndKeepRunningInStep() throws Exception { state.setActiveServer(A); create(); dashboard.streamUp(A); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); dashboard.runEvent(A, "state", "{\"running\":false,\"at\":\"t\"}", false); @@ -366,7 +348,7 @@ void aConfigChangedEventRefetchesHealthOnceAndPushesTheSummaryOnlyWhenItChanged( state.setActiveServer(A); create(); dashboard.streamUp(A); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); clearInvocations(serverApi); @@ -390,7 +372,7 @@ void eventsFromAServerThatIsNoLongerActiveAreIgnored() throws Exception { dashboard.streamUp(A); state.setActiveServer(B); dashboard.sync(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); clearInvocations(serverApi); @@ -411,7 +393,7 @@ void switchingServersPushesASnapshotThatClearsEverythingAboutTheOldOne() throws create(); dashboard.streamUp(A); dashboard.runEvent(A, "state", "{\"running\":true}", true); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); doThrow(new ResourceAccessException("refused")).when(serverApi).health(B); @@ -421,10 +403,14 @@ void switchingServersPushesASnapshotThatClearsEverythingAboutTheOldOne() throws List events = drain(browser); assertEquals(List.of("snapshot", "link", "versions"), names(events)); String snapshot = events.get(0); - assertTrue(snapshot.contains("\"activeServer\":\"" + B + "\""), snapshot); - assertTrue(snapshot.contains("\"knownServers\":[\"" + A + "\",\"" + B + "\"]"), snapshot); - assertTrue(snapshot.contains("\"link\":\"CONNECTING\"") && snapshot.contains("\"running\":null") && snapshot.contains("\"health\":null"), snapshot); - assertTrue(snapshot.contains("\"server\":{\"currentVersion\":null") && snapshot.contains("\"checkState\":\"NOT_CHECKED\""), snapshot); + 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 @@ -453,7 +439,7 @@ void clearingTheActiveServerGoesDownWithoutPolling() throws Exception { state.setActiveServer(A); create(); dashboard.streamUp(A); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); clearInvocations(serverApi); @@ -464,7 +450,8 @@ void clearingTheActiveServerGoesDownWithoutPolling() throws Exception { List events = drain(browser); assertEquals(List.of("snapshot"), names(events)); - assertTrue(events.get(0).contains("\"activeServer\":null") && events.get(0).contains("\"link\":\"DOWN\"")); + assertTrue(RecordingPublisher.data(events.get(0)).path("activeServer").isNull()); + assertEquals("DOWN", RecordingPublisher.data(events.get(0)).path("link").asString()); verify(serverApi, never()).health(anyString()); } @@ -472,7 +459,7 @@ void clearingTheActiveServerGoesDownWithoutPolling() throws Exception { void knownServerChangesArePushedOnceAndWithoutASnapshotWhenTheActiveServerStaysTheSame() throws Exception { state.setActiveServer(A); create(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); state.updateKnownServers(List.of(A, B)); @@ -486,7 +473,7 @@ void knownServerChangesArePushedOnceAndWithoutASnapshotWhenTheActiveServerStaysT void aDiscoveryThatPicksTheFirstActiveServerPushesOneSnapshot() throws Exception { when(serverApi.health(anyString())).thenThrow(new ResourceAccessException("refused")); create(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); state.updateKnownServers(List.of(A, B)); @@ -502,7 +489,7 @@ void theServerVersionIsFetchedOnLinkUpAndAServerSwitchNotOnEveryRead() throws Ex verify(serverApi, times(1)).serverVersion(A); dashboard.state(); - dashboard.subscribe(); + dashboard.subscribe(publisher::subscribe); dashboard.state(); verify(serverApi, times(1)).serverVersion(A); @@ -528,7 +515,7 @@ void theServerVersionIsRefetchedAtMostHourlyAndPushedWhenItChanges() throws Exce state.setActiveServer(A); create(); dashboard.streamUp(A); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); clearInvocations(serverApi); @@ -543,7 +530,7 @@ void theServerVersionIsRefetchedAtMostHourlyAndPushedWhenItChanges() throws Exce verify(serverApi, times(1)).serverVersion(A); List events = drain(browser).stream().filter(event -> nameOf(event).equals("versions")).toList(); assertEquals(1, events.size()); - assertTrue(events.get(0).contains("\"server\":{\"currentVersion\":\"0.2.0\""), events.get(0)); + assertEquals("0.2.0", RecordingPublisher.data(events.get(0)).path("server").path("currentVersion").asString()); } @Test @@ -553,7 +540,7 @@ void theClientsOwnUpdateCheckIsPushedAsAVersionsEvent() throws Exception { create(); ArgumentCaptor> listener = ArgumentCaptor.forClass(Consumer.class); verify(updateCheck).addStatusListener(listener.capture()); - RecordingEmitter browser = subscribe(); + 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); @@ -562,8 +549,10 @@ void theClientsOwnUpdateCheckIsPushedAsAVersionsEvent() throws Exception { List events = drain(browser); assertEquals(List.of("versions"), names(events)); - assertTrue(events.get(0).contains("\"latestVersion\":\"0.3.0\"") && events.get(0).contains("\"updateAvailable\":true"), events.get(0)); - assertTrue(events.get(0).contains("\"server\":{")); + 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 @@ -604,7 +593,7 @@ void aServerIsConnectingUntilItsFirstAnswerAndOnlyThenDownWithAnUnavailableVersi state.setActiveServer(A); doThrow(new ResourceAccessException("refused")).when(serverApi).health(A); create(queued::add); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); DashboardState before = dashboard.state(); @@ -639,7 +628,7 @@ void aServerVersionThatWasNotCheckedYetIsFetchedAgainWithinHalfAMinute() throws doReturn(notChecked).doReturn(notChecked).doReturn(SERVER_VERSION).when(serverApi).serverVersion(A); create(); dashboard.streamUp(A); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); clearInvocations(serverApi); @@ -654,7 +643,7 @@ void aServerVersionThatWasNotCheckedYetIsFetchedAgainWithinHalfAMinute() throws assertEquals(CheckState.OK, dashboard.state().versions().server().checkState()); List events = drain(browser).stream().filter(event -> nameOf(event).equals("versions")).toList(); assertEquals(1, events.size()); - assertTrue(events.get(0).contains("\"checkState\":\"OK\""), events.get(0)); + assertEquals("OK", RecordingPublisher.data(events.get(0)).path("server").path("checkState").asString()); } @Test @@ -677,7 +666,7 @@ void whileDegradedTheClientChecksTheArchiveListOncePerMinuteAndPushesBackupsChan 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(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); advance(Duration.ofSeconds(8)); @@ -695,7 +684,7 @@ void whileDegradedTheClientChecksTheArchiveListOncePerMinuteAndPushesBackupsChan verify(serverApi, times(2)).listBackups(A); List events = drain(browser).stream().filter(event -> nameOf(event).equals("backups-changed")).toList(); assertEquals(1, events.size()); - assertTrue(events.get(0).contains("\"at\":\"2026-11-12T10:01:09Z\""), events.get(0)); + assertEquals("2026-11-12T10:01:09Z", RecordingPublisher.data(events.get(0)).path("at").asString()); advance(Duration.ofSeconds(61)); dashboard.tick(); @@ -725,7 +714,7 @@ void aRunThatFinishesWhileDegradedRebaselinesTheArchiveListInsteadOfAnnouncingIt create(); advance(Duration.ofSeconds(8)); dashboard.tick(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); doReturn(IDLE).when(serverApi).health(A); @@ -780,4 +769,79 @@ void aFailingArchiveListingIsRetriedOnlyOncePerMinute() { 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 index b28b7c1..92f90db 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/SemVerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/SemVerTest.java @@ -8,6 +8,7 @@ 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 { @@ -30,16 +31,12 @@ void parsesPrereleaseAndIgnoresBuildMetadata() { } @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 rejectsNull() { - assertEquals(Optional.empty(), SemVer.parse(null)); - } - @Test void comparesNumericallyNotLexically() { assertTrue(v("0.10.0").compareTo(v("0.9.0")) > 0); diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java index 9b41876..cd76332 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java @@ -2,8 +2,10 @@ 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; @@ -15,6 +17,7 @@ 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; @@ -29,11 +32,15 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; -import wellatleastitried.mediagarrdclient.Configuration; +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 { @@ -42,12 +49,15 @@ private record Exchange(String method, String path, String body) { } private final List exchanges = new ArrayList<>(); - private final ServerApiService service = new ServerApiService(Duration.ofHours(6)); + 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 @@ -64,6 +74,76 @@ void stopServer() { 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\"}"; @@ -85,6 +165,56 @@ void readsTheServerVersionStatusAndIgnoresUnknownFields() { 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\"}"; @@ -129,9 +259,41 @@ void fallsBackToTheStatusWhenTheServerSendsNoMessage() { 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)); + ServerApiService shortTimeout = new ServerApiService(Duration.ofMillis(200), url -> token, ServerTls.defaults()); delay = Duration.ofSeconds(2); BackupRunTimeoutException e = assertThrows(BackupRunTimeoutException.class, () -> shortTimeout.triggerBackup(serverUrl)); @@ -143,15 +305,6 @@ void reportsABackupRunThatOutlastsTheTimeout() { assertTrue(e.getMessage().contains("still running on the server")); } - @Test - void waitsForABackupRunWithinTheTimeout() { - delay = Duration.ofMillis(300); - - service.triggerBackup(serverUrl); - - assertEquals(1, exchanges.size()); - } - @Test void rejectsABackupRunTimeoutBelowTheMinimum() { assertRejected(null); @@ -159,26 +312,228 @@ void rejectsABackupRunTimeoutBelowTheMinimum() { assertRejected(Duration.ZERO); IllegalStateException e = assertRejected(Duration.ofSeconds(59)); assertTrue(e.getMessage().contains("at least PT1M")); - Configuration ok = new Configuration(); + MediaGarrdProperties ok = new MediaGarrdProperties(); ok.setBackupRunTimeout(Duration.ofMinutes(1)); - new ServerApiService(ok); + new ServerApiService(ok, mock(ClientStateService.class), ServerTls.defaults()); } private static IllegalStateException assertRejected(Duration timeout) { - Configuration properties = new Configuration(); + MediaGarrdProperties properties = new MediaGarrdProperties(); properties.setBackupRunTimeout(timeout); - return assertThrows(IllegalStateException.class, () -> new ServerApiService(properties)); + return assertThrows(IllegalStateException.class, () -> new ServerApiService(properties, mock(ClientStateService.class), ServerTls.defaults())); } @Test void mapsAReadTimeoutOnTheOrdinaryClientsToGatewayTimeout() { - delay = Duration.ofSeconds(8); - ResourceAccessException e = assertThrows(ResourceAccessException.class, () -> service.health(serverUrl)); + 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"); @@ -194,6 +549,9 @@ 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 @@ -205,14 +563,10 @@ void treatsAConnectTimeoutAsATimeoutButNotAsAReadTimeout() { assertEquals(HttpStatus.GATEWAY_TIMEOUT, new ApiExceptionHandler().serverUnreachable((ResourceAccessException) connect).getStatusCode()); } - @Test - void doesNotReportAnUnreachableServerAsATimeout() { - assertThrows(ResourceAccessException.class, () -> service.triggerBackup("http://127.0.0.1:1")); - } - 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) { @@ -220,6 +574,9 @@ private void handle(HttpExchange exchange) throws IOException { } 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 { diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java index af19981..462bf83 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java @@ -27,6 +27,7 @@ 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; @@ -37,10 +38,10 @@ import org.junit.jupiter.params.provider.CsvSource; import org.springframework.scheduling.annotation.Scheduled; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; import com.sun.net.httpserver.HttpServer; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService.HostInput; @Timeout(10) @@ -48,9 +49,9 @@ class ServerDiscoveryServiceTest { private static final String HEALTH = "{\"healthy\":true,\"running\":false,\"backupRetentionCount\":4,\"backupInterval\":\"PT6H\"}"; - private final Configuration configuration = new Configuration(); + private final MediaGarrdProperties configuration = new MediaGarrdProperties(); private final ClientStateService state = mock(ClientStateService.class); - private final ServerDiscoveryService discovery = new ServerDiscoveryService(configuration, state, new ObjectMapper()); + private final ServerDiscoveryService discovery = new ServerDiscoveryService(configuration, state, JsonMapper.builder().build(), ServerTls.defaults()); private HttpServer mediaGarrd; private HttpServer otherApp; @@ -88,32 +89,15 @@ void scansEveryPortWhenTheGivenPortIsNotAMediaGarrdServer() { assertTrue(Duration.ofNanos(System.nanoTime() - start).toSeconds() < 15, "full port scan took too long"); } - @Test - void preferredServerIsResolvedFromConfiguration() { - configuration.setPreferredServerIp("localhost:" + port(mediaGarrd)); - - assertEquals(Optional.of("http://localhost:" + port(mediaGarrd)), discovery.resolvePreferredServer()); - } - @Test void connectsThePreferredServerOnlyWhileNoneIsSelected() { - configuration.setPreferredServerIp("127.0.0.1:" + port(mediaGarrd)); + configuration.setPreferredServerIp("localhost:" + port(mediaGarrd)); discovery.connectPreferredServer(); when(state.getActiveServer()).thenReturn("http://other:38471"); discovery.connectPreferredServer(); - verify(state, times(1)).setActiveServerIfBlank(url(mediaGarrd)); - } - - @Test - void retriesQuicklyWhileNoServerIsSelected() throws NoSuchMethodException { - Scheduled schedule = ServerDiscoveryService.class.getMethod("connectPreferredServer").getAnnotation(Scheduled.class); - - assertTrue(schedule.fixedDelay() >= 1_000 && schedule.fixedDelay() <= 5_000, - "connectPreferredServer must use a numeric fixedDelay of 1-5 s, found " + schedule.fixedDelay() + " ms (fixedDelayString='" + schedule.fixedDelayString() + "')"); - assertTrue(schedule.initialDelay() >= 0 && schedule.initialDelay() <= 5_000, - "connectPreferredServer must use a numeric initialDelay of at most 5 s, found " + schedule.initialDelay() + " ms (initialDelayString='" + schedule.initialDelayString() + "')"); + verify(state, times(1)).setActiveServerIfBlank("http://localhost:" + port(mediaGarrd)); } @Test @@ -141,9 +125,10 @@ void keepsRetryingUntilThePreferredServerComesUp() throws IOException { 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, new ObjectMapper(), pool, deadline) { + ServerDiscoveryService hanging = new ServerDiscoveryService(configuration, state, JsonMapper.builder().build(), ServerTls.defaults(), pool, deadline) { @Override public Optional resolvePreferredServer() { attempts.incrementAndGet(); @@ -154,14 +139,13 @@ public Optional resolvePreferredServer() { } catch (InterruptedException ignored) { } } + resolveFinished.set(true); return Optional.empty(); } }; try { - long start = System.nanoTime(); hanging.connectPreferredServer(); - long elapsed = Duration.ofNanos(System.nanoTime() - start).toMillis(); - assertTrue(elapsed < deadline.toMillis() + 1_500, "tick blocked for " + elapsed + " ms"); + assertFalse(resolveFinished.get(), "the tick waited for the hanging resolve instead of abandoning it at the deadline"); hanging.connectPreferredServer(); hanging.connectPreferredServer(); @@ -214,7 +198,7 @@ public boolean awaitTermination(long timeout, TimeUnit unit) { return true; } }; - ServerDiscoveryService service = new ServerDiscoveryService(configuration, state, new ObjectMapper(), deferred, Duration.ofMillis(100)); + ServerDiscoveryService service = new ServerDiscoveryService(configuration, state, JsonMapper.builder().build(), ServerTls.defaults(), deferred, Duration.ofMillis(100)); service.connectPreferredServer(); assertEquals(1, queued.size()); @@ -280,7 +264,7 @@ void listsTheHostsOfTheLocalSubnet(int prefix, int count, String first, String l @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(host, port), ServerDiscoveryService.parseHost(input)); + assertEquals(new HostInput("http", host, port), ServerDiscoveryService.parseHost(input)); } @Test @@ -317,4 +301,56 @@ private static int port(HttpServer server) { 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 index fb8dd88..6f645da 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamServiceTest.java @@ -6,11 +6,8 @@ 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.clearInvocations; -import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.timeout; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; @@ -24,12 +21,16 @@ 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; @@ -38,17 +39,17 @@ import org.junit.jupiter.api.io.TempDir; import org.springframework.web.client.ResourceAccessException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.databind.json.JsonMapper; +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.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; import wellatleastitried.mediagarrdclient.dto.CheckState; import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; -import wellatleastitried.mediagarrdclient.service.ClientEventBroadcasterTest.RecordingEmitter; import wellatleastitried.mediagarrdclient.service.ServerEventStreamService.Timing; @Timeout(30) @@ -56,7 +57,7 @@ class ServerEventStreamServiceTest { private static final ObjectMapper MAPPER = JsonMapper.builder() .findAndAddModules() - .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) + .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); @@ -71,12 +72,14 @@ static final class FakeServer { 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); @@ -110,32 +113,28 @@ void stop() { Path tempDir; private ClientStateService state; - private ClientEventBroadcaster broadcaster; + private RecordingPublisher publisher; private DashboardService dashboard; private ServerApiService serverApi; private ExecutorService refreshes; private ServerEventStreamService service; - private RecordingEmitter browser; + private RecordingPublisher browser; private final List servers = new ArrayList<>(); @BeforeEach void setUp() { - Configuration configuration = new Configuration(); + MediaGarrdProperties configuration = new MediaGarrdProperties(); configuration.setStateFile(tempDir.resolve("state.json").toString()); configuration.setPickupInterval(Duration.ofHours(12)); state = new ClientStateService(configuration, MAPPER); - broadcaster = new ClientEventBroadcaster(Duration.ofMinutes(10), 32, 64, Duration.ofMinutes(5), Duration.ofMinutes(6), runnable -> { - Thread thread = new Thread(runnable); - thread.setDaemon(true); - return thread; - }, RecordingEmitter::new); + 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, broadcaster, serverApi, new VersionService(updateCheck, serverApi), updateCheck, MAPPER, refreshes, Clock.systemUTC()); + dashboard = new DashboardService(state, publisher, serverApi, new VersionService(updateCheck, serverApi), updateCheck, MAPPER, refreshes, Clock.systemUTC()); } @AfterEach @@ -143,11 +142,15 @@ void tearDown() { if (service != null) { service.shutdown(); } - broadcaster.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); @@ -155,8 +158,8 @@ private FakeServer fake(Behavior behavior) throws IOException { } private void startService(Timing timing) { - service = new ServerEventStreamService(state, dashboard, MAPPER, timing); - browser = (RecordingEmitter) dashboard.subscribe().orElseThrow(); + service = new ServerEventStreamService(state, dashboard, MAPPER, ServerTls.defaults(), timing); + browser = dashboard.subscribe(publisher::subscribe).orElseThrow(); service.start(); } @@ -215,29 +218,80 @@ void forwardsRunEventsAndIgnoresEverythingElse() throws Exception { frame(out, "event:run-finished\ndata:{\"running\":false,\"status\":\"PARTIAL\",\"startedAt\":\"t1\",\"finishedAt\":\"t2\"}\n\n"); hold(); }); - state.setActiveServer(fake.url()); + activate(fake.url()); startService(FAST); List seen = collectUntil("event:run-finished"); - List relevant = seen.stream().filter(event -> !event.contains("event:versions") && !(event.contains("event:link") && event.contains("\"state\":\"DOWN\""))).toList(); + 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(relevant.get(0).contains("\"activeServer\":null")); - assertTrue(relevant.get(1).contains("\"activeServer\":\"" + fake.url() + "\"") && relevant.get(1).contains("\"link\":\"CONNECTING\"")); - assertTrue(relevant.get(2).contains("\"state\":\"LIVE\"") && relevant.get(2).contains(fake.url())); - assertTrue(relevant.get(4).contains("\"startedAt\":\"t1\"")); - assertEquals("event:backups-changed\ndata:{\"at\":\"t3\"}\n\n", relevant.get(5)); - assertTrue(relevant.get(6).contains("\"status\":\"PARTIAL\"")); + 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) { - for (String line : event.split("\n")) { - if (line.startsWith("event:")) { - return line.substring("event:".length()); + 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; } } - return ""; + } + + 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 { @@ -253,7 +307,7 @@ void reconnectsRightAwayAfterACleanEndWithoutFlickeringTheLink() throws Exceptio hold(); } }); - state.setActiveServer(fake.url()); + activate(fake.url()); startService(FAST); @@ -262,33 +316,42 @@ void reconnectsRightAwayAfterACleanEndWithoutFlickeringTheLink() throws Exceptio List seen = collectUntil("\"running\":false"); int connectedAt = -1; for (int i = 0; i < seen.size(); i++) { - if (seen.get(i).contains("event:link") && seen.get(i).contains("\"state\":\"LIVE\"")) { + 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 -> event.contains("event:link") && event.contains("\"state\":\"DOWN\""))); + 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(); }); - state.setActiveServer(fake.url()); + 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(seen.stream().anyMatch(event -> event.contains("event:link") && event.contains("\"state\":\"LIVE\""))); + 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 @@ -304,12 +367,12 @@ void rejectsAResponseThatIsNotAnEventStream() throws Exception { frame(out, "event: state\ndata: {\"running\":false}\n\n"); hold(); }); - state.setActiveServer(fake.url()); + activate(fake.url()); startService(FAST); List seen = collectUntil("event:state"); - assertTrue(seen.get(seen.size() - 1).contains("\"running\":false")); + assertFalse(dataOf(seen.get(seen.size() - 1)).path("running").asBoolean(true)); assertEquals(2, fake.count.get()); } @@ -324,7 +387,7 @@ void anOldServerWithoutTheStreamIsRetriedOnlyAfterTheLongInterval() throws Excep frame(out, "event: state\ndata: {\"running\":false}\n\n"); hold(); }); - state.setActiveServer(fake.url()); + activate(fake.url()); startService(FAST); @@ -339,16 +402,17 @@ void movingToAnotherServerClosesTheOldStreamAndSubscribesToTheNewOne() throws Ex 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")); - state.setActiveServer(old.url()); + activate(old.url()); startService(FAST); collectUntil("\"running\":true"); - state.setActiveServer(next.url()); + 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 -> event.contains("event:snapshot") && event.contains("\"activeServer\":\"" + next.url() + "\"") && event.contains("\"running\":null"))); - assertTrue(seen.stream().anyMatch(event -> event.contains("event:link") && event.contains("\"state\":\"LIVE\"") && event.contains(next.url()))); + 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()); } @@ -356,7 +420,7 @@ void movingToAnotherServerClosesTheOldStreamAndSubscribesToTheNewOne() throws Ex void clearingTheActiveServerStopsTheStreamAndDoesNotReconnect() throws Exception { CountDownLatch closed = new CountDownLatch(1); FakeServer fake = fake(holdOpen(closed, "event: state\ndata: {\"running\":true}\n\n")); - state.setActiveServer(fake.url()); + activate(fake.url()); startService(FAST); collectUntil("\"running\":true"); @@ -364,7 +428,8 @@ void clearingTheActiveServerStopsTheStreamAndDoesNotReconnect() throws Exception assertTrue(closed.await(10, TimeUnit.SECONDS)); String cleared = browser.nextContaining("\"activeServer\":null"); - assertTrue(cleared.contains("event:snapshot") && cleared.contains("\"link\":\"DOWN\""), cleared); + assertEquals("snapshot", nameOf(cleared)); + assertEquals("DOWN", dataOf(cleared).path("link").asString(), cleared); assertEquals(1, fake.count.get()); } @@ -373,8 +438,10 @@ void doesNotConnectWithoutAnActiveServer() throws Exception { startService(FAST); String snapshot = browser.next(); - assertTrue(snapshot.contains("event:snapshot") && snapshot.contains("\"link\":\"DOWN\"")); - assertNull(browser.sent.poll(200, TimeUnit.MILLISECONDS)); + assertEquals("snapshot", nameOf(snapshot)); + assertEquals("DOWN", dataOf(snapshot).path("link").asString()); + assertTrue(streamThreads().isEmpty()); + assertNull(browser.sent.poll()); } @Test @@ -385,21 +452,27 @@ void reconnectsAStreamThatGoesSilent() throws Exception { frame(out, "event: state\ndata: {\"running\":" + (connection == 1) + "}\n\n"); hold(); }); - state.setActiveServer(fake.url()); + activate(fake.url()); startService(quick); fake.awaitConnection(); fake.awaitConnection(); List seen = collectUntil("\"running\":false"); - assertFalse(seen.isEmpty()); + 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")); - state.setActiveServer(fake.url()); - Configuration configuration = new Configuration(); + activate(fake.url()); + MediaGarrdProperties configuration = new MediaGarrdProperties(); configuration.setStateFile(tempDir.resolve("state.json").toString()); configuration.setPickupInterval(Duration.ofHours(12)); state = new ClientStateService(configuration, MAPPER); @@ -417,7 +490,7 @@ void aStreamThatEndsRightAfterOpeningIsRetriedWithBackoffInsteadOfInALoop() thro OutputStream out = open(exchange); frame(out, "event: state\ndata: {\"running\":false}\n\n"); }); - state.setActiveServer(fake.url()); + activate(fake.url()); startService(slowRetry); @@ -429,23 +502,292 @@ void aStreamThatEndsRightAfterOpeningIsRetriedWithBackoffInsteadOfInALoop() thro } @Test - void aConfigChangedEventMakesTheClientRefetchTheServerHealthOnce() throws Exception { - doReturn(new ServerStatusDto(true, false, 5, Duration.ofHours(6))).when(serverApi).health(anyString()); + 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"); - Thread.sleep(2000); - frame(out, "event: config-changed\ndata: {\"at\":\"t\"}\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); - browser.nextContaining("event:config"); - Thread.sleep(800); - clearInvocations(serverApi); + 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"); - verify(serverApi, timeout(10_000).times(1)).health(fake.url()); + 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 index 4310a64..af76343 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/UpdateCheckServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/UpdateCheckServiceTest.java @@ -19,11 +19,14 @@ 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.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; import wellatleastitried.mediagarrdclient.dto.CheckState; import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; @@ -33,7 +36,7 @@ class UpdateCheckServiceTest { private final List requests = new ArrayList<>(); private final List userAgents = new ArrayList<>(); - private final Configuration properties = new Configuration(); + private final MediaGarrdProperties properties = new MediaGarrdProperties(); private HttpServer server; private int status = 200; private String rateLimitRemaining; @@ -119,36 +122,16 @@ void reportsAnUpdateWhenTheLatestReleaseIsNewer() { assertEquals(List.of("MediaGarrd-Client/0.1.0"), userAgents); } - @Test - void reportsUpToDateWhenTheLatestReleaseIsTheSameVersion() { - response = release("v0.1.0"); - UpdateCheckService service = service("0.1.0"); - - service.check(); - - assertEquals(CheckState.OK, service.status().checkState()); - assertEquals("0.1.0", service.status().latestVersion()); - assertFalse(service.status().updateAvailable()); - } - - @Test - void neverReportsAnOlderReleaseAsAnUpdate() { - response = release("v0.1.0"); - UpdateCheckService service = service("0.2.0"); + @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()); - assertFalse(service.status().updateAvailable()); - } - - @Test - void treatsAPrereleaseOfTheRunningVersionAsOlder() { - response = release("v0.2.0-rc.1"); - UpdateCheckService service = service("0.2.0"); - - service.check(); - + assertEquals(latest, service.status().latestVersion()); assertFalse(service.status().updateAvailable()); } @@ -268,9 +251,10 @@ void reportsAnErrorWithoutCallingGithubWhenTheCurrentVersionIsUnknown() { assertTrue(requests.isEmpty()); } - @Test - void buildsTheReleaseUrlWhenGithubOmitsIt() { - response = "{\"tag_name\": \"v0.3.0\"}"; + @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(); diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java index 6cb5e16..85f64e2 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java @@ -11,11 +11,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.time.Clock; import java.time.Duration; import java.time.Instant; -import java.time.ZoneId; -import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; import org.springframework.web.client.ResourceAccessException; @@ -32,23 +29,7 @@ class VersionServiceTest { 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 AtomicReference now = new AtomicReference<>(NOW); - private final Clock clock = new Clock() { - @Override - public java.time.ZoneId getZone() { - return ZoneId.of("UTC"); - } - - @Override - public Clock withZone(ZoneId zone) { - return this; - } - - @Override - public Instant instant() { - return now.get(); - } - }; + 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); @@ -96,16 +77,16 @@ void refetchesAtMostHourlyAndAtOnceAfterAnInvalidation() { service.select(URL); service.refresh(); - now.set(NOW.plus(Duration.ofMinutes(59))); + clock.set(NOW.plus(Duration.ofMinutes(59))); assertFalse(service.needsRefresh()); - now.set(NOW.plus(Duration.ofHours(1))); + clock.set(NOW.plus(Duration.ofHours(1))); assertTrue(service.needsRefresh()); service.refresh(); assertFalse(service.needsRefresh()); assertFalse(service.invalidate(false)); assertFalse(service.needsRefresh()); - now.set(now.get().plus(Duration.ofMinutes(6))); + clock.set(clock.instant().plus(Duration.ofMinutes(6))); assertTrue(service.invalidate(false)); assertTrue(service.needsRefresh()); } @@ -117,14 +98,14 @@ void aServerThatHasNotCheckedYetIsAskedAgainAfterThirtySeconds() { service.select(URL); service.refresh(); - now.set(NOW.plus(Duration.ofSeconds(29))); + clock.set(NOW.plus(Duration.ofSeconds(29))); assertFalse(service.needsRefresh()); - now.set(NOW.plus(Duration.ofSeconds(30))); + clock.set(NOW.plus(Duration.ofSeconds(30))); assertTrue(service.needsRefresh()); assertTrue(service.refresh()); assertEquals(CheckState.OK, service.versions().server().checkState()); - now.set(NOW.plus(Duration.ofMinutes(10))); + clock.set(NOW.plus(Duration.ofMinutes(10))); assertFalse(service.needsRefresh()); } @@ -135,9 +116,9 @@ void aServerThatReportedAnErrorIsAskedAgainAfterFiveMinutes() { service.select(URL); service.refresh(); - now.set(NOW.plus(Duration.ofMinutes(4))); + clock.set(NOW.plus(Duration.ofMinutes(4))); assertFalse(service.needsRefresh()); - now.set(NOW.plus(Duration.ofMinutes(5))); + clock.set(NOW.plus(Duration.ofMinutes(5))); assertTrue(service.needsRefresh()); assertTrue(service.invalidate(false)); } @@ -196,9 +177,9 @@ void reportsTheServerAsUnavailableWhenItCannotBeReachedAndRetriesSooner() { assertEquals(CLIENT, result.client()); assertEquals(CheckState.UNAVAILABLE, result.server().checkState()); assertFalse(result.server().updateAvailable()); - now.set(NOW.plus(Duration.ofMinutes(9))); + clock.set(NOW.plus(Duration.ofMinutes(9))); assertFalse(service.needsRefresh()); - now.set(NOW.plus(Duration.ofMinutes(10))); + clock.set(NOW.plus(Duration.ofMinutes(10))); assertTrue(service.needsRefresh()); } 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 index 501ae08..cfaf3c8 100644 --- a/src/test/js/dashboard-model.test.mjs +++ b/src/test/js/dashboard-model.test.mjs @@ -141,13 +141,6 @@ test('a run finishing reloads the backups, however it was learned', () => { assert.equal(changes(idle, reduce(idle, 'run-started', {}), 'run-started').refreshBackups, false); }); -test('a backups-changed announcement reloads the backups while the server is up', () => { - const state = loaded(); - assert.equal(changes(state, reduce(state, 'backups-changed', {}), 'backups-changed').refreshBackups, true); - const down = loaded({ link: 'DOWN' }); - assert.equal(changes(down, reduce(down, 'backups-changed', {}), 'backups-changed').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); @@ -200,3 +193,23 @@ test('a connecting link forgets the run state and a first answer reloads the bac 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/view-model.test.mjs b/src/test/js/view-model.test.mjs index 3a3f8ba..83b4949 100644 --- a/src/test/js/view-model.test.mjs +++ b/src/test/js/view-model.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { emptyState, reduce } from '../../main/resources/static/js/dashboard-model.js'; -import { classifyVersion, linkView, planKnown, versionsView } from '../../main/resources/static/js/view-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', @@ -32,7 +32,7 @@ test('a live server shows its details and the host in the badge', () => { test('a degraded server looks connected but says live updates are unavailable', () => { const view = linkView(loaded({ link: 'DEGRADED' })); - assert.equal(view.badge.kind, 'ok'); + assert.equal(view.badge.kind, 'degraded'); assert.equal(view.showDetails, true); assert.equal(view.degraded, true); }); @@ -140,3 +140,39 @@ test('a server that has not answered yet is connecting, not unreachable', () => 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*