diff --git a/.env.example b/.env.example index 7820621..14014ae 100644 --- a/.env.example +++ b/.env.example @@ -21,7 +21,6 @@ MAIL_PASSWORD= # --- Allowed CORS origins (full URLs, no trailing slash) --- FRONTEND_BASEURL=https://lensbridge.tech -MUSALLAHBOARD_BASEURL=https://musallah.lensbridge.tech # --- MusallahBoard --- MUSALLAHBOARD_ENROLLMENT_TOKEN_PEPPER= diff --git a/docker-compose.yml b/docker-compose.yml index a3d59ec..ea27b75 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -41,7 +41,6 @@ services: MAIL_USERNAME: ${MAIL_USERNAME} MAIL_PASSWORD: ${MAIL_PASSWORD} FRONTEND_BASEURL: ${FRONTEND_BASEURL} - MUSALLAHBOARD_BASEURL: ${MUSALLAHBOARD_BASEURL} SPRINGDOC_API_DOCS_ENABLED: ${SPRINGDOC_API_DOCS_ENABLED:-false} MUSALLAHBOARD_ENROLLMENT_TOKEN_PEPPER: ${MUSALLAHBOARD_ENROLLMENT_TOKEN_PEPPER} MUSALLAHBOARD_AGENT_WS_URL: ${MUSALLAHBOARD_AGENT_WS_URL} diff --git a/docker/nginx/nginx.conf b/docker/nginx/nginx.conf index 5527271..a41ded3 100644 --- a/docker/nginx/nginx.conf +++ b/docker/nginx/nginx.conf @@ -111,7 +111,7 @@ http { proxy_set_header Forwarded ""; proxy_set_header X-Forwarded-Prefix ""; - # WebSocket support (/api/agent/ws, /api/refresh-musallahboard, /api/dashboard/ws/**) + # WebSocket support (/api/agent/ws, /api/dashboard/ws/**) proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; diff --git a/openapi.yaml b/openapi.yaml index 9d07e0d..3bf4e8c 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -493,11 +493,46 @@ paths: schema: $ref: "#/components/schemas/MessageResponse" description: Request failed; body carries a human-readable message - summary: List every enrolled board device + summary: "List every board, connected or not" + tags: + - device-admin-controller + post: + description: "Creates the board before it is ever switched on, with no device\ + \ key. Its config, content packages and setup file work at once; it gets a\ + \ key only if it later claims online. Requires board:device:enroll." + operationId: createDevice + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/CreateDeviceRequest" + required: true + responses: + "201": + content: + application/json: + schema: + $ref: "#/components/schemas/DeviceSummary" + description: Board created + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: "Missing name or audience, or an unusable location" + default: + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: Request failed; body carries a human-readable message + summary: Add a board tags: - device-admin-controller /api/admin/board/devices/enrollment-tokens: post: + description: "The token creates a new device when used. To enroll a board already\ + \ added in the console, use POST /api/admin/board/devices/{deviceId}/enrollment-tokens." operationId: issueEnrollmentToken requestBody: content: @@ -518,7 +553,7 @@ paths: schema: $ref: "#/components/schemas/MessageResponse" description: Request failed; body carries a human-readable message - summary: Mint a one-time token a new device can exchange for an identity + summary: Mint a one-time token that enrolls a new device over SSH (legacy) tags: - device-admin-controller /api/admin/board/devices/{deviceId}: @@ -574,15 +609,28 @@ paths: application/json: schema: $ref: "#/components/schemas/DeviceSummary" - description: OK + description: Device updated + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: Blank or over-long displayName + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: No device with that id default: content: application/json: schema: $ref: "#/components/schemas/MessageResponse" description: Request failed; body carries a human-readable message + summary: Rename a board or change its audience tags: - - board-admin-controller + - device-admin-controller /api/admin/board/devices/{deviceId}/commands: get: operationId: listDeviceCommands @@ -663,6 +711,55 @@ paths: summary: Queue a command for a device tags: - device-admin-controller + /api/admin/board/devices/{deviceId}/enrollment-tokens: + post: + description: "For musallahboard-agent enroll --token on the board. The token\ + \ binds the board's key to this device, replacing any key it had (for example\ + \ after an SD card swap). Boards set up with an online setup file claim by\ + \ themselves and need no token." + operationId: issueDeviceEnrollmentToken + parameters: + - in: path + name: deviceId + required: true + schema: + type: string + format: uuid + - description: "Lifetime of the token in minutes (1-1440, default 30)" + in: query + name: expiresInMinutes + required: false + schema: + type: integer + format: int32 + responses: + "201": + content: + application/json: + schema: + $ref: "#/components/schemas/IssueEnrollmentTokenResponse" + description: Token issued; the plaintext is returned exactly once + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: No device with that id + "409": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: Device is revoked + default: + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: Request failed; body carries a human-readable message + summary: Mint a one-time token that enrolls this board over SSH (maintainers) + tags: + - device-admin-controller /api/admin/board/devices/{deviceId}/offline-bundle: get: description: "A signed .mbu content package (format version 2) holding one fully\ @@ -686,7 +783,7 @@ paths: type: integer format: int32 default: 14 - maximum: 31 + maximum: 92 minimum: 1 responses: "200": @@ -708,7 +805,7 @@ paths: application/json: schema: $ref: "#/components/schemas/MessageResponse" - description: days outside 1-31 + description: days outside 1-92 "404": content: application/json: @@ -745,8 +842,8 @@ paths: - device-admin-controller /api/admin/board/devices/{deviceId}/revoke: post: - description: "Closes any live agent session and refresh stream. Idempotent:\ - \ re-revoking an already revoked device is a no-op." + description: "Closes any live agent session. Idempotent: re-revoking an already\ + \ revoked device is a no-op." operationId: revokeDevice parameters: - in: path @@ -777,6 +874,173 @@ paths: summary: Revoke a device's enrollment tags: - device-admin-controller + /api/admin/board/devices/{deviceId}/setup-file: + get: + description: "A signed .mbu provision package (provision.json: deviceId, displayName,\ + \ sequence, issuedAt and, with online=true, backendUrl and a claimSecret).\ + \ Plugged into a fresh board on a USB stick, it makes the board this one.\ + \ Every download has a newer sequence; an online one also replaces the claim\ + \ secret, so earlier online files can no longer claim the board. Requires\ + \ board:device:enroll." + operationId: downloadSetupFile + parameters: + - in: path + name: deviceId + required: true + schema: + type: string + format: uuid + - description: "Include the backend URL and a new claim secret, for a board\ + \ that will be online. Default: an offline-only board." + in: query + name: online + required: false + schema: + type: boolean + default: false + responses: + "200": + content: + application/vnd.musallahboard.mbu: + schema: + type: string + format: binary + description: The setup file + headers: + Content-Disposition: + description: attachment; filename="musallahboard-setup-.mbu" + schema: + type: string + style: simple + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: No device with that id + "409": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: Device is revoked + "503": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: "No content signing key, or (online) no backend URL, is configured\ + \ on the server" + default: + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: Request failed; body carries a human-readable message + summary: Download a board's setup file + tags: + - device-admin-controller + /api/admin/board/devices/{deviceId}/usb-kit: + get: + description: "A zip holding one folder, MusallahBoard/, with content-.mbu,\ + \ setup-.mbu (includeSetup=true; online=true adds the backend URL and\ + \ a new claim secret), and the latest board app and arm64 agent packages from\ + \ their GitHub release channels. When a channel cannot be reached the kit\ + \ goes without that package and the X-Usb-Kit-Omitted header says why. Requires\ + \ board:device:read, and board:device:enroll with includeSetup." + operationId: downloadUsbKit + parameters: + - in: path + name: deviceId + required: true + schema: + type: string + format: uuid + - description: "Days of content, starting today in each board's timezone" + in: query + name: days + required: false + schema: + type: integer + format: int32 + default: 14 + maximum: 92 + minimum: 1 + - description: Include the board's setup file + in: query + name: includeSetup + required: false + schema: + type: boolean + default: false + - description: Make the setup file an online one (backend URL and a new claim + secret) + in: query + name: online + required: false + schema: + type: boolean + default: false + responses: + "200": + content: + application/zip: + schema: + type: string + format: binary + description: The kit + headers: + Content-Disposition: + description: attachment; filename="musallahboard-usb-kit--.zip" + schema: + type: string + style: simple + X-Usb-Kit-Omitted: + description: "Present when the kit is missing the app or agent package:\ + \ what, and why" + schema: + type: string + style: simple + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: days outside 1-92 + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: No device with that id + "409": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: Device is revoked + "502": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: A poster image could not be fetched + "503": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: "No content signing key (or, online, no backend URL) is configured" + default: + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: Request failed; body carries a human-readable message + summary: Download a USB kit for one board + tags: + - usb-kit-controller /api/admin/board/events: get: operationId: getBoardEvents @@ -1121,7 +1385,7 @@ paths: - board-admin-controller /api/admin/board/refresh: post: - operationId: refreshSignboard + operationId: refreshBoards responses: "200": content: @@ -1135,6 +1399,7 @@ paths: schema: $ref: "#/components/schemas/MessageResponse" description: Request failed; body carries a human-readable message + summary: Ask every connected board to sync its content now tags: - board-admin-controller /api/admin/board/socials: @@ -1289,6 +1554,90 @@ paths: description: Request failed; body carries a human-readable message tags: - board-admin-controller + /api/admin/board/usb-kit: + get: + description: "As the one-board kit, with the files of every board that is not\ + \ revoked. One stick then updates any of them: each board keeps only its own\ + \ files." + operationId: downloadAllBoardsUsbKit + parameters: + - description: "Days of content, starting today in each board's timezone" + in: query + name: days + required: false + schema: + type: integer + format: int32 + default: 14 + maximum: 92 + minimum: 1 + - description: Include every board's setup file + in: query + name: includeSetup + required: false + schema: + type: boolean + default: false + - description: Make the setup files online ones (backend URL and new claim secrets) + in: query + name: online + required: false + schema: + type: boolean + default: false + responses: + "200": + content: + application/zip: + schema: + type: string + format: binary + description: The kit + headers: + Content-Disposition: + description: attachment; filename="musallahboard-usb-kit-all-.zip" + schema: + type: string + style: simple + X-Usb-Kit-Omitted: + description: "Present when the kit is missing the app or agent package:\ + \ what, and why" + schema: + type: string + style: simple + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: days outside 1-92 + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: There are no boards + "502": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: A poster image could not be fetched + "503": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: "No content signing key (or, online, no backend URL) is configured" + default: + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: Request failed; body carries a human-readable message + summary: Download a USB kit for every board + tags: + - usb-kit-controller /api/admin/board/weekly-content: get: operationId: getAllWeeklyContent @@ -2126,6 +2475,54 @@ paths: description: Request failed; body carries a human-readable message tags: - admin-controller + /api/agent/claim: + post: + description: "proof is base64url(HMAC-SHA256(key = the setup file's claimSecret\ + \ bytes, msg = deviceId + \"\\n\" + publicKey)), with the lowercase deviceId\ + \ and the publicKey string exactly as sent. Idempotent: claiming again with\ + \ the same key succeeds. The response is the same as enrollment's." + operationId: claimAgent + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/AgentClaimRequest" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/AgentEnrollResponse" + description: Key bound (or already bound to this key) + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: "Malformed body, public key or proof" + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: "Unknown or revoked device, no online setup file issued for\ + \ it, or a wrong proof (a setup file older than the latest online one)" + "409": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: The device is already bound to a different key + default: + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: Request failed; body carries a human-readable message + summary: Bind a board's device key to its pre-created device (online setup file) + tags: + - agent-enrollment-controller /api/agent/content-bundle: post: description: "Device-authenticated with the X-MB-* headers (Ed25519 signature\ @@ -2181,7 +2578,7 @@ paths: application/json: schema: $ref: "#/components/schemas/MessageResponse" - description: "Malformed body, days outside 1-31, or a bad haveMedia entry" + description: "Malformed body, days outside 1-92, or a bad haveMedia entry" "401": content: application/json: @@ -3232,6 +3629,32 @@ components: $ref: "#/components/schemas/DayBucket" heading: type: string + AgentClaimRequest: + type: object + properties: + agentVersion: + type: string + maxLength: 255 + minLength: 0 + deviceId: + type: string + format: uuid + hostname: + type: string + maxLength: 255 + minLength: 0 + proof: + type: string + maxLength: 64 + minLength: 0 + publicKey: + type: string + maxLength: 64 + minLength: 0 + required: + - deviceId + - proof + - publicKey AgentEnrollRequest: type: object properties: @@ -3557,7 +3980,7 @@ components: type: integer format: int32 default: 7 - maximum: 31 + maximum: 92 minimum: 1 haveMedia: type: array @@ -3601,6 +4024,24 @@ components: - location - name - startEpochMs + CreateDeviceRequest: + type: object + properties: + audience: + type: string + enum: + - brothers + - sisters + - both + displayName: + type: string + maxLength: 255 + minLength: 0 + location: + $ref: "#/components/schemas/Location" + required: + - audience + - displayName CreatePosterRequest: type: object properties: diff --git a/src/main/java/com/ibrasoft/lensbridge/config/WebSocketConfig.java b/src/main/java/com/ibrasoft/lensbridge/config/WebSocketConfig.java index a2469c0..bc5f108 100644 --- a/src/main/java/com/ibrasoft/lensbridge/config/WebSocketConfig.java +++ b/src/main/java/com/ibrasoft/lensbridge/config/WebSocketConfig.java @@ -1,6 +1,5 @@ package com.ibrasoft.lensbridge.config; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -9,7 +8,6 @@ import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import com.ibrasoft.lensbridge.handler.AgentWebSocketHandler; -import com.ibrasoft.lensbridge.handler.BoardStreamHandler; import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration; import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; @@ -17,28 +15,15 @@ @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { - private final BoardStreamHandler boardStreamHandler; private final AgentWebSocketHandler agentWebSocketHandler; - @Value("${frontend.baseurl}") - String frontendBaseUrl; - - @Value("${musallahboard.baseurl}") - String musallahBoardBaseUrl; - - public WebSocketConfig(BoardStreamHandler boardStreamHandler, - AgentWebSocketHandler agentWebSocketHandler) { - this.boardStreamHandler = boardStreamHandler; + public WebSocketConfig(AgentWebSocketHandler agentWebSocketHandler) { this.agentWebSocketHandler = agentWebSocketHandler; } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { - // Path is the deployed kiosk's; boards scope themselves with ?deviceId=. - registry.addHandler(boardStreamHandler, "/api/refresh-musallahboard") - .setAllowedOrigins(frontendBaseUrl, musallahBoardBaseUrl); - - // Agents authenticate per-frame inside the channel; the WS upgrade itself is open. + // The only socket a board opens. Agents authenticate per-frame inside the channel; the WS upgrade itself is open. registry.addHandler(agentWebSocketHandler, "/api/agent/ws") .setAllowedOrigins("*"); } diff --git a/src/main/java/com/ibrasoft/lensbridge/config/stomp/StompConfig.java b/src/main/java/com/ibrasoft/lensbridge/config/stomp/StompConfig.java index 715c3dc..d2fc920 100644 --- a/src/main/java/com/ibrasoft/lensbridge/config/stomp/StompConfig.java +++ b/src/main/java/com/ibrasoft/lensbridge/config/stomp/StompConfig.java @@ -32,9 +32,6 @@ public class StompConfig implements WebSocketMessageBrokerConfigurer { @Value("${frontend.baseurl}") private String frontendBaseUrl; - @Value("${musallahboard.baseurl}") - private String musallahBoardBaseUrl; - @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/topic"); @@ -44,7 +41,7 @@ public void configureMessageBroker(MessageBrokerRegistry registry) { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/api/dashboard/ws") - .setAllowedOrigins(frontendBaseUrl, musallahBoardBaseUrl); + .setAllowedOrigins(frontendBaseUrl); } @Override diff --git a/src/main/java/com/ibrasoft/lensbridge/controller/AgentContentController.java b/src/main/java/com/ibrasoft/lensbridge/controller/AgentContentController.java index 9e8a6ca..951264f 100644 --- a/src/main/java/com/ibrasoft/lensbridge/controller/AgentContentController.java +++ b/src/main/java/com/ibrasoft/lensbridge/controller/AgentContentController.java @@ -80,7 +80,7 @@ public class AgentContentController { schema = @Schema(type = "string")), content = @Content(mediaType = OfflineBundleService.MBU_CONTENT_TYPE, schema = @Schema(type = "string", format = "binary"))), - @ApiResponse(responseCode = "400", description = "Malformed body, days outside 1-31, or a bad haveMedia entry", + @ApiResponse(responseCode = "400", description = "Malformed body, days outside 1-92, or a bad haveMedia entry", content = @Content(schema = @Schema(implementation = MessageResponse.class))), @ApiResponse(responseCode = "502", description = "A poster image could not be fetched; the message names the poster", content = @Content(schema = @Schema(implementation = MessageResponse.class))), diff --git a/src/main/java/com/ibrasoft/lensbridge/controller/AgentEnrollmentController.java b/src/main/java/com/ibrasoft/lensbridge/controller/AgentEnrollmentController.java index ba18289..fe883d2 100644 --- a/src/main/java/com/ibrasoft/lensbridge/controller/AgentEnrollmentController.java +++ b/src/main/java/com/ibrasoft/lensbridge/controller/AgentEnrollmentController.java @@ -1,9 +1,11 @@ package com.ibrasoft.lensbridge.controller; +import com.ibrasoft.lensbridge.dto.board.request.AgentClaimRequest; import com.ibrasoft.lensbridge.dto.board.request.AgentEnrollRequest; import com.ibrasoft.lensbridge.dto.board.response.AgentEnrollResponse; import com.ibrasoft.lensbridge.dto.auth.response.MessageResponse; import com.ibrasoft.lensbridge.exception.ApiResponseException; +import com.ibrasoft.lensbridge.service.agent.DeviceClaimService; import com.ibrasoft.lensbridge.service.agent.DeviceEnrollmentService; import com.ibrasoft.lensbridge.service.agent.DeviceEnrollmentService.Outcome; import com.ibrasoft.lensbridge.service.board.offline.ContentSigningService; @@ -24,11 +26,15 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.UUID; + /** - * Public endpoint used by a freshly-flashed agent to convert a one-time enrollment token - * into a Device row + Ed25519 public-key registration. + * The two public endpoints through which a board binds its Ed25519 device key to a device: + * the online claim (a board set up by an online setup file proves it holds the file's claim + * secret) and the legacy enrollment token (a maintainer's {@code musallahboard-agent enroll}). *

- * No auth required (the token is the credential), but rate-limiting belongs at the gateway. + * No user auth: the claim proof or the token is the credential. Both are rate-limited per + * client address by {@code RateLimitingFilter}, like every {@code /api/} path. */ @RestController @RequestMapping("/api/agent") @@ -37,11 +43,51 @@ public class AgentEnrollmentController { private final DeviceEnrollmentService enrollmentService; + private final DeviceClaimService claimService; private final ContentSigningService signingService; @Value("${musallahboard.agent.websocketUrl}") private String websocketUrl; + @Operation(operationId = "claimAgent", + summary = "Bind a board's device key to its pre-created device (online setup file)", + description = "proof is base64url(HMAC-SHA256(key = the setup file's claimSecret bytes, " + + "msg = deviceId + \"\\n\" + publicKey)), with the lowercase deviceId and the publicKey " + + "string exactly as sent. Idempotent: claiming again with the same key succeeds. " + + "The response is the same as enrollment's.") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "Key bound (or already bound to this key)"), + @ApiResponse(responseCode = "400", description = "Malformed body, public key or proof", + content = @Content(schema = @Schema(implementation = MessageResponse.class))), + @ApiResponse(responseCode = "401", description = "Unknown or revoked device, no online setup file " + + "issued for it, or a wrong proof (a setup file older than the latest online one)", + content = @Content(schema = @Schema(implementation = MessageResponse.class))), + @ApiResponse(responseCode = "409", description = "The device is already bound to a different key", + content = @Content(schema = @Schema(implementation = MessageResponse.class))) + }) + @PostMapping("/claim") + public ResponseEntity claim(@Valid @RequestBody AgentClaimRequest request, + HttpServletRequest httpRequest) { + DeviceClaimService.Outcome outcome = claimService.claim( + request.getDeviceId(), + request.getPublicKey(), + request.getProof(), + request.getAgentVersion(), + request.getHostname(), + httpRequest.getRemoteAddr()); + + return switch (outcome) { + case DeviceClaimService.Outcome.Ok ok -> ResponseEntity.ok(identity(ok.device().getId())); + case DeviceClaimService.Outcome.BadRequest bad -> throw new ApiResponseException(HttpStatus.BAD_REQUEST, + new MessageResponse(bad.reason())); + case DeviceClaimService.Outcome.Refused ignored -> throw new ApiResponseException(HttpStatus.UNAUTHORIZED, + new MessageResponse("Claim refused: unknown or revoked board, or its setup file is not the " + + "latest online one")); + case DeviceClaimService.Outcome.KeyConflict ignored -> throw new ApiResponseException(HttpStatus.CONFLICT, + new MessageResponse("This board is already bound to a different device key")); + }; + } + @Operation(operationId = "enrollAgent", summary = "Exchange a one-time enrollment token for a device identity", description = "Called once per device by the MusallahBoard agent. The returned websocketUrl is " @@ -72,16 +118,20 @@ public ResponseEntity enroll(@Valid @RequestBody AgentEnrol ); return switch (outcome) { - case Outcome.Ok ok -> ResponseEntity.ok(AgentEnrollResponse.builder() - .deviceId(ok.device().getId()) - .websocketUrl(websocketUrl) - // Pinned by the agent over this same TLS connection; empty without a key. - .contentSigningKeys(signingService.publicKeys()) - .build()); + case Outcome.Ok ok -> ResponseEntity.ok(identity(ok.device().getId())); case Outcome.InvalidPublicKey bad -> throw new ApiResponseException(HttpStatus.BAD_REQUEST, new MessageResponse("Invalid public key: " + bad.reason())); case Outcome.InvalidToken ignored -> throw new ApiResponseException(HttpStatus.UNAUTHORIZED, new MessageResponse("Enrollment token is invalid, expired, or already used")); }; } + + private AgentEnrollResponse identity(UUID deviceId) { + return AgentEnrollResponse.builder() + .deviceId(deviceId) + .websocketUrl(websocketUrl) + // Pinned by the agent over this same TLS connection; empty without a key. + .contentSigningKeys(signingService.publicKeys()) + .build(); + } } diff --git a/src/main/java/com/ibrasoft/lensbridge/controller/BoardAdminController.java b/src/main/java/com/ibrasoft/lensbridge/controller/BoardAdminController.java index 2f8ae52..cd2e63e 100644 --- a/src/main/java/com/ibrasoft/lensbridge/controller/BoardAdminController.java +++ b/src/main/java/com/ibrasoft/lensbridge/controller/BoardAdminController.java @@ -6,17 +6,13 @@ import com.ibrasoft.lensbridge.dto.board.request.UpdatePromotableSocialMediaRequest; import com.ibrasoft.lensbridge.dto.board.request.UpdateBoardConfigRequest; import com.ibrasoft.lensbridge.dto.board.request.UpdateCalendarEventRequest; -import com.ibrasoft.lensbridge.dto.board.request.UpdateDeviceRequest; import com.ibrasoft.lensbridge.dto.board.request.UpdatePosterRequest; import com.ibrasoft.lensbridge.dto.board.request.UpdateTickerRequest; import com.ibrasoft.lensbridge.dto.board.request.WeeklyContentRequest; -import com.ibrasoft.lensbridge.dto.board.response.DeviceSummary; import com.ibrasoft.lensbridge.dto.auth.response.MessageResponse; -import com.ibrasoft.lensbridge.handler.BoardStreamHandler; import com.ibrasoft.lensbridge.model.audit.AuditAction; import com.ibrasoft.lensbridge.model.board.Audience; import com.ibrasoft.lensbridge.model.board.BoardEvent; -import com.ibrasoft.lensbridge.model.board.Device; import com.ibrasoft.lensbridge.model.board.embedded.DeviceConfig; import com.ibrasoft.lensbridge.model.board.Poster; import com.ibrasoft.lensbridge.model.board.PromotableSocialMedia; @@ -26,6 +22,7 @@ import com.ibrasoft.lensbridge.service.BoardService; import com.ibrasoft.lensbridge.service.PosterService; import com.ibrasoft.lensbridge.service.PromotableSocialMediaService; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; @@ -63,7 +60,7 @@ public class BoardAdminController { private final PromotableSocialMediaService socialMediaService; private final BoardService boardService; private final AdminAuditService auditService; - private final BoardStreamHandler boardStream; + private final ContentChangeNotifier contentChanges; // ==================== Board Config Endpoints ==================== @@ -425,30 +422,20 @@ public ResponseEntity deleteEvent( return ResponseEntity.ok(new MessageResponse("Calendar event deleted successfully")); } + /** + * Asks every connected board to sync its content now ({@code content_changed} on the agent + * WebSocket). A manual escape hatch: every content edit already does this by itself. + */ @PostMapping("/refresh") @PreAuthorize("hasAuthority('" + Permission.Authority.BOARD_REFRESH + "')") + @Operation(operationId = "refreshBoards", summary = "Ask every connected board to sync its content now") public ResponseEntity refreshSignboard(HttpServletRequest request) { - boardStream.refreshAll(); + contentChanges.contentChanged("manual refresh"); auditService.logAuditEvent(getCurrentUserEmail(), AuditAction.REFRESH_BOARDS, "Musallah Board", null, request.getRemoteAddr()); - return ResponseEntity.ok(new MessageResponse("Refresh sent to all MusallahBoard instances")); - } - - @PatchMapping("/devices/{deviceId}") - @PreAuthorize("hasAuthority('" + Permission.Authority.BOARD_CONFIG_WRITE + "')") - public ResponseEntity updateDevice( - @PathVariable UUID deviceId, - @Valid @RequestBody UpdateDeviceRequest updateRequest, - HttpServletRequest request) { - - log.info("Admin updating device: {}", deviceId); - Device updated = boardService.updateDevice(deviceId, updateRequest); - boardStream.configChanged(deviceId); - auditService.logAuditEvent(getCurrentUserEmail(), AuditAction.UPDATE_BOARD_CONFIG, "Device", deviceId, request.getRemoteAddr()); - - return ResponseEntity.ok(DeviceSummary.of(updated)); + return ResponseEntity.ok(new MessageResponse("Sync requested from every connected board")); } private String getCurrentUserEmail() { diff --git a/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java b/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java index 40aabe0..46b76a8 100644 --- a/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java +++ b/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java @@ -1,8 +1,10 @@ package com.ibrasoft.lensbridge.controller; import com.fasterxml.jackson.databind.ObjectMapper; +import com.ibrasoft.lensbridge.dto.board.request.CreateDeviceRequest; import com.ibrasoft.lensbridge.dto.board.request.IssueCommandRequest; import com.ibrasoft.lensbridge.dto.board.request.IssueEnrollmentTokenRequest; +import com.ibrasoft.lensbridge.dto.board.request.UpdateDeviceRequest; import com.ibrasoft.lensbridge.dto.board.response.CommandIssuedResponse; import com.ibrasoft.lensbridge.dto.board.response.CommandView; import com.ibrasoft.lensbridge.dto.board.response.DeviceSummary; @@ -15,13 +17,16 @@ import com.ibrasoft.lensbridge.repository.sql.DeviceCommandRepository; import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; import com.ibrasoft.lensbridge.service.AdminAuditService; +import com.ibrasoft.lensbridge.service.BoardService; import com.ibrasoft.lensbridge.service.agent.AgentSessionRegistry; import com.ibrasoft.lensbridge.service.agent.CommandDispatcher; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; import com.ibrasoft.lensbridge.service.agent.EnrollmentTokenService; import com.ibrasoft.lensbridge.exception.ApiResponseException; import com.ibrasoft.lensbridge.service.agent.EnrollmentTokenService.Issued; import com.ibrasoft.lensbridge.service.board.offline.OfflineBundle; import com.ibrasoft.lensbridge.service.board.offline.OfflineBundleService; +import com.ibrasoft.lensbridge.service.board.offline.SetupFileService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.headers.Header; @@ -69,8 +74,11 @@ public class DeviceAdminController { private final AgentSessionRegistry sessionRegistry; private final AdminAuditService auditService; private final OfflineBundleService offlineBundleService; + private final BoardService boardService; + private final ContentChangeNotifier contentChanges; + private final SetupFileService setupFileService; - @Operation(operationId = "listDevices", summary = "List every enrolled board device") + @Operation(operationId = "listDevices", summary = "List every board, connected or not") @GetMapping @PreAuthorize("hasAuthority('" + Permission.Authority.BOARD_DEVICE_READ + "')") public ResponseEntity> list() { @@ -94,8 +102,96 @@ public ResponseEntity get(@PathVariable UUID deviceId) { new MessageResponse("Device not found"))); } + @Operation(operationId = "createDevice", + summary = "Add a board", + description = "Creates the board before it is ever switched on, with no device key. Its config, " + + "content packages and setup file work at once; it gets a key only if it later claims " + + "online. Requires board:device:enroll.") + @ApiResponses({ + @ApiResponse(responseCode = "201", description = "Board created"), + @ApiResponse(responseCode = "400", description = "Missing name or audience, or an unusable location", + content = @Content(schema = @Schema(implementation = MessageResponse.class))) + }) + @PostMapping + @PreAuthorize("hasAuthority('" + Permission.Authority.BOARD_DEVICE_ENROLL + "')") + public ResponseEntity createDevice(@Valid @RequestBody CreateDeviceRequest request, + HttpServletRequest httpRequest) { + Device created = boardService.createDevice(request); + // There is no CREATE_DEVICE action (the column has a check constraint); this is the + // closest, and the detail says what happened. + auditService.logAuditEvent(getCurrentUserEmail(), AuditAction.UPDATE_BOARD_CONFIG, + "Device", created.getId(), httpRequest.getRemoteAddr(), "created board"); + return ResponseEntity.status(HttpStatus.CREATED).body(DeviceSummary.of(created)); + } + + /** + * Same reasons as {@link #offlineBundle}: built first, written straight to the response. + * A GET that changes state (the sequence, and the claim secret when online) because it is + * a download link; downloading again simply issues a newer file. + */ + @Operation(operationId = "downloadSetupFile", + summary = "Download a board's setup file", + description = "A signed .mbu provision package (provision.json: deviceId, displayName, sequence, " + + "issuedAt and, with online=true, backendUrl and a claimSecret). Plugged into a fresh board " + + "on a USB stick, it makes the board this one. Every download has a newer sequence; an " + + "online one also replaces the claim secret, so earlier online files can no longer claim " + + "the board. Requires board:device:enroll.") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "The setup file", + headers = @Header(name = HttpHeaders.CONTENT_DISPOSITION, + description = "attachment; filename=\"musallahboard-setup-.mbu\"", + schema = @Schema(type = "string")), + content = @Content(mediaType = OfflineBundleService.MBU_CONTENT_TYPE, + schema = @Schema(type = "string", format = "binary"))), + @ApiResponse(responseCode = "404", description = "No device with that id", + content = @Content(schema = @Schema(implementation = MessageResponse.class))), + @ApiResponse(responseCode = "409", description = "Device is revoked", + content = @Content(schema = @Schema(implementation = MessageResponse.class))), + @ApiResponse(responseCode = "503", description = "No content signing key, or (online) no backend URL, " + + "is configured on the server", + content = @Content(schema = @Schema(implementation = MessageResponse.class))) + }) + @GetMapping("/{deviceId}/setup-file") + @PreAuthorize("hasAuthority('" + Permission.Authority.BOARD_DEVICE_ENROLL + "')") + public void setupFile( + @PathVariable UUID deviceId, + @Parameter(description = "Include the backend URL and a new claim secret, for a board that will " + + "be online. Default: an offline-only board.") + @RequestParam(defaultValue = "false") boolean online, + HttpServletRequest httpRequest, + HttpServletResponse response) throws IOException { + OfflineBundle file = setupFileService.build(deviceId, online); + auditService.logAuditEvent(getCurrentUserEmail(), AuditAction.ISSUE_ENROLLMENT_TOKEN, + "Device", deviceId, httpRequest.getRemoteAddr(), + online ? "setup file (online, claim secret rotated)" : "setup file (offline)"); + writePackage(file, response); + } + + @Operation(operationId = "updateDevice", summary = "Rename a board or change its audience") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "Device updated"), + @ApiResponse(responseCode = "400", description = "Blank or over-long displayName", + content = @Content(schema = @Schema(implementation = MessageResponse.class))), + @ApiResponse(responseCode = "404", description = "No device with that id", + content = @Content(schema = @Schema(implementation = MessageResponse.class))) + }) + @PatchMapping("/{deviceId}") + @PreAuthorize("hasAuthority('" + Permission.Authority.BOARD_CONFIG_WRITE + "')") + public ResponseEntity updateDevice(@PathVariable UUID deviceId, + @Valid @RequestBody UpdateDeviceRequest request, + HttpServletRequest httpRequest) { + Device updated = boardService.updateDevice(deviceId, request); + // The audience decides which posters, events and socials the board shows. + contentChanges.deviceChanged(deviceId, "device"); + auditService.logAuditEvent(getCurrentUserEmail(), AuditAction.UPDATE_BOARD_CONFIG, + "Device", deviceId, httpRequest.getRemoteAddr()); + return ResponseEntity.ok(DeviceSummary.of(updated)); + } + @Operation(operationId = "issueEnrollmentToken", - summary = "Mint a one-time token a new device can exchange for an identity") + summary = "Mint a one-time token that enrolls a new device over SSH (legacy)", + description = "The token creates a new device when used. To enroll a board already added in the " + + "console, use POST /api/admin/board/devices/{deviceId}/enrollment-tokens.") @ApiResponse(responseCode = "201", description = "Token issued; the plaintext is returned exactly once") @PostMapping("/enrollment-tokens") @PreAuthorize("hasAuthority('" + Permission.Authority.BOARD_DEVICE_ENROLL + "')") @@ -124,6 +220,43 @@ public ResponseEntity issueEnrollmentToken( ); } + @Operation(operationId = "issueDeviceEnrollmentToken", + summary = "Mint a one-time token that enrolls this board over SSH (maintainers)", + description = "For musallahboard-agent enroll --token on the board. The token binds the board's key to " + + "this device, replacing any key it had (for example after an SD card swap). Boards set up " + + "with an online setup file claim by themselves and need no token.") + @ApiResponses({ + @ApiResponse(responseCode = "201", description = "Token issued; the plaintext is returned exactly once"), + @ApiResponse(responseCode = "404", description = "No device with that id", + content = @Content(schema = @Schema(implementation = MessageResponse.class))), + @ApiResponse(responseCode = "409", description = "Device is revoked", + content = @Content(schema = @Schema(implementation = MessageResponse.class))) + }) + @PostMapping("/{deviceId}/enrollment-tokens") + @PreAuthorize("hasAuthority('" + Permission.Authority.BOARD_DEVICE_ENROLL + "')") + public ResponseEntity issueDeviceEnrollmentToken( + @PathVariable UUID deviceId, + @Parameter(description = "Lifetime of the token in minutes (1-1440, default 30)") + @RequestParam(required = false) Integer expiresInMinutes, + HttpServletRequest httpRequest) { + Device device = deviceRepository.findById(deviceId) + .orElseThrow(() -> new ApiResponseException(HttpStatus.NOT_FOUND, new MessageResponse("Device not found"))); + if (device.getRevokedAt() != null) { + throw new ApiResponseException(HttpStatus.CONFLICT, new MessageResponse("Device is revoked")); + } + String adminEmail = getCurrentUserEmail(); + Issued issued = enrollmentTokenService.issueFor(device, expiresInMinutes, adminEmail); + log.info("Admin {} issued enrollment token {} for device {}", adminEmail, issued.token().getId(), deviceId); + auditService.logAuditEvent(adminEmail, AuditAction.ISSUE_ENROLLMENT_TOKEN, + "Device", deviceId, httpRequest.getRemoteAddr(), "token " + issued.token().getId()); + + return ResponseEntity.status(HttpStatus.CREATED).body(IssueEnrollmentTokenResponse.builder() + .tokenId(issued.token().getId()) + .token(issued.plaintext()) + .expiresAt(issued.token().getExpiresAt()) + .build()); + } + @Operation(operationId = "revokeDevice", summary = "Revoke a device's enrollment", description = "Closes any live agent session. Idempotent: re-revoking an already revoked device is a no-op.") @@ -231,7 +364,7 @@ public ResponseEntity> recentCommands(@PathVariable UUID devic schema = @Schema(type = "string")), content = @Content(mediaType = OfflineBundleService.MBU_CONTENT_TYPE, schema = @Schema(type = "string", format = "binary"))), - @ApiResponse(responseCode = "400", description = "days outside 1-31", + @ApiResponse(responseCode = "400", description = "days outside 1-92", content = @Content(schema = @Schema(implementation = MessageResponse.class))), @ApiResponse(responseCode = "404", description = "No device with that id", content = @Content(schema = @Schema(implementation = MessageResponse.class))), @@ -252,7 +385,10 @@ public void offlineBundle( defaultValue = "" + OfflineBundleService.DEFAULT_DAYS)) @RequestParam(defaultValue = "" + OfflineBundleService.DEFAULT_DAYS) int days, HttpServletResponse response) throws IOException { - OfflineBundle bundle = offlineBundleService.build(deviceId, days); + writePackage(offlineBundleService.build(deviceId, days), response); + } + + private static void writePackage(OfflineBundle bundle, HttpServletResponse response) throws IOException { response.setStatus(HttpStatus.OK.value()); response.setContentType(OfflineBundleService.MBU_CONTENT_TYPE); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, diff --git a/src/main/java/com/ibrasoft/lensbridge/controller/UsbKitController.java b/src/main/java/com/ibrasoft/lensbridge/controller/UsbKitController.java new file mode 100644 index 0000000..043b40c --- /dev/null +++ b/src/main/java/com/ibrasoft/lensbridge/controller/UsbKitController.java @@ -0,0 +1,179 @@ +package com.ibrasoft.lensbridge.controller; + +import com.ibrasoft.lensbridge.dto.auth.response.MessageResponse; +import com.ibrasoft.lensbridge.exception.ApiResponseException; +import com.ibrasoft.lensbridge.model.audit.AuditAction; +import com.ibrasoft.lensbridge.model.auth.Permission; +import com.ibrasoft.lensbridge.model.board.Device; +import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; +import com.ibrasoft.lensbridge.service.AdminAuditService; +import com.ibrasoft.lensbridge.service.board.offline.OfflineBundleService; +import com.ibrasoft.lensbridge.service.board.offline.UsbKitService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.headers.Header; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.io.IOException; +import java.nio.file.Files; +import java.time.LocalDate; +import java.time.ZoneOffset; +import java.util.List; +import java.util.UUID; + +/** + * The USB kit downloads (contract C4): everything a volunteer copies onto a stick, for one board + * or for every board. Both endpoints live here, not in {@link DeviceAdminController}, so the kit + * is one file to read; the one-board URL sits under that controller's {@code /devices} prefix. + *

+ * Reading devices is enough for a content-only kit. Setup files need board:device:enroll, since + * an online one carries a claim secret. + */ +@RestController +@RequestMapping("/api/admin/board") +@RequiredArgsConstructor +public class UsbKitController { + + /** Lists what the kit goes without (the latest app or agent when GitHub could not be reached). */ + public static final String OMITTED_HEADER = "X-Usb-Kit-Omitted"; + + private static final String KIT_ACCESS = "hasAuthority('" + Permission.Authority.BOARD_DEVICE_READ + "')" + + " and (!#includeSetup or hasAuthority('" + Permission.Authority.BOARD_DEVICE_ENROLL + "'))"; + + private final UsbKitService usbKitService; + private final DeviceRepository deviceRepository; + private final AdminAuditService auditService; + + @Operation(operationId = "downloadUsbKit", summary = "Download a USB kit for one board", + description = "A zip holding one folder, MusallahBoard/, with content-.mbu, setup-.mbu " + + "(includeSetup=true; online=true adds the backend URL and a new claim secret), and the latest " + + "board app and arm64 agent packages from their GitHub release channels. When a channel cannot be " + + "reached the kit goes without that package and the " + OMITTED_HEADER + " header says why. " + + "Requires board:device:read, and board:device:enroll with includeSetup.") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "The kit", + headers = { + @Header(name = HttpHeaders.CONTENT_DISPOSITION, schema = @Schema(type = "string"), + description = "attachment; filename=\"musallahboard-usb-kit--.zip\""), + @Header(name = OMITTED_HEADER, schema = @Schema(type = "string"), + description = "Present when the kit is missing the app or agent package: what, and why")}, + content = @Content(mediaType = "application/zip", schema = @Schema(type = "string", format = "binary"))), + @ApiResponse(responseCode = "400", description = "days outside 1-92", + content = @Content(schema = @Schema(implementation = MessageResponse.class))), + @ApiResponse(responseCode = "404", description = "No device with that id", + content = @Content(schema = @Schema(implementation = MessageResponse.class))), + @ApiResponse(responseCode = "409", description = "Device is revoked", + content = @Content(schema = @Schema(implementation = MessageResponse.class))), + @ApiResponse(responseCode = "502", description = "A poster image could not be fetched", + content = @Content(schema = @Schema(implementation = MessageResponse.class))), + @ApiResponse(responseCode = "503", description = "No content signing key (or, online, no backend URL) is configured", + content = @Content(schema = @Schema(implementation = MessageResponse.class))) + }) + @GetMapping("/devices/{deviceId}/usb-kit") + @PreAuthorize(KIT_ACCESS) + public void deviceKit(@PathVariable UUID deviceId, + @Parameter(description = "Days of content, starting today in each board's timezone", + schema = @Schema(type = "integer", format = "int32", minimum = "1", + maximum = "" + OfflineBundleService.MAX_DAYS, + defaultValue = "" + OfflineBundleService.DEFAULT_DAYS)) + @RequestParam(defaultValue = "" + OfflineBundleService.DEFAULT_DAYS) int days, + @Parameter(description = "Include the board's setup file") + @RequestParam(defaultValue = "false") boolean includeSetup, + @Parameter(description = "Make the setup file an online one (backend URL and a new claim secret)") + @RequestParam(defaultValue = "false") boolean online, + HttpServletRequest request, HttpServletResponse response) throws IOException { + Device device = deviceRepository.findById(deviceId) + .orElseThrow(() -> new ApiResponseException(HttpStatus.NOT_FOUND, new MessageResponse("Device not found"))); + String filename = "musallahboard-usb-kit-" + deviceId.toString().substring(0, 8) + "-" + today() + ".zip"; + send(usbKitService.build(List.of(device), filename, days, includeSetup, online), includeSetup, online, + deviceId, request, response); + } + + @Operation(operationId = "downloadAllBoardsUsbKit", summary = "Download a USB kit for every board", + description = "As the one-board kit, with the files of every board that is not revoked. One stick then " + + "updates any of them: each board keeps only its own files.") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "The kit", + headers = { + @Header(name = HttpHeaders.CONTENT_DISPOSITION, schema = @Schema(type = "string"), + description = "attachment; filename=\"musallahboard-usb-kit-all-.zip\""), + @Header(name = OMITTED_HEADER, schema = @Schema(type = "string"), + description = "Present when the kit is missing the app or agent package: what, and why")}, + content = @Content(mediaType = "application/zip", schema = @Schema(type = "string", format = "binary"))), + @ApiResponse(responseCode = "400", description = "days outside 1-92", + content = @Content(schema = @Schema(implementation = MessageResponse.class))), + @ApiResponse(responseCode = "404", description = "There are no boards", + content = @Content(schema = @Schema(implementation = MessageResponse.class))), + @ApiResponse(responseCode = "502", description = "A poster image could not be fetched", + content = @Content(schema = @Schema(implementation = MessageResponse.class))), + @ApiResponse(responseCode = "503", description = "No content signing key (or, online, no backend URL) is configured", + content = @Content(schema = @Schema(implementation = MessageResponse.class))) + }) + @GetMapping("/usb-kit") + @PreAuthorize(KIT_ACCESS) + public void allBoardsKit(@Parameter(description = "Days of content, starting today in each board's timezone", + schema = @Schema(type = "integer", format = "int32", minimum = "1", + maximum = "" + OfflineBundleService.MAX_DAYS, + defaultValue = "" + OfflineBundleService.DEFAULT_DAYS)) + @RequestParam(defaultValue = "" + OfflineBundleService.DEFAULT_DAYS) int days, + @Parameter(description = "Include every board's setup file") + @RequestParam(defaultValue = "false") boolean includeSetup, + @Parameter(description = "Make the setup files online ones (backend URL and new claim secrets)") + @RequestParam(defaultValue = "false") boolean online, + HttpServletRequest request, HttpServletResponse response) throws IOException { + List boards = deviceRepository.findByRevokedAtIsNullOrderByDisplayNameAsc(); + String filename = "musallahboard-usb-kit-all-" + today() + ".zip"; + send(usbKitService.build(boards, filename, days, includeSetup, online), includeSetup, online, + null, request, response); + } + + /** Built completely first (see UsbKitService), then copied to the response on this thread. */ + private void send(UsbKitService.Kit kit, boolean includeSetup, boolean online, UUID deviceId, + HttpServletRequest request, HttpServletResponse response) throws IOException { + try (kit) { + if (includeSetup) { + auditService.logAuditEvent(currentUser(), AuditAction.ISSUE_ENROLLMENT_TOKEN, "Device", deviceId, + request.getRemoteAddr(), online ? "USB kit with setup files (online, claim secrets rotated)" + : "USB kit with setup files (offline)"); + } + response.setStatus(HttpStatus.OK.value()); + response.setContentType("application/zip"); + response.setHeader(HttpHeaders.CONTENT_DISPOSITION, + ContentDisposition.attachment().filename(kit.filename()).build().toString()); + if (!kit.omitted().isEmpty()) { + // Header values must be plain ASCII on one line. + response.setHeader(OMITTED_HEADER, String.join("; ", kit.omitted()) + .replaceAll("[^\\x20-\\x7E]", "?")); + } + response.setContentLengthLong(Files.size(kit.file())); + Files.copy(kit.file(), response.getOutputStream()); + response.flushBuffer(); + } + } + + private static LocalDate today() { + return LocalDate.now(ZoneOffset.UTC); + } + + private static String currentUser() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + return authentication != null ? authentication.getName() : "unknown"; + } +} diff --git a/src/main/java/com/ibrasoft/lensbridge/dto/board/request/AgentClaimRequest.java b/src/main/java/com/ibrasoft/lensbridge/dto/board/request/AgentClaimRequest.java new file mode 100644 index 0000000..5f94245 --- /dev/null +++ b/src/main/java/com/ibrasoft/lensbridge/dto/board/request/AgentClaimRequest.java @@ -0,0 +1,46 @@ +package com.ibrasoft.lensbridge.dto.board.request; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.UUID; + +/** + * Body of {@code POST /api/agent/claim} (contract C2): a board set up by an online setup file + * binds the device key it generated to its pre-created device. + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class AgentClaimRequest { + + /** The deviceId from the board's setup file. */ + @NotNull + private UUID deviceId; + + /** Base64 (standard) of the 32-byte Ed25519 public key the board generated. */ + @NotBlank + @Size(max = 64) + private String publicKey; + + /** + * Base64url of HMAC-SHA256, keyed with the claim secret's 32 bytes, over + * {@code deviceId + "\n" + publicKey}: the lowercase deviceId and the publicKey string + * exactly as sent. Padding optional. + */ + @NotBlank + @Size(max = 64) + private String proof; + + @Size(max = 255, message = "agentVersion must be at most 255 characters") + private String agentVersion; + + @Size(max = 255, message = "hostname must be at most 255 characters") + private String hostname; +} diff --git a/src/main/java/com/ibrasoft/lensbridge/dto/board/request/CreateDeviceRequest.java b/src/main/java/com/ibrasoft/lensbridge/dto/board/request/CreateDeviceRequest.java new file mode 100644 index 0000000..3ebd5fa --- /dev/null +++ b/src/main/java/com/ibrasoft/lensbridge/dto/board/request/CreateDeviceRequest.java @@ -0,0 +1,36 @@ +package com.ibrasoft.lensbridge.dto.board.request; + +import com.ibrasoft.lensbridge.model.board.Audience; +import com.ibrasoft.lensbridge.model.board.Location; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Body of {@code POST /api/admin/board/devices}: a board created in the console, before it has + * ever been switched on. It has no key until it claims online; an offline board never does. + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class CreateDeviceRequest { + + /** Shown on the board when its setup file is applied ("Set up as North Musallah"). */ + @NotBlank + @Size(max = 255, message = "displayName must be at most 255 characters") + private String displayName; + + @NotNull + private Audience audience; + + /** + * Where the board is, for its prayer times. Optional: fields left out keep the defaults + * (the same location a token-enrolled board starts with), and can be edited later. + */ + private Location location; +} diff --git a/src/main/java/com/ibrasoft/lensbridge/dto/board/response/DeviceSummary.java b/src/main/java/com/ibrasoft/lensbridge/dto/board/response/DeviceSummary.java index a0471cd..7a5bfe3 100644 --- a/src/main/java/com/ibrasoft/lensbridge/dto/board/response/DeviceSummary.java +++ b/src/main/java/com/ibrasoft/lensbridge/dto/board/response/DeviceSummary.java @@ -10,7 +10,8 @@ import java.util.UUID; /** - * Admin-facing summary of a Device. Excludes the public key bytes (operators don't need them). + * Admin-facing summary of a Device. Excludes the public key bytes (operators don't need them) + * and the claim secret (a credential). */ @Data @Builder @@ -19,6 +20,7 @@ public class DeviceSummary { private UUID id; private String displayName; private Audience audience; + /** When the board first connected (claim or enrollment); null for a board that never has. */ private Instant enrolledAt; private Instant lastHeartbeat; private Instant revokedAt; diff --git a/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandler.java b/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandler.java deleted file mode 100644 index 57cfe5a..0000000 --- a/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandler.java +++ /dev/null @@ -1,219 +0,0 @@ -package com.ibrasoft.lensbridge.handler; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.ibrasoft.lensbridge.model.board.Device; -import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; - -import org.springframework.lang.NonNull; -import org.springframework.stereotype.Component; -import org.springframework.web.socket.CloseStatus; -import org.springframework.web.socket.TextMessage; -import org.springframework.web.socket.WebSocketSession; -import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator; -import org.springframework.web.socket.handler.TextWebSocketHandler; - -import java.time.Instant; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Push channel for kiosk pages: tells a board its content or config changed so it can - * refetch without waiting out its ten-minute poll. - *

- * Every board on this channel is an enrolled device. A connection must name a known, - * unrevoked {@code ?deviceId=} or it is closed on the spot — there is no anonymous - * or pre-enrollment state here. A board that has not been enrolled has no business on the - * stream: it has no payload to refetch and nothing can be addressed to it. - *

- */ -@Component -@RequiredArgsConstructor -@Slf4j -public class BoardStreamHandler extends TextWebSocketHandler { - - // Should probably be enums but this is sufficient for now - static final CloseStatus CLOSE_NO_DEVICE = new CloseStatus(4001, "device_id_required"); - static final CloseStatus CLOSE_UNKNOWN_DEVICE = new CloseStatus(4002, "unknown_device"); - static final CloseStatus CLOSE_REVOKED = new CloseStatus(4003, "device_revoked"); - static final CloseStatus CLOSE_SUPERSEDED = CloseStatus.NORMAL.withReason("superseded"); - - /** - * A push that has been stuck this long means the board has stopped reading; the decorator - * then closes the session instead of letting writers pile up behind it. Pushes are tiny - * and a healthy board drains them instantly, so this is generous. - */ - static final int SEND_TIME_LIMIT_MS = 10_000; - - /** Bytes of unsent pushes tolerated per board before it is cut off (a push is ~100 bytes). */ - static final int SEND_BUFFER_LIMIT_BYTES = 64 * 1024; - - /** Session attribute holding the device a connection was accepted as. */ - private static final String DEVICE_ATTR = "board.deviceId"; - - private final ObjectMapper objectMapper; - private final DeviceRepository deviceRepository; - - /** - * Live boards keyed by device. One session per device: a reloading kiosk can briefly - * open its replacement before the old socket finishes closing, so the newcomer wins - * and the stale one is closed rather than left to accumulate. - *

- * Sessions are stored wrapped in a {@link ConcurrentWebSocketSessionDecorator}. Pushes - * come from whichever admin request thread changed the content, and the container allows - * only one writer per session at a time: a second concurrent send throws, and the - * failure was being swallowed, so a board silently missed its refresh. The decorator - * serialises the writes. - */ - private final Map sessions = new ConcurrentHashMap<>(); - - @Override - public void afterConnectionEstablished(@NonNull WebSocketSession session) { - UUID deviceId = parseDeviceId(session); - if (deviceId == null) { - close(session, CLOSE_NO_DEVICE); - return; - } - - Optional device = deviceRepository.findById(deviceId); - if (device.isEmpty()) { - log.warn("Board stream session={} named unknown device {}", session.getId(), deviceId); - close(session, CLOSE_UNKNOWN_DEVICE); - return; - } - if (device.get().getRevokedAt() != null) { - log.warn("Board stream session={} is a revoked device {}", session.getId(), deviceId); - close(session, CLOSE_REVOKED); - return; - } - - session.getAttributes().put(DEVICE_ATTR, deviceId); - ConcurrentWebSocketSessionDecorator safe = - new ConcurrentWebSocketSessionDecorator(session, SEND_TIME_LIMIT_MS, SEND_BUFFER_LIMIT_BYTES); - ConcurrentWebSocketSessionDecorator previous = sessions.put(deviceId, safe); - if (previous != null) { - log.info("Board stream device {} superseded session {} with {}", - deviceId, previous.getId(), session.getId()); - close(previous, CLOSE_SUPERSEDED); - } - log.info("Board stream connected: session={} device={}", session.getId(), deviceId); - } - - @Override - public void afterConnectionClosed(@NonNull WebSocketSession session, @NonNull CloseStatus status) { - UUID deviceId = (UUID) session.getAttributes().get(DEVICE_ATTR); - if (deviceId == null) return; // rejected before it was ever registered - - // Only remove the entry if it still wraps this very session: a superseded session - // closing later must not evict the replacement that has already taken its place. - sessions.computeIfPresent(deviceId, (id, current) -> current.getDelegate() == session ? null : current); - log.info("Board stream disconnected: session={} device={} status={}", - session.getId(), deviceId, status); - } - - /** Content every board shares — posters, events, weekly content. */ - public void contentChanged(String reason) { - push(reason, null); - } - - /** Config for one board. */ - public void configChanged(UUID deviceId) { - push("config", deviceId); - } - - /** Operator-triggered "refresh everything", kept as a manual escape hatch. */ - public void refreshAll() { - push("manual-refresh", null); - } - - /** - * Push a message to every connected board, or to a single one. - * - * @param reason why the board should refetch. Carried on the wire for logging and for - * a frontend that wants to react selectively. - * @param target device to notify, or null to reach every board. - */ - private void push(String reason, UUID target) { - String json = serialize(reason, target); - if (json == null) return; - - if (target != null) { - ConcurrentWebSocketSessionDecorator session = sessions.get(target); - if (session == null) { - log.debug("Board stream reason={} device={} not connected — it will pick the change up on its next poll", - reason, target); - return; - } - if (send(target, session, json)) { - log.debug("Board stream push reason={} device={}", reason, target); - } - return; - } - - int sent = 0; - for (Map.Entry entry : sessions.entrySet()) { - if (send(entry.getKey(), entry.getValue(), json)) sent++; - } - log.debug("Board stream broadcast reason={} boards={}", reason, sent); - } - - /** @return true when the frame was written; drops the session if it has gone away. */ - private boolean send(UUID deviceId, ConcurrentWebSocketSessionDecorator session, String json) { - if (!session.isOpen()) { - sessions.remove(deviceId, session); - return false; - } - try { - session.sendMessage(new TextMessage(json)); - return true; - } catch (Exception e) { - log.warn("Board stream send failed: session={} device={} err={}", - session.getId(), deviceId, e.getMessage()); - return false; - } - } - - private String serialize(String reason, UUID target) { - Map body = new LinkedHashMap<>(); - body.put("type", "refresh"); - body.put("reason", reason); - body.put("deviceId", target); - // Pre-formatted rather than a raw Instant: a mapper without JavaTimeModule throws on - // one, and the only symptom would be pushes silently going nowhere. - body.put("at", Instant.now().toString()); - try { - return objectMapper.writeValueAsString(body); - } catch (Exception e) { - log.error("Board stream message could not be serialized", e); - return null; - } - } - - private static UUID parseDeviceId(WebSocketSession session) { - String query = session.getUri() == null ? null : session.getUri().getQuery(); - if (query == null) return null; - for (String param : query.split("&")) { - if (!param.startsWith("deviceId=")) continue; - String raw = param.substring("deviceId=".length()); - try { - return UUID.fromString(raw); - } catch (IllegalArgumentException e) { - log.warn("Board stream session={} sent a malformed deviceId: {}", session.getId(), raw); - return null; - } - } - return null; - } - - private static void close(WebSocketSession session, CloseStatus status) { - try { - if (session.isOpen()) session.close(status); - } catch (Exception e) { - log.debug("Board stream close failed: session={} err={}", session.getId(), e.getMessage()); - } - } -} diff --git a/src/main/java/com/ibrasoft/lensbridge/model/board/Device.java b/src/main/java/com/ibrasoft/lensbridge/model/board/Device.java index d288978..d425026 100644 --- a/src/main/java/com/ibrasoft/lensbridge/model/board/Device.java +++ b/src/main/java/com/ibrasoft/lensbridge/model/board/Device.java @@ -40,6 +40,10 @@ public class Device { @Column(nullable = false) private String displayName; + /** + * When a board first bound its device key (online claim or token enrollment). Null for a + * board created in the console that has never connected: an offline board stays that way. + */ private Instant enrolledAt; private Instant lastHeartbeat; @@ -54,7 +58,10 @@ public class Device { @Column(nullable = false) private Audience audience; - /** Ed25519 public key (32 bytes). Set during enrollment; null before. */ + /** + * Ed25519 public key (32 bytes). Set when the board claims or enrolls; null before, and + * forever for an offline board. Device-authenticated endpoints refuse a device without one. + */ @ToString.Exclude @Column(name = "public_key", length = 32) private byte[] publicKey; @@ -72,9 +79,20 @@ public class Device { /** When set, all auth attempts are rejected and any live session is closed. */ private Instant revokedAt; + /** + * Secret of the online claim (32 bytes): a board proves it holds it with an HMAC to bind + * its key. A credential: never logged, never returned except inside an online setup file. + * Null until the first online setup file, which (like every later one) replaces it. + */ + @ToString.Exclude + @Column(name = "claim_secret", length = 32) + private byte[] claimSecret; + + /** Sequence of the last setup file issued for this device; null before the first. */ + private Long provisionSequence; + @PrePersist private void prePersist() { - if (enrolledAt == null) enrolledAt = Instant.now(); if (organizationId == null) organizationId = "utmmsa"; } diff --git a/src/main/java/com/ibrasoft/lensbridge/model/board/EnrollmentToken.java b/src/main/java/com/ibrasoft/lensbridge/model/board/EnrollmentToken.java index b6a42a8..32b3983 100644 --- a/src/main/java/com/ibrasoft/lensbridge/model/board/EnrollmentToken.java +++ b/src/main/java/com/ibrasoft/lensbridge/model/board/EnrollmentToken.java @@ -50,9 +50,15 @@ public class EnrollmentToken { /** Set the moment the token is consumed; subsequent attempts fail. */ private Instant consumedAt; - /** Device created from this token, if consumed. */ + /** Device created (or bound) by this token, if consumed. */ private UUID consumedByDeviceId; + /** + * The pre-created device this token enrolls: enrollment binds the key to that row instead + * of creating a new device. Null for a token that creates a new device. + */ + private UUID deviceId; + @PrePersist private void prePersist() { if (createdAt == null) createdAt = Instant.now(); diff --git a/src/main/java/com/ibrasoft/lensbridge/repository/sql/DeviceRepository.java b/src/main/java/com/ibrasoft/lensbridge/repository/sql/DeviceRepository.java index 7844de0..e561455 100644 --- a/src/main/java/com/ibrasoft/lensbridge/repository/sql/DeviceRepository.java +++ b/src/main/java/com/ibrasoft/lensbridge/repository/sql/DeviceRepository.java @@ -2,10 +2,55 @@ import com.ibrasoft.lensbridge.model.board.Device; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; +import java.util.List; import java.util.UUID; @Repository public interface DeviceRepository extends JpaRepository { + + /** Every board that is not revoked, by name: the "all boards" USB kit. */ + List findByRevokedAtIsNullOrderByDisplayNameAsc(); + + /** + * Binds a key to a device that has none. The row count is the answer: 1 for the one + * caller that bound it, 0 when the device already had a key (or does not exist), so two + * boards claiming at once cannot both win. The persistence context is cleared afterwards + * so a copy loaded before the update is not flushed back over it. + */ + @Modifying(flushAutomatically = true, clearAutomatically = true) + @Query("update Device d set d.publicKey = :key where d.id = :id and d.publicKey is null") + int bindPublicKeyIfUnset(@Param("id") UUID id, @Param("key") byte[] key); + + /** + * Gives a device that is not revoked its next setup-file sequence: one more than the last, + * or {@code now} (epoch milliseconds) when that is greater. 1 when it did, 0 for an + * unknown or revoked device. + *

+ * One UPDATE, not a read and a save, so it takes the row's write lock (the database's on + * SQLite) before it reads the old value: a second issuer waits for the first to commit + * and then counts from its sequence, never from the same one. Make it the transaction's + * first statement: a SQLite transaction that has already read cannot wait for the lock + * and fails at once instead. Read the sequence back afterwards ({@code findById}; the + * persistence context is cleared). + */ + @Modifying(flushAutomatically = true, clearAutomatically = true) + @Query("update Device d set d.provisionSequence = case" + + " when coalesce(d.provisionSequence, 0) + 1 > :now then coalesce(d.provisionSequence, 0) + 1" + + " else :now end" + + " where d.id = :id and d.revokedAt is null") + int advanceProvisionSequence(@Param("id") UUID id, @Param("now") long now); + + /** + * Replaces a device's claim secret. Call it after {@link #advanceProvisionSequence} in the + * same transaction, which already holds the row's lock, so the stored secret is always the + * one of the highest sequence issued. + */ + @Modifying(flushAutomatically = true, clearAutomatically = true) + @Query("update Device d set d.claimSecret = :secret where d.id = :id") + int replaceClaimSecret(@Param("id") UUID id, @Param("secret") byte[] secret); } diff --git a/src/main/java/com/ibrasoft/lensbridge/security/WebSecurityConfig.java b/src/main/java/com/ibrasoft/lensbridge/security/WebSecurityConfig.java index 160a83f..9269ddb 100644 --- a/src/main/java/com/ibrasoft/lensbridge/security/WebSecurityConfig.java +++ b/src/main/java/com/ibrasoft/lensbridge/security/WebSecurityConfig.java @@ -37,9 +37,6 @@ public class WebSecurityConfig { @Value("${frontend.baseurl}") private String frontendBaseUrl; - @Value("${musallahboard.baseurl}") - private String musallahBoardBaseUrl; - @Bean public AuthTokenFilter authenticationJwtTokenFilter() { return new AuthTokenFilter(); @@ -66,11 +63,11 @@ public PasswordEncoder passwordEncoder() { @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); - configuration.setAllowedOrigins(Arrays.asList(frontendBaseUrl, musallahBoardBaseUrl)); + configuration.setAllowedOrigins(Arrays.asList(frontendBaseUrl)); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")); configuration.setAllowedHeaders(Arrays.asList("*")); - // So the admin frontend can read the offline bundle's filename from a fetch() response. - configuration.setExposedHeaders(Arrays.asList("Content-Disposition")); + // So the admin frontend can read a download's filename, and what a USB kit lacks, from fetch(). + configuration.setExposedHeaders(Arrays.asList("Content-Disposition", "X-Usb-Kit-Omitted")); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); @@ -88,8 +85,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .requestMatchers("/api/gallery/**").permitAll() .requestMatchers("/api/auth/**").permitAll() .requestMatchers("/api/events/**").permitAll() - .requestMatchers("/api/refresh-musallahboard").permitAll() .requestMatchers("/api/agent/enroll").permitAll() + .requestMatchers("/api/agent/claim").permitAll() .requestMatchers("/api/agent/ws").permitAll() // Public keys, and device-signed requests authenticated in the controller. .requestMatchers("/api/agent/signing-keys").permitAll() diff --git a/src/main/java/com/ibrasoft/lensbridge/service/BoardService.java b/src/main/java/com/ibrasoft/lensbridge/service/BoardService.java index c7aba5f..e12f014 100644 --- a/src/main/java/com/ibrasoft/lensbridge/service/BoardService.java +++ b/src/main/java/com/ibrasoft/lensbridge/service/BoardService.java @@ -1,6 +1,7 @@ package com.ibrasoft.lensbridge.service; import com.ibrasoft.lensbridge.dto.board.request.CreateCalendarEventRequest; +import com.ibrasoft.lensbridge.dto.board.request.CreateDeviceRequest; import com.ibrasoft.lensbridge.dto.board.request.UpdateBoardConfigRequest; import com.ibrasoft.lensbridge.dto.board.request.UpdateCalendarEventRequest; import com.ibrasoft.lensbridge.dto.board.request.UpdateDeviceRequest; @@ -8,7 +9,7 @@ import com.ibrasoft.lensbridge.dto.board.request.WeeklyContentRequest; import com.ibrasoft.lensbridge.dto.upload.response.ErrorResponse; import com.ibrasoft.lensbridge.exception.ApiResponseException; -import com.ibrasoft.lensbridge.handler.BoardStreamHandler; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; import com.ibrasoft.lensbridge.model.board.*; import com.ibrasoft.lensbridge.model.board.embedded.DeviceConfig; import com.ibrasoft.lensbridge.repository.sql.BoardConfigRepository; @@ -21,8 +22,6 @@ import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.springframework.transaction.support.TransactionSynchronization; -import org.springframework.transaction.support.TransactionSynchronizationManager; import java.time.DateTimeException; import java.time.Instant; @@ -31,6 +30,7 @@ import java.time.ZoneId; import java.time.format.DateTimeParseException; import java.time.format.DateTimeFormatter; +import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; @@ -44,7 +44,7 @@ public class BoardService { private final DeviceRepository deviceRepository; private final BoardEventRepository boardEventRepository; private final WeeklyContentRepository weeklyContentRepository; - private final BoardStreamHandler boardStream; + private final ContentChangeNotifier contentChanges; // ==================== Board Config ==================== @@ -76,7 +76,7 @@ public DeviceConfig saveBoardConfig(UUID deviceId, DeviceConfig deviceConfig) { } DeviceConfig saved = boardConfigRepository.save(deviceConfig); log.info("Saved board config for device: {}", deviceId); - boardStream.configChanged(deviceId); + contentChanges.deviceChanged(deviceId, "config"); return saved; } @@ -90,7 +90,7 @@ public DeviceConfig updateBoardConfig(UUID deviceId, UpdateBoardConfigRequest re Patch.apply(request.getNextPrayerDurationSeconds(), existing::setNextPrayerDurationSeconds); DeviceConfig saved = boardConfigRepository.save(existing); log.info("Updated board config for device: {}", deviceId); - boardStream.configChanged(deviceId); + contentChanges.deviceChanged(deviceId, "config"); return saved; } @@ -170,7 +170,7 @@ public DeviceConfig updateTicker(UUID deviceId, UpdateTickerRequest request) { Patch.apply(request.getScrollingMessages(), existing::setScrollingMessages); DeviceConfig saved = boardConfigRepository.save(existing); log.info("Updated ticker for device: {}", deviceId); - boardStream.configChanged(deviceId); + contentChanges.deviceChanged(deviceId, "config"); return saved; } @@ -241,7 +241,7 @@ public WeeklyContent saveWeeklyContent(int year, int weekNumber, WeeklyContentRe WeeklyContent saved = weeklyContentRepository.save(content); log.info("Saved weekly content for week {} of {}", weekNumber, year); - contentChangedAfterCommit("weekly-content"); + contentChanges.contentChanged("weekly-content"); return saved; } @@ -255,25 +255,6 @@ private static LocalTime parsePrayerTime(String value) { } } - /** - * Tells the boards to refetch once the surrounding transaction has committed. Notifying - * inside it lets a board refetch before the commit and read the old content, then stay on - * it until the next change. With no transaction active the save has already committed, so - * it notifies immediately, as every other mutator here does. - */ - private void contentChangedAfterCommit(String what) { - if (TransactionSynchronizationManager.isSynchronizationActive()) { - TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { - @Override - public void afterCommit() { - boardStream.contentChanged(what); - } - }); - } else { - boardStream.contentChanged(what); - } - } - /** @return the id of the deleted row, so callers can record what was destroyed. */ public UUID deleteWeeklyContent(int year, int weekNumber) { WeeklyContent content = weeklyContentRepository.findByYearAndWeekNumber(year, weekNumber) @@ -283,7 +264,7 @@ public UUID deleteWeeklyContent(int year, int weekNumber) { UUID deletedId = content.getId(); weeklyContentRepository.delete(content); log.info("Deleted weekly content for week {} of {}", weekNumber, year); - boardStream.contentChanged("weekly-content"); + contentChanges.contentChanged("weekly-content"); return deletedId; } @@ -325,7 +306,7 @@ public BoardEvent createEvent(CreateCalendarEventRequest request) { .build(); BoardEvent saved = boardEventRepository.save(boardEvent); log.info("Created event: id={}, name={}", saved.getId(), saved.getName()); - boardStream.contentChanged("events"); + contentChanges.contentChanged("events"); return saved; } @@ -342,7 +323,7 @@ public BoardEvent updateEvent(UUID eventId, UpdateCalendarEventRequest request) validateEventTimes(existing.getStartTime(), existing.getEndTime()); BoardEvent saved = boardEventRepository.save(existing); log.info("Updated event: id={}", eventId); - boardStream.contentChanged("events"); + contentChanges.contentChanged("events"); return saved; } @@ -356,11 +337,51 @@ public void deleteEvent(UUID eventId) { BoardEvent boardEvent = getEventById(eventId); boardEventRepository.delete(boardEvent); log.info("Deleted event: id={}", eventId); - boardStream.contentChanged("events"); + contentChanges.contentChanged("events"); } // ================== Device Management Changes ==================== + /** + * Creates a board before it has ever connected (contract C3): the device row, with no + * public key, and its config. Everything per-device (config, content packages, setup + * files) works for it at once. + */ + @Transactional + public Device createDevice(CreateDeviceRequest request) { + Device device = deviceRepository.save(Device.builder() + .displayName(request.getDisplayName().trim()) + .audience(request.getAudience()) + .build()); + DeviceConfig config = defaultConfig(device); + mergeLocation(config, request.getLocation()); + boardConfigRepository.save(config); + device.setConfig(config); + log.info("Created board {} ({})", device.getId(), device.getDisplayName()); + return device; + } + + /** + * The config every new board starts with, whether created in the console or by a legacy + * enrollment token. Hard-coded to the one organization this backend serves today. + */ + public static DeviceConfig defaultConfig(Device device) { + return DeviceConfig.builder() + .device(device) + .location(Location.builder() + .city("Mississauga") + .country("Canada") + .latitude(43.589) + .longitude(-79.6441) + .timezone("America/Toronto") + .method(CalculationMethod.ISNA) + .build()) + .darkModeAfterIsha(true) + .enableScrollingMessage(true) + .scrollingMessages(new ArrayList<>(List.of("Welcome to UTM MSA - Follow us @utmmsa for updates!"))) + .build(); + } + public Device updateDevice(UUID deviceId, UpdateDeviceRequest request) { Device existing = deviceRepository.findById(deviceId) .orElseThrow(() -> new ApiResponseException( diff --git a/src/main/java/com/ibrasoft/lensbridge/service/PosterService.java b/src/main/java/com/ibrasoft/lensbridge/service/PosterService.java index e1682f2..50d304f 100644 --- a/src/main/java/com/ibrasoft/lensbridge/service/PosterService.java +++ b/src/main/java/com/ibrasoft/lensbridge/service/PosterService.java @@ -4,7 +4,7 @@ import com.ibrasoft.lensbridge.dto.board.request.UpdatePosterRequest; import com.ibrasoft.lensbridge.dto.upload.response.ErrorResponse; import com.ibrasoft.lensbridge.exception.ApiResponseException; -import com.ibrasoft.lensbridge.handler.BoardStreamHandler; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; import com.ibrasoft.lensbridge.model.board.Audience; import com.ibrasoft.lensbridge.model.board.Poster; import java.time.Instant; @@ -28,7 +28,7 @@ public class PosterService { private final PosterRepository posterRepository; private final R2StorageService r2StorageService; - private final BoardStreamHandler boardStream; + private final ContentChangeNotifier contentChanges; @Value("${cloudflare.r2.public-url}") private String publicUrl; @@ -98,7 +98,7 @@ public Poster createPoster(CreatePosterRequest request) { poster = posterRepository.save(poster); log.info("Created poster: id={}, title={}", poster.getId(), poster.getTitle()); - boardStream.contentChanged("posters"); + contentChanges.contentChanged("posters"); return poster; } @@ -130,7 +130,7 @@ public Poster updatePoster(UUID posterId, UpdatePosterRequest request) { poster = posterRepository.save(poster); log.info("Updated poster: id={}", posterId); - boardStream.contentChanged("posters"); + contentChanges.contentChanged("posters"); return poster; } @@ -169,7 +169,7 @@ public Poster updatePosterImage(UUID posterId, MultipartFile imageFile) { // Delete the old object last: if the upload or the save above fails the poster // still points at an image that exists. A failed delete only leaks an object. deleteStoredImage(oldImage); - boardStream.contentChanged("posters"); + contentChanges.contentChanged("posters"); return poster; } @@ -187,7 +187,7 @@ public void deletePoster(UUID posterId) { posterRepository.delete(poster); log.info("Deleted poster: id={}", posterId); - boardStream.contentChanged("posters"); + contentChanges.contentChanged("posters"); } // ==================== Helper Methods ==================== diff --git a/src/main/java/com/ibrasoft/lensbridge/service/PromotableSocialMediaService.java b/src/main/java/com/ibrasoft/lensbridge/service/PromotableSocialMediaService.java index 4a14f81..0867785 100644 --- a/src/main/java/com/ibrasoft/lensbridge/service/PromotableSocialMediaService.java +++ b/src/main/java/com/ibrasoft/lensbridge/service/PromotableSocialMediaService.java @@ -4,7 +4,7 @@ import com.ibrasoft.lensbridge.dto.board.request.UpdatePromotableSocialMediaRequest; import com.ibrasoft.lensbridge.dto.upload.response.ErrorResponse; import com.ibrasoft.lensbridge.exception.ApiResponseException; -import com.ibrasoft.lensbridge.handler.BoardStreamHandler; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; import com.ibrasoft.lensbridge.model.board.Audience; import com.ibrasoft.lensbridge.model.board.PromotableSocialMedia; import com.ibrasoft.lensbridge.model.board.SocialType; @@ -29,7 +29,7 @@ public class PromotableSocialMediaService { private final PromotableSocialMediaRepository repository; - private final BoardStreamHandler boardStream; + private final ContentChangeNotifier contentChanges; /** Every promotable social, ordered by name. */ public List getAll() { @@ -74,7 +74,7 @@ public PromotableSocialMedia create(CreatePromotableSocialMediaRequest request) social = repository.save(social); log.info("Created promotable social media: id={}, type={}, name={}", social.getId(), social.getType(), social.getName()); - boardStream.contentChanged("socials"); + contentChanges.contentChanged("socials"); return social; } @@ -117,7 +117,7 @@ public PromotableSocialMedia update(UUID id, UpdatePromotableSocialMediaRequest social = repository.save(social); log.info("Updated promotable social media: id={}", id); - boardStream.contentChanged("socials"); + contentChanges.contentChanged("socials"); return social; } @@ -127,7 +127,7 @@ public void delete(UUID id) { repository.delete(social); log.info("Deleted promotable social media: id={}", id); - boardStream.contentChanged("socials"); + contentChanges.contentChanged("socials"); } // ==================== Helper Methods ==================== diff --git a/src/main/java/com/ibrasoft/lensbridge/service/agent/AgentSessionRegistry.java b/src/main/java/com/ibrasoft/lensbridge/service/agent/AgentSessionRegistry.java index 0a3ceda..f1147e6 100644 --- a/src/main/java/com/ibrasoft/lensbridge/service/agent/AgentSessionRegistry.java +++ b/src/main/java/com/ibrasoft/lensbridge/service/agent/AgentSessionRegistry.java @@ -49,6 +49,11 @@ public void untrack(AgentSession session) { connections.remove(session); } + /** A snapshot of the authenticated sessions, one per connected device. */ + public List authenticated() { + return List.copyOf(byDevice.values()); + } + /** A snapshot of every open connection, for the liveness sweep. */ public List connections() { return List.copyOf(connections); diff --git a/src/main/java/com/ibrasoft/lensbridge/service/agent/ContentChangeNotifier.java b/src/main/java/com/ibrasoft/lensbridge/service/agent/ContentChangeNotifier.java new file mode 100644 index 0000000..3780c59 --- /dev/null +++ b/src/main/java/com/ibrasoft/lensbridge/service/agent/ContentChangeNotifier.java @@ -0,0 +1,56 @@ +package com.ibrasoft.lensbridge.service.agent; + +import com.ibrasoft.lensbridge.dto.board.agent.OutgoingAgentFrame; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +/** + * Tells connected boards that their content may have changed, with a {@code content_changed} + * frame on the agent WebSocket ({@code /api/agent/ws}). The agent answers by syncing its + * content package a few seconds later, so an edit in the console reaches an online board + * without waiting for its 30-minute sync. + *

+ * The frame carries no content and no reason: the board always fetches its whole package + * through {@code POST /api/agent/content-bundle}. The reason is only logged here. + *

+ * Best effort. A board that is offline, or misses the frame, still picks the change up on its + * next scheduled sync, and an offline board gets it on its next USB stick. Frames are sent + * after the surrounding transaction commits, so a board never fetches before the change is + * visible. + */ +@Component +@RequiredArgsConstructor +@Slf4j +public class ContentChangeNotifier { + + static final String FRAME_TYPE = "content_changed"; + + private final AgentSessionRegistry registry; + + /** Content every board may show (posters, events, socials, weekly content): every board. */ + public void contentChanged(String what) { + AfterCommit.run(() -> { + int sent = 0; + for (AgentSession session : registry.authenticated()) { + if (send(session)) sent++; + } + log.info("content_changed ({}) sent to {} connected board(s)", what, sent); + }); + } + + /** Content of one board (its config, name or audience). */ + public void deviceChanged(UUID deviceId, String what) { + AfterCommit.run(() -> registry.get(deviceId).ifPresentOrElse( + session -> { + if (send(session)) log.info("content_changed ({}) sent to board {}", what, deviceId); + }, + () -> log.debug("content_changed ({}) not sent: board {} is not connected", what, deviceId))); + } + + private static boolean send(AgentSession session) { + return session.send(OutgoingAgentFrame.builder().type(FRAME_TYPE)); + } +} diff --git a/src/main/java/com/ibrasoft/lensbridge/service/agent/DeviceClaimService.java b/src/main/java/com/ibrasoft/lensbridge/service/agent/DeviceClaimService.java new file mode 100644 index 0000000..ef483bd --- /dev/null +++ b/src/main/java/com/ibrasoft/lensbridge/service/agent/DeviceClaimService.java @@ -0,0 +1,115 @@ +package com.ibrasoft.lensbridge.service.agent; + +import com.ibrasoft.lensbridge.model.board.Device; +import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.Optional; +import java.util.UUID; + +/** + * The online claim (contract C2): a board set up with an online setup file proves it holds the + * file's claim secret and binds the device key it generated to its pre-created device. + *

+ *   proof = base64url( HMAC-SHA256( key = claim secret bytes, msg = deviceId + "\n" + publicKey ) )
+ * 
+ * {@code deviceId} is the lowercase UUID, {@code publicKey} the base64 string exactly as sent. + *
    + *
  • Unknown, revoked, never given an online setup file, or a wrong proof: refused, all the + * same way, so the answer says nothing about which devices exist.
  • + *
  • No key yet: this one is bound.
  • + *
  • This same key already: success again, so a board whose response was lost can retry.
  • + *
  • A different key: conflict. Only a new SD card does that, and it needs a new + * enrollment token (see {@link DeviceEnrollmentService}).
  • + *
+ * The secret is kept after the bind, for those retries, until a new online setup file + * replaces it. It and the proof are never logged. + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class DeviceClaimService { + + private static final int ED25519_PUBLIC_KEY_LEN = 32; + private static final String HMAC = "HmacSHA256"; + + private final DeviceRepository deviceRepository; + + public sealed interface Outcome { + record Ok(Device device) implements Outcome {} + record BadRequest(String reason) implements Outcome {} + /** Any reason the claim cannot be accepted, deliberately not told apart. */ + record Refused() implements Outcome {} + record KeyConflict() implements Outcome {} + } + + @Transactional + public Outcome claim(UUID deviceId, String publicKeyBase64, String proofBase64Url, + String agentVersion, String hostname, String remoteIp) { + byte[] publicKey; + try { + publicKey = Base64.getDecoder().decode(publicKeyBase64); + } catch (IllegalArgumentException e) { + return new Outcome.BadRequest("publicKey is not base64"); + } + if (publicKey.length != ED25519_PUBLIC_KEY_LEN) { + return new Outcome.BadRequest("publicKey must be 32 bytes, got " + publicKey.length); + } + byte[] proof; + try { + proof = Base64.getUrlDecoder().decode(proofBase64Url); + } catch (IllegalArgumentException e) { + return new Outcome.BadRequest("proof is not base64url"); + } + + Optional found = deviceRepository.findById(deviceId); + if (found.isEmpty() || found.get().getRevokedAt() != null || found.get().getClaimSecret() == null) { + log.warn("Claim refused for device {}: {}", deviceId, found.isEmpty() ? "unknown device" + : found.get().getRevokedAt() != null ? "revoked" : "no online setup file issued"); + return new Outcome.Refused(); + } + Device device = found.get(); + byte[] expected = proof(device.getClaimSecret(), deviceId, publicKeyBase64); + if (!MessageDigest.isEqual(expected, proof)) { + log.warn("Claim refused for device {}: wrong proof (an older setup file, or not this board's)", deviceId); + return new Outcome.Refused(); + } + + if (device.getPublicKey() == null && deviceRepository.bindPublicKeyIfUnset(deviceId, publicKey) == 1) { + log.info("Device {} claimed: key bound (hostname {}, agent {})", deviceId, hostname, agentVersion); + } + // Reloaded: the bind cleared the persistence context, and another claim may have won. + device = deviceRepository.findById(deviceId).orElseThrow(); + if (!Arrays.equals(device.getPublicKey(), publicKey)) { + log.warn("Claim refused for device {}: it is bound to a different key", deviceId); + return new Outcome.KeyConflict(); + } + + if (device.getEnrolledAt() == null) device.setEnrolledAt(Instant.now()); + device.setAgentVersion(agentVersion); + device.setLastSeenIp(remoteIp); + return new Outcome.Ok(deviceRepository.save(device)); + } + + /** The proof a board holding {@code claimSecret} sends for this device and key. */ + public static byte[] proof(byte[] claimSecret, UUID deviceId, String publicKeyBase64) { + try { + Mac mac = Mac.getInstance(HMAC); + mac.init(new SecretKeySpec(claimSecret, HMAC)); + return mac.doFinal((deviceId + "\n" + publicKeyBase64).getBytes(StandardCharsets.UTF_8)); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("HmacSHA256 is mandatory in every JRE", e); + } + } +} diff --git a/src/main/java/com/ibrasoft/lensbridge/service/agent/DeviceEnrollmentService.java b/src/main/java/com/ibrasoft/lensbridge/service/agent/DeviceEnrollmentService.java index 2697eb6..d611a07 100644 --- a/src/main/java/com/ibrasoft/lensbridge/service/agent/DeviceEnrollmentService.java +++ b/src/main/java/com/ibrasoft/lensbridge/service/agent/DeviceEnrollmentService.java @@ -1,28 +1,33 @@ package com.ibrasoft.lensbridge.service.agent; -import com.ibrasoft.lensbridge.model.board.CalculationMethod; import com.ibrasoft.lensbridge.model.board.Device; import com.ibrasoft.lensbridge.model.board.EnrollmentToken; -import com.ibrasoft.lensbridge.model.board.Location; import com.ibrasoft.lensbridge.model.board.embedded.DeviceConfig; import com.ibrasoft.lensbridge.repository.sql.BoardConfigRepository; import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; +import com.ibrasoft.lensbridge.service.BoardService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.socket.CloseStatus; import java.time.Instant; +import java.util.Arrays; import java.util.Base64; -import java.util.List; import java.util.Optional; +import java.util.UUID; /** - * Orchestrates the agent enrollment flow: + * Orchestrates the agent enrollment flow (the maintainer's {@code musallahboard-agent enroll + * --token}; boards set up by a setup file claim instead, see {@link DeviceClaimService}): *
    *
  1. Validate and decode the device-supplied Ed25519 public key.
  2. *
  3. Atomically consume the one-time enrollment token.
  4. - *
  5. Persist a Device row carrying the public key and metadata reported by the agent.
  6. + *
  7. A token issued for a board created in the console binds the key to that device, + * replacing any key it had (the admin asked for this board to be re-keyed, for example + * after an SD card swap) and closing the old key's live session. Any other token + * creates a new device carrying the key.
  8. *
*/ @Service @@ -38,6 +43,7 @@ public class DeviceEnrollmentService { private final EnrollmentTokenService enrollmentTokenService; private final DeviceRepository deviceRepository; private final BoardConfigRepository boardConfigRepository; + private final AgentSessionRegistry sessionRegistry; public sealed interface Outcome { record Ok(Device device) implements Outcome {} @@ -67,6 +73,9 @@ public Outcome enroll(String plaintextToken, return new Outcome.InvalidToken(); } EnrollmentToken token = consumed.get(); + if (token.getDeviceId() != null) { + return bindExisting(token, publicKey, hardwareModel, agentVersion, remoteIp); + } Device device = Device.builder() .displayName(displayNameFor(token, hostname)) @@ -83,20 +92,7 @@ public Outcome enroll(String plaintextToken, // The id only exists now that the device is persisted; same transaction as the consume. enrollmentTokenService.recordConsumer(token.getId(), saved.getId()); - DeviceConfig defaultConfig = DeviceConfig.builder() - .device(saved) - .location(Location.builder() - .city("Mississauga") - .country("Canada") - .latitude(43.589) - .longitude(-79.6441) - .timezone("America/Toronto") - .method(CalculationMethod.ISNA) - .build()) - .darkModeAfterIsha(true) - .enableScrollingMessage(true) - .scrollingMessages(List.of("Welcome to UTM MSA - Follow us @utmmsa for updates!")) - .build(); + DeviceConfig defaultConfig = BoardService.defaultConfig(saved); boardConfigRepository.save(defaultConfig); log.info("Enrolled device {} from token {} (issued by {})", @@ -104,6 +100,33 @@ public Outcome enroll(String plaintextToken, return new Outcome.Ok(saved); } + private Outcome bindExisting(EnrollmentToken token, byte[] publicKey, String hardwareModel, + String agentVersion, String remoteIp) { + Optional found = deviceRepository.findById(token.getDeviceId()); + if (found.isEmpty() || found.get().getRevokedAt() != null) { + log.warn("Enrollment token {} is for device {}, which is {}", token.getId(), token.getDeviceId(), + found.isEmpty() ? "gone" : "revoked"); + return new Outcome.InvalidToken(); + } + Device device = found.get(); + boolean rekeyed = device.getPublicKey() != null && !Arrays.equals(device.getPublicKey(), publicKey); + device.setPublicKey(publicKey); + device.setHardwareModel(hardwareModel); + device.setAgentVersion(agentVersion); + device.setLastSeenIp(remoteIp); + if (device.getEnrolledAt() == null) device.setEnrolledAt(Instant.now()); + Device saved = deviceRepository.save(device); + enrollmentTokenService.recordConsumer(token.getId(), saved.getId()); + if (rekeyed) { + // The old key must not keep a live session; it can no longer authenticate. + UUID id = saved.getId(); + AfterCommit.run(() -> sessionRegistry.closeIfPresent(id, CloseStatus.POLICY_VIOLATION.withReason("rekeyed"))); + } + log.info("Enrolled device {} from token {} (issued by {}){}", saved.getId(), token.getId(), + token.getCreatedBy(), rekeyed ? ", replacing its previous key" : ""); + return new Outcome.Ok(saved); + } + /** Token name plus the hostname the agent reported, clipped to the column. */ private static String displayNameFor(EnrollmentToken token, String hostname) { String name = hostname != null && !hostname.isBlank() diff --git a/src/main/java/com/ibrasoft/lensbridge/service/agent/EnrollmentTokenService.java b/src/main/java/com/ibrasoft/lensbridge/service/agent/EnrollmentTokenService.java index ea514b1..e65d50f 100644 --- a/src/main/java/com/ibrasoft/lensbridge/service/agent/EnrollmentTokenService.java +++ b/src/main/java/com/ibrasoft/lensbridge/service/agent/EnrollmentTokenService.java @@ -1,6 +1,7 @@ package com.ibrasoft.lensbridge.service.agent; import com.ibrasoft.lensbridge.model.board.Audience; +import com.ibrasoft.lensbridge.model.board.Device; import com.ibrasoft.lensbridge.model.board.EnrollmentToken; import com.ibrasoft.lensbridge.repository.sql.EnrollmentTokenRepository; import lombok.RequiredArgsConstructor; @@ -46,6 +47,16 @@ public record Issued(EnrollmentToken token, String plaintext) {} @Transactional public Issued issue(String displayName, Audience audience, Integer ttlMinutes, String createdBy) { + return issue(displayName, audience, null, ttlMinutes, createdBy); + } + + /** A token that enrolls (binds a key to) an existing device instead of creating one. */ + @Transactional + public Issued issueFor(Device device, Integer ttlMinutes, String createdBy) { + return issue(device.getDisplayName(), device.getAudience(), device.getId(), ttlMinutes, createdBy); + } + + private Issued issue(String displayName, Audience audience, UUID deviceId, Integer ttlMinutes, String createdBy) { int ttl = clampTtl(ttlMinutes); String plaintext = generatePlaintext(); @@ -53,6 +64,7 @@ public Issued issue(String displayName, Audience audience, Integer ttlMinutes, S .tokenHash(hash(plaintext)) .displayName(displayName) .audience(audience) + .deviceId(deviceId) .createdBy(createdBy) .createdAt(Instant.now()) .expiresAt(Instant.now().plus(Duration.ofMinutes(ttl))) diff --git a/src/main/java/com/ibrasoft/lensbridge/service/board/offline/MbuManifest.java b/src/main/java/com/ibrasoft/lensbridge/service/board/offline/MbuManifest.java index 56df5c1..c86d8ca 100644 --- a/src/main/java/com/ibrasoft/lensbridge/service/board/offline/MbuManifest.java +++ b/src/main/java/com/ibrasoft/lensbridge/service/board/offline/MbuManifest.java @@ -15,16 +15,22 @@ * and stored in the zip as-is; nothing may re-serialize the manifest after signing. * {@link JsonInclude.Include#ALWAYS} keeps {@code "version": null} in the output even if the * application mapper is ever configured to drop nulls, so the bytes do not depend on that. + *

+ * Two types share it, both signed by the content key (this backend holds no other): + * {@code content} (payloads and media, {@link OfflineBundleService}) and {@code provision} + * (a board's setup file, {@code provision.json} alone, {@link SetupFileService}). A + * provision manifest has no {@code content} block; it is left out rather than written as null. * * @param format always {@code "mbu"} * @param formatVersion always {@value OfflineBundleService#FORMAT_VERSION} - * @param type always {@code "content"}: this backend only holds a content key + * @param type {@code "content"} or {@code "provision"} * @param createdAt RFC 3339 UTC, second precision ({@code 2026-09-24T14:02:11Z}) * @param sequence build time in epoch milliseconds (not truncated like {@code createdAt}); * the board's anti-rollback counter - * @param deviceId the device the content is bound to - * @param version always null for content (only software packages carry a version) - * @param files every payload and media file, including media left out of this zip + * @param deviceId the device the package is bound to + * @param version always null (only software packages carry a version) + * @param files every file of the package, including media left out of this zip + * @param content the content block; null (and absent from the JSON) for a provision package */ @JsonInclude(JsonInclude.Include.ALWAYS) @JsonPropertyOrder({"format", "formatVersion", "type", "createdAt", "sequence", "deviceId", "version", "files", "content"}) @@ -37,7 +43,7 @@ public record MbuManifest( String deviceId, String version, List files, - Content content + @JsonInclude(JsonInclude.Include.NON_NULL) Content content ) { /** One file of the package. {@code sha256} is lowercase hex of the bytes, {@code bytes} their exact size. */ diff --git a/src/main/java/com/ibrasoft/lensbridge/service/board/offline/MbuPackager.java b/src/main/java/com/ibrasoft/lensbridge/service/board/offline/MbuPackager.java new file mode 100644 index 0000000..59c2d49 --- /dev/null +++ b/src/main/java/com/ibrasoft/lensbridge/service/board/offline/MbuPackager.java @@ -0,0 +1,83 @@ +package com.ibrasoft.lensbridge.service.board.offline; + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.ibrasoft.lensbridge.dto.upload.response.ErrorResponse; +import com.ibrasoft.lensbridge.exception.ApiResponseException; +import org.springframework.http.HttpStatus; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; + +/** + * The one place a {@code .mbu} is signed and laid out, for every package type this backend + * builds (content and provision). See MusallahBoard {@code agent/docs/architecture.md}, + * sections 4 and 4.2. + *

+ * The manifest is serialized exactly once. Those bytes are signed and those same bytes are + * stored as {@code mbu.json}; the signature covers + * {@value ContentSigningService#MBU_SIGNATURE_PREFIX} followed by them, and nothing else. + */ +final class MbuPackager { + + static final String MANIFEST_ENTRY = "mbu.json"; + static final String SIGNATURE_ENTRY = "mbu.sig"; + + private final ObjectMapper objectMapper; + private final ContentSigningService signingService; + + MbuPackager(ObjectMapper objectMapper, ContentSigningService signingService) { + this.objectMapper = objectMapper; + this.signingService = signingService; + } + + /** + * @param files the package's files in zip order, after {@code mbu.json} and {@code mbu.sig}; + * the manifest must already list each of them (and may list more, such as + * media the board already holds) + */ + OfflineBundle pack(String filename, MbuManifest manifest, List files) { + byte[] manifestBytes = toJson(manifest); + byte[] signature = signingService.signManifest(manifestBytes); + byte[] signatureFile = toJson(new SignatureFile(List.of( + new SignatureEntry(signingService.currentKeyId(), Base64.getEncoder().encodeToString(signature))))); + + List entries = new ArrayList<>(files.size() + 2); + entries.add(new OfflineBundle.Entry(MANIFEST_ENTRY, manifestBytes, false)); + entries.add(new OfflineBundle.Entry(SIGNATURE_ENTRY, signatureFile, false)); + entries.addAll(files); + return new OfflineBundle(filename, entries); + } + + byte[] toJson(Object value) { + try { + return objectMapper.writeValueAsBytes(value); + } catch (JsonProcessingException e) { + throw new ApiResponseException(HttpStatus.INTERNAL_SERVER_ERROR, + ErrorResponse.of("Could not serialize package: " + e.getOriginalMessage())); + } + } + + static MbuManifest.FileEntry fileEntry(String path, byte[] bytes) { + return new MbuManifest.FileEntry(path, sha256Hex(bytes), bytes.length); + } + + static String sha256Hex(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is mandatory in every JRE", e); + } + } + + /** {@code mbu.sig}: {@code {"signatures":[{"keyId","sig"}]}}. */ + private record SignatureFile(List signatures) {} + + @JsonPropertyOrder({"keyId", "sig"}) + private record SignatureEntry(String keyId, String sig) {} +} diff --git a/src/main/java/com/ibrasoft/lensbridge/service/board/offline/OfflineBundleService.java b/src/main/java/com/ibrasoft/lensbridge/service/board/offline/OfflineBundleService.java index e4de601..b5d4978 100644 --- a/src/main/java/com/ibrasoft/lensbridge/service/board/offline/OfflineBundleService.java +++ b/src/main/java/com/ibrasoft/lensbridge/service/board/offline/OfflineBundleService.java @@ -1,7 +1,5 @@ package com.ibrasoft.lensbridge.service.board.offline; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.ibrasoft.lensbridge.dto.board.response.MusallahBoardPayload; import com.ibrasoft.lensbridge.dto.upload.response.ErrorResponse; @@ -17,16 +15,12 @@ import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.time.Clock; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.time.temporal.ChronoUnit; import java.util.ArrayList; -import java.util.Base64; -import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; @@ -54,9 +48,7 @@ * plus a handful of posters (10 MB cap each), and building first is the only way a failed * image download can still become a 502 rather than a truncated download. *

- * Signing: the manifest is serialized exactly once. Those bytes are signed and those same - * bytes are stored as {@code mbu.json}; the signature covers - * {@value ContentSigningService#MBU_SIGNATURE_PREFIX} followed by them, and nothing else. + * Signing and the zip layout are {@link MbuPackager}'s, shared with the setup file. */ @Service @Slf4j @@ -69,13 +61,11 @@ public class OfflineBundleService { * {@link com.ibrasoft.lensbridge.dto.board.request.ContentBundleRequest#DEFAULT_DAYS}). */ public static final int DEFAULT_DAYS = 14; - public static final int MAX_DAYS = 31; + public static final int MAX_DAYS = 92; /** Media type of a {@code .mbu} package. */ public static final String MBU_CONTENT_TYPE = "application/vnd.musallahboard.mbu"; - private static final String MANIFEST_ENTRY = "mbu.json"; - private static final String SIGNATURE_ENTRY = "mbu.sig"; private static final String MEDIA_DIR = "media/"; private static final String PAYLOAD_DIR = "payloads/"; @@ -114,6 +104,7 @@ public class OfflineBundleService { */ private final ObjectMapper objectMapper; private final ContentSigningService signingService; + private final MbuPackager packager; private final Clock clock; /** Lets a sync in which the board already holds every poster skip downloading them. */ private final MediaMetadataCache mediaMetadataCache; @@ -139,6 +130,7 @@ public OfflineBundleService(BoardPayloadAssembler payloadAssembler, this.r2StorageService = r2StorageService; this.objectMapper = objectMapper; this.signingService = signingService; + this.packager = new MbuPackager(objectMapper, signingService); this.clock = clock; this.mediaMetadataCache = new MediaMetadataCache(clock); } @@ -210,10 +202,10 @@ public OfflineBundle build(UUID deviceId, int days, Set haveMedia) { // Payload bytes first: the manifest lists their hashes. Map payloadFiles = new LinkedHashMap<>(); - payloads.forEach((day, payload) -> payloadFiles.put(PAYLOAD_DIR + day + ".json", toJson(payload))); + payloads.forEach((day, payload) -> payloadFiles.put(PAYLOAD_DIR + day + ".json", packager.toJson(payload))); List files = new ArrayList<>(); - payloadFiles.forEach((path, bytes) -> files.add(new MbuManifest.FileEntry(path, sha256Hex(bytes), bytes.length))); + payloadFiles.forEach((path, bytes) -> files.add(MbuPackager.fileEntry(path, bytes))); List mediaEntries = new ArrayList<>(); for (MediaFile m : mediaByHash.values()) { files.add(new MbuManifest.FileEntry(m.path(), m.sha256(), m.bytes())); @@ -231,15 +223,7 @@ public OfflineBundle build(UUID deviceId, int days, Set haveMedia) { files, new MbuManifest.Content(zone.getId(), firstDay.toString(), lastDay.toString(), mediaEntries)); - // Serialize once; sign these bytes; store these same bytes. - byte[] manifestBytes = toJson(manifest); - byte[] signature = signingService.signManifest(manifestBytes); - byte[] signatureFile = toJson(new SignatureFile(List.of( - new SignatureEntry(signingService.currentKeyId(), Base64.getEncoder().encodeToString(signature))))); - List entries = new ArrayList<>(); - entries.add(new OfflineBundle.Entry(MANIFEST_ENTRY, manifestBytes, false)); - entries.add(new OfflineBundle.Entry(SIGNATURE_ENTRY, signatureFile, false)); payloadFiles.forEach((path, bytes) -> entries.add(new OfflineBundle.Entry(path, bytes, false))); int omitted = 0; for (MediaFile media : mediaByHash.values()) { @@ -254,15 +238,9 @@ public OfflineBundle build(UUID deviceId, int days, Set haveMedia) { manifest.sequence(), deviceId, firstDay, lastDay, mediaByHash.size(), omitted); String filename = "musallahboard-content-" + deviceId.toString().substring(0, 8) + "-" + firstDay + ".mbu"; - return new OfflineBundle(filename, entries); + return packager.pack(filename, manifest, entries); } - /** {@code mbu.sig}: {@code {"signatures":[{"keyId","sig"}]}}. */ - private record SignatureFile(List signatures) {} - - @JsonPropertyOrder({"keyId", "sig"}) - private record SignatureEntry(String keyId, String sig) {} - // ==================== Media ==================== private record PosterFrame(String frameId, PosterFrameConfig config) {} @@ -333,7 +311,7 @@ private MediaFile fetch(PosterFrame poster, String objectKey) { throw imageFailure(poster, "its image is empty"); } - String sha256 = sha256Hex(object.bytes()); + String sha256 = MbuPackager.sha256Hex(object.bytes()); String keyExtension = extensionOf(objectKey); String contentType = normalizeContentType(object.contentType()); // Trust a stored image type; otherwise (missing, or a generic type such as @@ -380,21 +358,4 @@ private static String extensionOf(String objectKey) { return ext.length() <= 5 && ext.chars().allMatch(c -> (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) ? ext : null; } - - private static String sha256Hex(byte[] bytes) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException("SHA-256 is mandatory in every JRE", e); - } - } - - private byte[] toJson(Object value) { - try { - return objectMapper.writeValueAsBytes(value); - } catch (JsonProcessingException e) { - throw new ApiResponseException(HttpStatus.INTERNAL_SERVER_ERROR, - ErrorResponse.of("Could not serialize content package: " + e.getOriginalMessage())); - } - } } diff --git a/src/main/java/com/ibrasoft/lensbridge/service/board/offline/ReleaseChannelCache.java b/src/main/java/com/ibrasoft/lensbridge/service/board/offline/ReleaseChannelCache.java new file mode 100644 index 0000000..ee60b31 --- /dev/null +++ b/src/main/java/com/ibrasoft/lensbridge/service/board/offline/ReleaseChannelCache.java @@ -0,0 +1,164 @@ +package com.ibrasoft.lensbridge.service.board.offline; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.EnumMap; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * The latest board app and arm64 agent packages, from the same GitHub release channels the + * agent follows (agent {@code internal/config}, architecture section 9.4), for the USB kit. + *

+ * A channel file is only a pointer ({@code {version, url, sha256, bytes}}). The backend checks + * the download against its sha256 and size and passes the package on byte for byte; it never + * signs software, and the board verifies the package against the release key compiled into its + * agent, as it does for any other transport. So a tampered channel or cache can at worst put a + * package on the stick that the board refuses. + *

+ * A channel is checked at most every {@link #RECHECK}; the last good package is kept in memory + * and served while GitHub cannot be reached. When there is none yet, {@link #latest} says why, + * and the kit goes without it rather than failing. + */ +@Component +@Slf4j +public class ReleaseChannelCache { + + /** Default channels: the agent's own defaults (internal/config/config.go), arm64 for the Pi. */ + public static final String DEFAULT_APP_CHANNEL = + "https://github.com/LensBridge/MusallahBoard/releases/latest/download/app-channel.json"; + public static final String DEFAULT_AGENT_CHANNEL = + "https://github.com/LensBridge/agent/releases/latest/download/agent-channel-arm64.json"; + + static final Duration RECHECK = Duration.ofMinutes(30); + /** mbu.MaxPackageBytes: the most a board accepts. */ + static final long MAX_PACKAGE_BYTES = 512L << 20; + private static final long MAX_CHANNEL_BYTES = 64 << 10; + private static final Pattern VERSION = Pattern.compile("^(0|[1-9][0-9]{0,8})\\.(0|[1-9][0-9]{0,8})\\.(0|[1-9][0-9]{0,8})$"); + private static final Pattern SHA256 = Pattern.compile("^[0-9a-f]{64}$"); + + public enum Kind { + APP("board app"), AGENT("agent"); + + final String label; + + Kind(String label) { + this.label = label; + } + } + + /** A package as the board will read it from the stick. */ + public record ReleasePackage(Kind kind, String version, String filename, byte[] bytes) {} + + /** Either a package, or why there is none (for the kit's notice). */ + public record Lookup(ReleasePackage pkg, String problem) {} + + private record Cached(ReleasePackage pkg, Instant checkedAt) {} + + private final Map channels = new EnumMap<>(Kind.class); + private final Map cache = new EnumMap<>(Kind.class); + private final HttpClient http; + private final ObjectMapper mapper = new ObjectMapper(); + private final Clock clock; + + @Autowired + public ReleaseChannelCache( + @Value("${musallahboard.release.app-channel-url:" + DEFAULT_APP_CHANNEL + "}") String appChannel, + @Value("${musallahboard.release.agent-channel-url:" + DEFAULT_AGENT_CHANNEL + "}") String agentChannel) { + this(appChannel, agentChannel, HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(10)) + .followRedirects(HttpClient.Redirect.NORMAL) + .build(), Clock.systemUTC()); + } + + ReleaseChannelCache(String appChannel, String agentChannel, HttpClient http, Clock clock) { + channels.put(Kind.APP, appChannel == null ? "" : appChannel.trim()); + channels.put(Kind.AGENT, agentChannel == null ? "" : agentChannel.trim()); + this.http = http; + this.clock = clock; + } + + /** The latest package of this kind, from the cache when it was checked recently. */ + public synchronized Lookup latest(Kind kind) { + String channel = channels.get(kind); + if (channel.isEmpty()) { + return new Lookup(null, "the " + kind.label + " release channel is turned off on this server"); + } + Cached cached = cache.get(kind); + Instant now = clock.instant(); + if (cached != null && cached.checkedAt().plus(RECHECK).isAfter(now)) { + return new Lookup(cached.pkg(), null); + } + try { + ReleasePackage pkg = fetch(kind, channel, cached == null ? null : cached.pkg()); + cache.put(kind, new Cached(pkg, now)); + return new Lookup(pkg, null); + } catch (IOException | InterruptedException | RuntimeException e) { + if (e instanceof InterruptedException) Thread.currentThread().interrupt(); + String problem = "could not fetch the latest " + kind.label + " from " + channel + ": " + e.getMessage(); + if (cached != null) { + log.warn("{}; using the cached {} {}", problem, kind.label, cached.pkg().version()); + cache.put(kind, new Cached(cached.pkg(), now)); // do not retry on every kit meanwhile + return new Lookup(cached.pkg(), null); + } + log.warn("{}; the USB kit goes without it", problem); + return new Lookup(null, problem); + } + } + + private ReleasePackage fetch(Kind kind, String channel, ReleasePackage current) + throws IOException, InterruptedException { + JsonNode pointer = mapper.readTree(get(channel, Duration.ofSeconds(15), MAX_CHANNEL_BYTES)); + String version = text(pointer, "version"); + String url = text(pointer, "url"); + String sha256 = text(pointer, "sha256"); + long bytes = pointer.path("bytes").asLong(-1); + if (!VERSION.matcher(version).matches()) throw new IOException("channel version " + version + " is not MAJOR.MINOR.PATCH"); + if (!SHA256.matcher(sha256).matches()) throw new IOException("channel sha256 is malformed"); + if (bytes <= 0 || bytes > MAX_PACKAGE_BYTES) throw new IOException("channel size " + bytes + " is out of range"); + if (!url.startsWith("https://") && !url.startsWith("http://")) throw new IOException("channel url is not http(s)"); + + if (current != null && current.version().equals(version)) return current; + + byte[] body = get(url, Duration.ofMinutes(2), bytes); + if (body.length != bytes) throw new IOException("download is " + body.length + " bytes, the channel says " + bytes); + if (!MbuPackager.sha256Hex(body).equals(sha256)) throw new IOException("download does not match the channel's sha256"); + + String filename = kind == Kind.APP + ? "musallahboard-app-" + version + ".mbu" + : "musallahboard-agent-" + version + "-arm64.mbu"; + log.info("Fetched {} {} ({} bytes) for USB kits", kind.label, version, body.length); + return new ReleasePackage(kind, version, filename, body); + } + + private byte[] get(String url, Duration timeout, long limit) throws IOException, InterruptedException { + HttpRequest request = HttpRequest.newBuilder(URI.create(url)).timeout(timeout).GET().build(); + HttpResponse response = http.send(request, HttpResponse.BodyHandlers.ofInputStream()); + try (InputStream in = response.body()) { + if (response.statusCode() != 200) throw new IOException("HTTP " + response.statusCode()); + byte[] body = in.readNBytes((int) Math.min(Integer.MAX_VALUE - 8, limit + 1)); + if (body.length > limit) throw new IOException("larger than " + limit + " bytes"); + return body; + } + } + + private static String text(JsonNode node, String field) throws IOException { + JsonNode v = node.get(field); + if (v == null || !v.isTextual()) throw new IOException("channel has no " + field); + return v.asText(); + } +} diff --git a/src/main/java/com/ibrasoft/lensbridge/service/board/offline/SetupFileService.java b/src/main/java/com/ibrasoft/lensbridge/service/board/offline/SetupFileService.java new file mode 100644 index 0000000..88d9fbf --- /dev/null +++ b/src/main/java/com/ibrasoft/lensbridge/service/board/offline/SetupFileService.java @@ -0,0 +1,164 @@ +package com.ibrasoft.lensbridge.service.board.offline; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.ibrasoft.lensbridge.dto.upload.response.ErrorResponse; +import com.ibrasoft.lensbridge.exception.ApiResponseException; +import com.ibrasoft.lensbridge.model.board.Device; +import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.net.URI; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.List; +import java.util.UUID; + +/** + * Builds a board's setup file: a signed {@code provision} package ({@code .mbu}, contract C1) + * holding one file, {@code provision.json}, that gives a fresh board its identity: + *

+ * {"format":1, "deviceId":"…", "displayName":"North Musallah", "sequence":…, "issuedAt":"…",
+ *  "backendUrl":"https://…", "claimSecret":"<base64url, no padding, 32 bytes>"}
+ * 
+ * {@code backendUrl} and {@code claimSecret} are present only in an online setup file. An + * offline board never talks to this server, so its file carries neither. + *

+ * It is signed with the content key by the same {@link MbuPackager} as content packages; the + * board verifies it against the same pinned content keys. Like content, it can only say who + * the board is and where its backend is: never keys, software or anything that runs. + *

+ * Every file gets a sequence greater than the last one issued for the device (a board only + * takes a newer one), and every online file a freshly generated claim secret, which replaces + * the stored one: a file downloaded earlier can no longer claim the board. + */ +@Service +@Slf4j +public class SetupFileService { + + /** {@code provision.json} format this backend writes. */ + public static final int PROVISION_FORMAT = 1; + public static final String PROVISION_ENTRY = "provision.json"; + static final int CLAIM_SECRET_BYTES = 32; + + private final DeviceRepository deviceRepository; + private final ContentSigningService signingService; + private final MbuPackager packager; + private final Clock clock; + private final SecureRandom random; + /** Where an online board reaches this server; null when it cannot be worked out. */ + private final String backendUrl; + + @Autowired + public SetupFileService(DeviceRepository deviceRepository, + ObjectMapper objectMapper, + ContentSigningService signingService, + @Value("${musallahboard.agent.backendUrl:}") String backendUrl, + @Value("${musallahboard.agent.websocketUrl:}") String websocketUrl) { + this(deviceRepository, objectMapper, signingService, resolveBackendUrl(backendUrl, websocketUrl), + Clock.systemUTC(), new SecureRandom()); + } + + SetupFileService(DeviceRepository deviceRepository, ObjectMapper objectMapper, + ContentSigningService signingService, String backendUrl, Clock clock, SecureRandom random) { + this.deviceRepository = deviceRepository; + this.signingService = signingService; + this.packager = new MbuPackager(objectMapper, signingService); + this.backendUrl = backendUrl; + this.clock = clock; + this.random = random; + } + + /** {@code provision.json}. Optional fields are left out, not written as null. */ + @JsonInclude(JsonInclude.Include.NON_NULL) + @JsonPropertyOrder({"format", "deviceId", "displayName", "sequence", "issuedAt", "backendUrl", "claimSecret"}) + record ProvisionFile(int format, String deviceId, String displayName, long sequence, String issuedAt, + String backendUrl, String claimSecret) {} + + /** + * Issues the file: allocates the sequence and, online, rotates the secret, then signs. + * Called inside a larger transaction (a USB kit), it joins it, and nothing it stores is + * kept unless that transaction commits. + * + * @param online include {@code backendUrl} and a newly rotated {@code claimSecret} + * @throws ApiResponseException 404 unknown device, 409 revoked, 503 no content signing key, + * or (online only) no backend URL configured + */ + @Transactional + public OfflineBundle build(UUID deviceId, boolean online) { + signingService.requireConfigured(); + if (online && backendUrl == null) { + throw new ApiResponseException(HttpStatus.SERVICE_UNAVAILABLE, ErrorResponse.of( + "No backend URL for online boards is configured on this server " + + "(set musallahboard.agent.backendUrl, or musallahboard.agent.websocketUrl)")); + } + + // The atomic update comes first (see advanceProvisionSequence): two downloads at once + // are serialized on the device's row, so each gets its own sequence and the secret + // left stored is that of the newest file. + Instant now = clock.instant(); + if (deviceRepository.advanceProvisionSequence(deviceId, now.toEpochMilli()) == 0) { + boolean exists = deviceRepository.existsById(deviceId); + throw exists + ? new ApiResponseException(HttpStatus.CONFLICT, ErrorResponse.of("Device is revoked")) + : new ApiResponseException(HttpStatus.NOT_FOUND, ErrorResponse.of("Device not found")); + } + String claimSecret = null; + if (online) { + byte[] secret = new byte[CLAIM_SECRET_BYTES]; + random.nextBytes(secret); + deviceRepository.replaceClaimSecret(deviceId, secret); + claimSecret = Base64.getUrlEncoder().withoutPadding().encodeToString(secret); + } + Device device = deviceRepository.findById(deviceId) + .orElseThrow(() -> new IllegalStateException("Device " + deviceId + " vanished while locked")); + long sequence = device.getProvisionSequence(); + + String issuedAt = now.truncatedTo(ChronoUnit.SECONDS).toString(); + byte[] provision = packager.toJson(new ProvisionFile(PROVISION_FORMAT, deviceId.toString(), + device.getDisplayName(), sequence, issuedAt, online ? backendUrl : null, claimSecret)); + MbuManifest manifest = new MbuManifest("mbu", OfflineBundleService.FORMAT_VERSION, "provision", + issuedAt, sequence, deviceId.toString(), null, + List.of(MbuPackager.fileEntry(PROVISION_ENTRY, provision)), null); + + // Never the secret itself. + log.info("Built setup file {} for device {} ({})", sequence, deviceId, + online ? "online, claim secret rotated" : "offline"); + return packager.pack("musallahboard-setup-" + deviceId.toString().substring(0, 8) + ".mbu", manifest, + List.of(new OfflineBundle.Entry(PROVISION_ENTRY, provision, false))); + } + + /** + * The configured backend URL, else the origin of the agent WebSocket URL + * ({@code wss://api.example.org/api/agent/ws} gives {@code https://api.example.org}). + * Null when neither gives an http(s) origin. + */ + static String resolveBackendUrl(String configured, String websocketUrl) { + if (configured != null && !configured.isBlank()) { + String url = configured.trim(); + return url.endsWith("/") ? url.substring(0, url.length() - 1) : url; + } + if (websocketUrl == null || websocketUrl.isBlank()) return null; + try { + URI ws = URI.create(websocketUrl.trim()); + String scheme = switch (ws.getScheme() == null ? "" : ws.getScheme()) { + case "wss" -> "https"; + case "ws" -> "http"; + default -> null; + }; + if (scheme == null || ws.getHost() == null) return null; + return scheme + "://" + ws.getRawAuthority(); + } catch (IllegalArgumentException e) { + return null; + } + } +} diff --git a/src/main/java/com/ibrasoft/lensbridge/service/board/offline/UsbKitService.java b/src/main/java/com/ibrasoft/lensbridge/service/board/offline/UsbKitService.java new file mode 100644 index 0000000..b4ab315 --- /dev/null +++ b/src/main/java/com/ibrasoft/lensbridge/service/board/offline/UsbKitService.java @@ -0,0 +1,170 @@ +package com.ibrasoft.lensbridge.service.board.offline; + +import com.ibrasoft.lensbridge.dto.upload.response.ErrorResponse; +import com.ibrasoft.lensbridge.exception.ApiResponseException; +import com.ibrasoft.lensbridge.model.board.Device; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.zip.CRC32; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** + * A USB kit (contract C4): one zip whose root holds a single {@code MusallahBoard/} folder, + * ready to unzip onto a stick: + *

+ * MusallahBoard/content-<id8>.mbu                  per board
+ * MusallahBoard/musallahboard-app-<v>.mbu           latest board app, when GitHub answers
+ * MusallahBoard/musallahboard-agent-<v>-arm64.mbu   latest agent, when GitHub answers
+ * MusallahBoard/setup-<id8>.mbu                    per board, only with includeSetup
+ * 
+ * Every board reads every file and keeps only what is its own and newer, so one stick serves + * any number of boards. The zip is written to a temporary file first: memory stays bounded by + * one board's package, and every failure (a poster image that cannot be fetched, say) is still + * a JSON error rather than a truncated download. + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class UsbKitService { + + static final String FOLDER = "MusallahBoard/"; + + private final OfflineBundleService offlineBundleService; + private final SetupFileService setupFileService; + private final ReleaseChannelCache releases; + private final ContentSigningService signingService; + private final PlatformTransactionManager transactionManager; + + /** + * A built kit on disk. The caller streams it and must {@link #close} it. + * + * @param omitted what the kit goes without, and why (empty when complete) + */ + public record Kit(Path file, String filename, List omitted) implements AutoCloseable { + @Override + public void close() { + try { + Files.deleteIfExists(file); + } catch (IOException e) { + log.warn("Could not delete USB kit temp file {}: {}", file, e.getMessage()); + } + } + } + + /** + * @param online setup files include the backend URL and a new claim secret (with includeSetup) + */ + public Kit build(List devices, String filename, int days, boolean includeSetup, boolean online) { + if (days < 1 || days > OfflineBundleService.MAX_DAYS) { + throw new ApiResponseException(HttpStatus.BAD_REQUEST, + ErrorResponse.of("days must be between 1 and " + OfflineBundleService.MAX_DAYS)); + } + if (devices.isEmpty()) { + throw new ApiResponseException(HttpStatus.NOT_FOUND, ErrorResponse.of("There are no boards to make a kit for")); + } + signingService.requireConfigured(); + + Path file; + try { + file = Files.createTempFile("musallahboard-usb-kit-", ".zip"); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + List omitted = new ArrayList<>(); + try (OutputStream out = Files.newOutputStream(file); ZipOutputStream zip = new ZipOutputStream(out)) { + ZipEntry folder = new ZipEntry(FOLDER); + zip.putNextEntry(folder); + zip.closeEntry(); + // Everything slow or fallible first, outside any transaction and with nothing + // stored: content (posters are fetched) and the releases (GitHub). + for (Device device : devices) { + put(zip, "content-" + shortId(device) + ".mbu", bytesOf(offlineBundleService.build(device.getId(), days))); + } + for (ReleaseChannelCache.Kind kind : ReleaseChannelCache.Kind.values()) { + ReleaseChannelCache.Lookup lookup = releases.latest(kind); + if (lookup.pkg() != null) { + put(zip, lookup.pkg().filename(), lookup.pkg().bytes()); + } else { + omitted.add(kind.label + ": " + lookup.problem()); + } + } + if (includeSetup) { + // Then every board's setup file in one transaction that commits only once the + // zip is complete: a failure anywhere (a board revoked meanwhile, a full disk) + // rolls back every sequence and claim secret, so the files boards already + // have keep working. Boards take setup files before content from one stick, + // so their place at the end of the zip does not matter. In id order, so two + // kits at once lock the same rows in the same order (no deadlock on Postgres). + List byId = devices.stream().sorted(Comparator.comparing(Device::getId)).toList(); + new TransactionTemplate(transactionManager).executeWithoutResult(status -> { + try { + for (Device device : byId) { + put(zip, "setup-" + shortId(device) + ".mbu", + bytesOf(setupFileService.build(device.getId(), online))); + } + zip.close(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }); + } + } catch (IOException e) { + deleteQuietly(file); + throw new UncheckedIOException(e); + } catch (RuntimeException e) { + deleteQuietly(file); + throw e; + } + log.info("Built USB kit {} for {} board(s): {} days, setup files {}{}", filename, devices.size(), days, + includeSetup ? (online ? "online" : "offline") : "no", + omitted.isEmpty() ? "" : ", without " + String.join("; ", omitted)); + return new Kit(file, filename, List.copyOf(omitted)); + } + + /** Packages are zips already; stored, not deflated again. */ + private static void put(ZipOutputStream zip, String name, byte[] bytes) throws IOException { + ZipEntry entry = new ZipEntry(FOLDER + name); + CRC32 crc = new CRC32(); + crc.update(bytes); + entry.setMethod(ZipEntry.STORED); + entry.setSize(bytes.length); + entry.setCompressedSize(bytes.length); + entry.setCrc(crc.getValue()); + zip.putNextEntry(entry); + zip.write(bytes); + zip.closeEntry(); + } + + private static String shortId(Device device) { + return device.getId().toString().substring(0, 8); + } + + private static byte[] bytesOf(OfflineBundle bundle) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + bundle.writeTo(out); + return out.toByteArray(); + } + + private static void deleteQuietly(Path file) { + try { + Files.deleteIfExists(file); + } catch (IOException ignored) { + // best effort + } + } +} diff --git a/src/main/resources/application.properties.example b/src/main/resources/application.properties.example index 967ac2c..1d610c3 100644 --- a/src/main/resources/application.properties.example +++ b/src/main/resources/application.properties.example @@ -17,7 +17,7 @@ spring.jpa.open-in-view=false # Schema is owned by Flyway; Hibernate only validates against it. Do not set ddl-auto=update # here -- it would let Hibernate patch a schema Flyway believes it controls, and the two would # disagree about what has been applied. Migrations are per-vendor because dev is SQLite and -# prod is Postgres; see docs/MIGRATIONS.md. +# prod is Postgres; see MigrationParityTest. spring.jpa.hibernate.ddl-auto=validate spring.flyway.enabled=true # Set explicitly per profile below -- classpath:db/migration/postgresql for prod, @@ -26,17 +26,19 @@ spring.flyway.enabled=true # JDBC URL, but inside this project's repackaged jar (Spring Boot 3.2+ nested-jar layout) # Flyway's classpath scan doesn't restrict to the resolved subdirectory -- it scans both # db/migration/sqlite and db/migration/postgresql and fails startup with "Found more than -# one migration with version 1". Confirmed against prod on 2026-08-10; see docs/MIGRATIONS.md. +# one migration with version 1". Confirmed against prod on 2026-08-10; see MigrationParityTest. # spring.flyway.locations=classpath:db/migration/postgresql # Allowed CORS origins frontend.baseurl=http://localhost:5173 -musallahboard.baseurl=http://localhost:3000 -# MusallahBoard device agents. websocketUrl is returned by /api/agent/enroll and +# MusallahBoard device agents. websocketUrl is returned by /api/agent/claim and /api/agent/enroll and # persisted verbatim on the device, so point it at the address agents can reach # from where they are deployed — not at whatever host happens to serve this app. musallahboard.agent.websocketUrl=ws://localhost:8080/api/agent/ws +# Where an online board reaches this server, written into online setup files (and the address it +# claims at, POST /api/agent/claim). Empty: the origin of websocketUrl above (wss://h/... -> https://h). +musallahboard.agent.backendUrl= # Optional extra input to the enrollment-token hash. Leave empty to disable. musallahboard.enrollment.tokenPepper= # Zone used for a board whose device config has no timezone, or an unparseable one. @@ -64,6 +66,11 @@ lensbridge.websocket.container-customizer.enabled=true # POST /api/agent/content-bundle and the admin offline-bundle download answer 503. Keep it out of # this file in production and set the MUSALLAHBOARD_CONTENT_SIGNING_KEY environment variable. musallahboard.content-signing.private-key=${MUSALLAHBOARD_CONTENT_SIGNING_KEY:} +# Release channels the USB kit takes the latest board app and arm64 agent from (the agent's own +# defaults). Fetched on demand, checked at most every 30 minutes and cached in memory; a kit made +# while GitHub is unreachable goes without them. Set one empty to leave that package out of kits. +musallahboard.release.app-channel-url=https://github.com/LensBridge/MusallahBoard/releases/latest/download/app-channel.json +musallahboard.release.agent-channel-url=https://github.com/LensBridge/agent/releases/latest/download/agent-channel-arm64.json # During a key rotation: comma-separated base64 raw public keys of retired content keys, still # published by GET /api/agent/signing-keys so boards keep trusting what they already hold. musallahboard.content-signing.previous-public-keys= diff --git a/src/main/resources/db/migration/postgresql/V5__board_setup_files.sql b/src/main/resources/db/migration/postgresql/V5__board_setup_files.sql new file mode 100644 index 0000000..f743566 --- /dev/null +++ b/src/main/resources/db/migration/postgresql/V5__board_setup_files.sql @@ -0,0 +1,20 @@ +-- +-- V5: boards created in the console before they ever connect (offline-first, v3). +-- +-- devices.claim_secret 32 random bytes, the secret of the board's online claim +-- (POST /api/agent/claim). The backend must verify an HMAC made +-- with it, so it is stored as is, not hashed. It is a one-use +-- bearer credential: it only lets a board bind its device key to +-- this not-yet-bound device. It leaves the server only inside an +-- online setup file, and a new online setup file replaces it. +-- Null for a board that has never had an online setup file. +-- devices.provision_sequence sequence of the last setup file issued for the device; the next +-- one must be greater, since a board only accepts a newer one. +-- enrollment_tokens.device_id the pre-created device a token enrolls (binds a key to), or null +-- for a legacy token that creates a new device. +-- +-- The SQLite twin of this file must stay at the same version -- see MigrationParityTest. + +alter table devices add column claim_secret bytea; +alter table devices add column provision_sequence bigint; +alter table enrollment_tokens add column device_id uuid; diff --git a/src/main/resources/db/migration/sqlite/V5__board_setup_files.sql b/src/main/resources/db/migration/sqlite/V5__board_setup_files.sql new file mode 100644 index 0000000..1dbbf1f --- /dev/null +++ b/src/main/resources/db/migration/sqlite/V5__board_setup_files.sql @@ -0,0 +1,20 @@ +-- +-- V5: boards created in the console before they ever connect (offline-first, v3). +-- +-- devices.claim_secret 32 random bytes, the secret of the board's online claim +-- (POST /api/agent/claim). The backend must verify an HMAC made +-- with it, so it is stored as is, not hashed. It is a one-use +-- bearer credential: it only lets a board bind its device key to +-- this not-yet-bound device. It leaves the server only inside an +-- online setup file, and a new online setup file replaces it. +-- Null for a board that has never had an online setup file. +-- devices.provision_sequence sequence of the last setup file issued for the device; the next +-- one must be greater, since a board only accepts a newer one. +-- enrollment_tokens.device_id the pre-created device a token enrolls (binds a key to), or null +-- for a legacy token that creates a new device. +-- +-- The Postgres twin of this file must stay at the same version -- see MigrationParityTest. + +alter table devices add column claim_secret blob; +alter table devices add column provision_sequence bigint; +alter table enrollment_tokens add column device_id blob; diff --git a/src/test/java/com/ibrasoft/lensbridge/config/WebSocketConfigTest.java b/src/test/java/com/ibrasoft/lensbridge/config/WebSocketConfigTest.java index 12195b6..0504b82 100644 --- a/src/test/java/com/ibrasoft/lensbridge/config/WebSocketConfigTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/config/WebSocketConfigTest.java @@ -1,7 +1,6 @@ package com.ibrasoft.lensbridge.config; import com.ibrasoft.lensbridge.handler.AgentWebSocketHandler; -import com.ibrasoft.lensbridge.handler.BoardStreamHandler; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; @@ -12,7 +11,7 @@ class WebSocketConfigTest { private final WebSocketConfig config = - new WebSocketConfig(mock(BoardStreamHandler.class), mock(AgentWebSocketHandler.class)); + new WebSocketConfig(mock(AgentWebSocketHandler.class)); /** * Regression: the bean that lifts Tomcat's 8 KB text buffer was gated on a property no diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/AgentClaimControllerTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/AgentClaimControllerTest.java new file mode 100644 index 0000000..e36a8cd --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/controller/AgentClaimControllerTest.java @@ -0,0 +1,126 @@ +package com.ibrasoft.lensbridge.controller; + +import com.ibrasoft.lensbridge.model.board.Audience; +import com.ibrasoft.lensbridge.model.board.Device; +import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; +import com.ibrasoft.lensbridge.service.OpenWeatherService; +import com.ibrasoft.lensbridge.service.UserService; +import com.ibrasoft.lensbridge.service.agent.DeviceClaimService; +import com.ibrasoft.lensbridge.service.agent.DeviceEnrollmentService; +import com.ibrasoft.lensbridge.service.agent.handshake.Ed25519Verifier; +import com.ibrasoft.lensbridge.service.agent.http.AuthenticatedDeviceArgumentResolver; +import com.ibrasoft.lensbridge.service.agent.http.DeviceAuthInterceptor; +import com.ibrasoft.lensbridge.service.agent.http.DeviceBodyCachingFilter; +import com.ibrasoft.lensbridge.service.agent.http.DeviceRequestAuthenticator; +import com.ibrasoft.lensbridge.service.board.offline.ContentSigningService; +import com.ibrasoft.lensbridge.dto.board.response.SigningKeyView; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** {@code POST /api/agent/claim} (contract C2): what each claim outcome looks like on the wire. */ +@WebMvcTest(controllers = AgentEnrollmentController.class) +@AutoConfigureMockMvc(addFilters = false) +@Import({DeviceRequestAuthenticator.class, Ed25519Verifier.class, DeviceAuthInterceptor.class, + AuthenticatedDeviceArgumentResolver.class, DeviceBodyCachingFilter.class}) +@TestPropertySource(properties = "musallahboard.agent.websocketUrl=wss://example.test/api/agent/ws") +class AgentClaimControllerTest { + + private static final String URL = "/api/agent/claim"; + + @Autowired + private MockMvc mockMvc; + + @MockitoBean + private DeviceEnrollmentService enrollmentService; + @MockitoBean + private DeviceClaimService claimService; + @MockitoBean + private ContentSigningService signingService; + // The device-auth interceptor and WebConfig's argument resolver need these in the slice. + @MockitoBean + private DeviceRepository deviceRepository; + @MockitoBean + private OpenWeatherService openWeatherService; + @MockitoBean + private UserService userService; + + private static final UUID DEVICE_ID = UUID.fromString("00000000-0000-0000-0000-000000000001"); + private static final String KEY = "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q="; + private static final String PROOF = "2_nUd8LSmcq1kdXUvLW5ZQkAr_yDjiTuIh2AzpJH2sA"; + + private static String body() { + return "{\"deviceId\":\"" + DEVICE_ID + "\",\"publicKey\":\"" + KEY + "\",\"proof\":\"" + PROOF + + "\",\"agentVersion\":\"0.5.0\",\"hostname\":\"board-1\"}"; + } + + private void claimReturns(DeviceClaimService.Outcome outcome) { + when(claimService.claim(any(), any(), any(), any(), any(), any())).thenReturn(outcome); + } + + @Test + void aClaimAnswersLikeEnrollment() throws Exception { + claimReturns(new DeviceClaimService.Outcome.Ok(Device.builder().id(DEVICE_ID) + .displayName("North Musallah").audience(Audience.BOTH).build())); + when(signingService.publicKeys()).thenReturn(List.of(new SigningKeyView("65b60673d6ed884b", "ebVW"))); + + mockMvc.perform(post(URL).contentType(MediaType.APPLICATION_JSON).content(body()) + .with(r -> { r.setRemoteAddr("203.0.113.9"); return r; })) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.deviceId").value(DEVICE_ID.toString())) + .andExpect(jsonPath("$.websocketUrl").value("wss://example.test/api/agent/ws")) + .andExpect(jsonPath("$.contentSigningKeys[0].keyId").value("65b60673d6ed884b")); + + verify(claimService).claim(DEVICE_ID, KEY, PROOF, "0.5.0", "board-1", "203.0.113.9"); + } + + @Test + void outcomesMapToStatuses() throws Exception { + claimReturns(new DeviceClaimService.Outcome.Refused()); + mockMvc.perform(post(URL).contentType(MediaType.APPLICATION_JSON).content(body())) + .andExpect(status().isUnauthorized()); + + claimReturns(new DeviceClaimService.Outcome.KeyConflict()); + mockMvc.perform(post(URL).contentType(MediaType.APPLICATION_JSON).content(body())) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.message").value(containsString("different device key"))); + + claimReturns(new DeviceClaimService.Outcome.BadRequest("publicKey must be 32 bytes, got 31")); + mockMvc.perform(post(URL).contentType(MediaType.APPLICATION_JSON).content(body())) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value(containsString("32 bytes"))); + } + + @Test + void aClaimWithoutDeviceKeyOrProofIsRejectedBeforeTheService() throws Exception { + for (String json : List.of( + "{\"publicKey\":\"" + KEY + "\",\"proof\":\"" + PROOF + "\"}", + "{\"deviceId\":\"" + DEVICE_ID + "\",\"proof\":\"" + PROOF + "\"}", + "{\"deviceId\":\"" + DEVICE_ID + "\",\"publicKey\":\"" + KEY + "\"}", + "{\"deviceId\":\"not-a-uuid\",\"publicKey\":\"" + KEY + "\",\"proof\":\"" + PROOF + "\"}")) { + mockMvc.perform(post(URL).contentType(MediaType.APPLICATION_JSON).content(json)) + .andExpect(status().isBadRequest()); + } + verifyNoInteractions(claimService); + } +} diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/AgentContentControllerTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/AgentContentControllerTest.java index abed165..013c429 100644 --- a/src/test/java/com/ibrasoft/lensbridge/controller/AgentContentControllerTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/controller/AgentContentControllerTest.java @@ -9,6 +9,7 @@ import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; import com.ibrasoft.lensbridge.service.OpenWeatherService; import com.ibrasoft.lensbridge.service.UserService; +import com.ibrasoft.lensbridge.service.agent.DeviceClaimService; import com.ibrasoft.lensbridge.service.agent.DeviceEnrollmentService; import com.ibrasoft.lensbridge.service.agent.Ed25519TestUtil; import com.ibrasoft.lensbridge.service.agent.handshake.Ed25519Verifier; @@ -97,6 +98,8 @@ class AgentContentControllerTest { @MockitoBean private DeviceEnrollmentService enrollmentService; @MockitoBean + private DeviceClaimService claimService; + @MockitoBean private OpenWeatherService openWeatherService; /** Needed by WebConfig's CurrentUserArgumentResolver; see BoardAdminControllerPermissionTest. */ @MockitoBean diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/AgentEnrollmentControllerTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/AgentEnrollmentControllerTest.java index b85c817..f33e56e 100644 --- a/src/test/java/com/ibrasoft/lensbridge/controller/AgentEnrollmentControllerTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/controller/AgentEnrollmentControllerTest.java @@ -5,6 +5,7 @@ import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; import com.ibrasoft.lensbridge.service.OpenWeatherService; import com.ibrasoft.lensbridge.service.UserService; +import com.ibrasoft.lensbridge.service.agent.DeviceClaimService; import com.ibrasoft.lensbridge.service.agent.DeviceEnrollmentService; import com.ibrasoft.lensbridge.service.agent.handshake.Ed25519Verifier; import com.ibrasoft.lensbridge.service.agent.http.AuthenticatedDeviceArgumentResolver; @@ -55,6 +56,8 @@ class AgentEnrollmentControllerTest { @MockitoBean private DeviceEnrollmentService enrollmentService; @MockitoBean + private DeviceClaimService claimService; + @MockitoBean private ContentSigningService signingService; // The device-auth interceptor and WebConfig's argument resolver need these in the slice. @MockitoBean diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/BoardAdminControllerContentValidationTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/BoardAdminControllerContentValidationTest.java index 89367c6..15f7f3b 100644 --- a/src/test/java/com/ibrasoft/lensbridge/controller/BoardAdminControllerContentValidationTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/controller/BoardAdminControllerContentValidationTest.java @@ -2,7 +2,7 @@ import com.ibrasoft.lensbridge.dto.upload.response.ErrorResponse; import com.ibrasoft.lensbridge.exception.ApiResponseException; -import com.ibrasoft.lensbridge.handler.BoardStreamHandler; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; import com.ibrasoft.lensbridge.model.auth.Role; import com.ibrasoft.lensbridge.model.board.BoardEvent; import com.ibrasoft.lensbridge.model.board.PromotableSocialMedia; @@ -58,7 +58,7 @@ class BoardAdminControllerContentValidationTest { @MockitoBean private AdminAuditService auditService; @MockitoBean - private BoardStreamHandler boardStreamHandler; + private ContentChangeNotifier contentChanges; @MockitoBean private UserService userService; diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/BoardAdminControllerPermissionTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/BoardAdminControllerPermissionTest.java index 3bdee72..048c008 100644 --- a/src/test/java/com/ibrasoft/lensbridge/controller/BoardAdminControllerPermissionTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/controller/BoardAdminControllerPermissionTest.java @@ -1,6 +1,6 @@ package com.ibrasoft.lensbridge.controller; -import com.ibrasoft.lensbridge.handler.BoardStreamHandler; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; import com.ibrasoft.lensbridge.model.auth.Role; import com.ibrasoft.lensbridge.service.AdminAuditService; import com.ibrasoft.lensbridge.service.BoardService; @@ -51,7 +51,7 @@ class BoardAdminControllerPermissionTest { @MockitoBean private AdminAuditService auditService; @MockitoBean - private BoardStreamHandler boardStreamHandler; + private ContentChangeNotifier contentChanges; /** * Not used by this controller. WebConfig registers CurrentUserArgumentResolver, which diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerIssueCommandTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerIssueCommandTest.java index 08d81ac..98bda78 100644 --- a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerIssueCommandTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerIssueCommandTest.java @@ -1,6 +1,6 @@ package com.ibrasoft.lensbridge.controller; -import com.ibrasoft.lensbridge.handler.BoardStreamHandler; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; import com.ibrasoft.lensbridge.model.auth.Permission; import com.ibrasoft.lensbridge.model.board.Audience; import com.ibrasoft.lensbridge.model.board.Device; @@ -10,6 +10,8 @@ import com.ibrasoft.lensbridge.security.CommandAuthorizer; import com.ibrasoft.lensbridge.service.AdminAuditService; import com.ibrasoft.lensbridge.service.UserService; +import com.ibrasoft.lensbridge.service.board.offline.SetupFileService; +import com.ibrasoft.lensbridge.service.BoardService; import com.ibrasoft.lensbridge.service.agent.AgentSessionRegistry; import com.ibrasoft.lensbridge.service.agent.CommandDispatcher; import com.ibrasoft.lensbridge.service.agent.EnrollmentTokenService; @@ -79,7 +81,11 @@ CommandAuthorizer commandAuthorizer() { @MockitoBean private AdminAuditService auditService; @MockitoBean - private BoardStreamHandler boardStream; + private ContentChangeNotifier contentChanges; + @MockitoBean + private BoardService boardService; + @MockitoBean + private SetupFileService setupFileService; @MockitoBean private UserService userService; diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerOfflineBundleTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerOfflineBundleTest.java index c6bdbbc..7d4bfa6 100644 --- a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerOfflineBundleTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerOfflineBundleTest.java @@ -8,6 +8,9 @@ import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; import com.ibrasoft.lensbridge.service.AdminAuditService; import com.ibrasoft.lensbridge.service.UserService; +import com.ibrasoft.lensbridge.service.board.offline.SetupFileService; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; +import com.ibrasoft.lensbridge.service.BoardService; import com.ibrasoft.lensbridge.service.agent.AgentSessionRegistry; import com.ibrasoft.lensbridge.service.agent.CommandDispatcher; import com.ibrasoft.lensbridge.service.agent.EnrollmentTokenService; @@ -73,6 +76,12 @@ class DeviceAdminControllerOfflineBundleTest { /** Needed by WebConfig's CurrentUserArgumentResolver; see BoardAdminControllerPermissionTest. */ @MockitoBean + private BoardService boardService; + @MockitoBean + private ContentChangeNotifier contentChangeNotifier; + @MockitoBean + private SetupFileService setupFileService; + @MockitoBean private UserService userService; private static OfflineBundle bundle() { diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerSetupTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerSetupTest.java new file mode 100644 index 0000000..d946dde --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerSetupTest.java @@ -0,0 +1,182 @@ +package com.ibrasoft.lensbridge.controller; + +import com.ibrasoft.lensbridge.dto.board.request.CreateDeviceRequest; +import com.ibrasoft.lensbridge.model.audit.AuditAction; +import com.ibrasoft.lensbridge.model.auth.Permission; +import com.ibrasoft.lensbridge.model.board.Audience; +import com.ibrasoft.lensbridge.model.board.Device; +import com.ibrasoft.lensbridge.model.board.EnrollmentToken; +import com.ibrasoft.lensbridge.repository.sql.DeviceCommandRepository; +import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; +import com.ibrasoft.lensbridge.service.AdminAuditService; +import com.ibrasoft.lensbridge.service.BoardService; +import com.ibrasoft.lensbridge.service.UserService; +import com.ibrasoft.lensbridge.service.agent.AgentSessionRegistry; +import com.ibrasoft.lensbridge.service.agent.CommandDispatcher; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; +import com.ibrasoft.lensbridge.service.agent.EnrollmentTokenService; +import com.ibrasoft.lensbridge.service.board.offline.OfflineBundle; +import com.ibrasoft.lensbridge.service.board.offline.OfflineBundleService; +import com.ibrasoft.lensbridge.service.board.offline.SetupFileService; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.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 java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** "Add board" and the setup file (contracts C3, C4): request shape and who may do it. */ +@WebMvcTest(controllers = DeviceAdminController.class) +@Import(MethodSecurityTestConfig.class) +class DeviceAdminControllerSetupTest { + + private static final UUID DEVICE_ID = UUID.fromString("3f2a1b4c-0000-4000-8000-000000000001"); + private static final String DEVICES = "/api/admin/board/devices"; + + @Autowired + private MockMvc mockMvc; + + @MockitoBean private OfflineBundleService offlineBundleService; + @MockitoBean private EnrollmentTokenService enrollmentTokenService; + @MockitoBean private DeviceRepository deviceRepository; + @MockitoBean private DeviceCommandRepository commandRepository; + @MockitoBean private CommandDispatcher commandDispatcher; + @MockitoBean private AgentSessionRegistry sessionRegistry; + @MockitoBean private AdminAuditService auditService; + @MockitoBean private BoardService boardService; + @MockitoBean private ContentChangeNotifier contentChanges; + @MockitoBean private SetupFileService setupFileService; + @MockitoBean private UserService userService; + + @Test + void createsABoardWithNoKey() throws Exception { + when(boardService.createDevice(any())).thenReturn(Device.builder() + .id(DEVICE_ID).displayName("North Musallah").audience(Audience.BROTHERS).build()); + + mockMvc.perform(post(DEVICES).with(TestAuthorities.asHolderOf(Permission.BOARD_DEVICE_ENROLL)) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"displayName\":\"North Musallah\",\"audience\":\"brothers\"," + + "\"location\":{\"city\":\"Toronto\",\"latitude\":43.65,\"longitude\":-79.38," + + "\"timezone\":\"America/Toronto\",\"method\":\"ISNA\"}}")) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.id").value(DEVICE_ID.toString())) + .andExpect(jsonPath("$.displayName").value("North Musallah")) + .andExpect(jsonPath("$.enrolledAt").doesNotExist()); + + ArgumentCaptor sent = ArgumentCaptor.forClass(CreateDeviceRequest.class); + verify(boardService).createDevice(sent.capture()); + assertThat(sent.getValue().getLocation().getCity()).isEqualTo("Toronto"); + verify(auditService).logAuditEvent(anyString(), eq(AuditAction.UPDATE_BOARD_CONFIG), eq("Device"), + eq(DEVICE_ID), any(), eq("created board")); + } + + @Test + void creatingNeedsANameAndAnAudience() throws Exception { + for (String body : List.of("{\"audience\":\"both\"}", "{\"displayName\":\" \",\"audience\":\"both\"}", + "{\"displayName\":\"A\"}")) { + mockMvc.perform(post(DEVICES).with(TestAuthorities.asHolderOf(Permission.BOARD_DEVICE_ENROLL)) + .contentType(MediaType.APPLICATION_JSON).content(body)) + .andExpect(status().isBadRequest()); + } + verifyNoInteractions(boardService); + } + + @Test + void creatingNeedsTheEnrollPermission() throws Exception { + mockMvc.perform(post(DEVICES).with(TestAuthorities.asHolderOf(Permission.BOARD_DEVICE_READ, + Permission.BOARD_CONFIG_WRITE)) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"displayName\":\"A\",\"audience\":\"both\"}")) + .andExpect(status().isForbidden()); + verifyNoInteractions(boardService); + } + + @Test + void theSetupFileIsOfflineByDefault() throws Exception { + when(setupFileService.build(DEVICE_ID, false)).thenReturn(new OfflineBundle("musallahboard-setup-3f2a1b4c.mbu", + List.of(new OfflineBundle.Entry("mbu.json", "{}".getBytes(StandardCharsets.UTF_8), false)))); + + mockMvc.perform(get(DEVICES + "/" + DEVICE_ID + "/setup-file") + .with(TestAuthorities.asHolderOf(Permission.BOARD_DEVICE_ENROLL))) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", "application/vnd.musallahboard.mbu")) + .andExpect(header().string("Content-Disposition", + "attachment; filename=\"musallahboard-setup-3f2a1b4c.mbu\"")); + verify(setupFileService).build(DEVICE_ID, false); + verify(auditService).logAuditEvent(anyString(), eq(AuditAction.ISSUE_ENROLLMENT_TOKEN), eq("Device"), + eq(DEVICE_ID), any(), eq("setup file (offline)")); + } + + @Test + void onlineAsksForTheOnlineFile() throws Exception { + when(setupFileService.build(DEVICE_ID, true)).thenReturn(new OfflineBundle("musallahboard-setup-3f2a1b4c.mbu", + List.of(new OfflineBundle.Entry("mbu.json", "{}".getBytes(StandardCharsets.UTF_8), false)))); + + mockMvc.perform(get(DEVICES + "/" + DEVICE_ID + "/setup-file").param("online", "true") + .with(TestAuthorities.asHolderOf(Permission.BOARD_DEVICE_ENROLL))) + .andExpect(status().isOk()); + verify(setupFileService).build(DEVICE_ID, true); + } + + /** It can carry a claim secret: reading devices is not enough. */ + @Test + void theSetupFileNeedsTheEnrollPermission() throws Exception { + mockMvc.perform(get(DEVICES + "/" + DEVICE_ID + "/setup-file") + .with(TestAuthorities.asHolderOf(Permission.BOARD_DEVICE_READ))) + .andExpect(status().isForbidden()); + verifyNoInteractions(setupFileService); + } + + @Test + void aTokenForThisBoardIsIssuedForItsRow() throws Exception { + Device device = Device.builder().id(DEVICE_ID).displayName("North Musallah").audience(Audience.BOTH).build(); + when(deviceRepository.findById(DEVICE_ID)).thenReturn(Optional.of(device)); + EnrollmentToken token = EnrollmentToken.builder().id(UUID.randomUUID()).deviceId(DEVICE_ID) + .expiresAt(Instant.parse("2026-11-19T12:30:00Z")).build(); + when(enrollmentTokenService.issueFor(eq(device), eq(60), anyString())) + .thenReturn(new EnrollmentTokenService.Issued(token, "plain-token")); + + mockMvc.perform(post(DEVICES + "/" + DEVICE_ID + "/enrollment-tokens").param("expiresInMinutes", "60") + .with(TestAuthorities.asHolderOf(Permission.BOARD_DEVICE_ENROLL))) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.token").value("plain-token")) + .andExpect(jsonPath("$.tokenId").value(token.getId().toString())); + } + + @Test + void noTokenForAnUnknownOrRevokedBoard() throws Exception { + when(deviceRepository.findById(DEVICE_ID)).thenReturn(Optional.empty()); + mockMvc.perform(post(DEVICES + "/" + DEVICE_ID + "/enrollment-tokens") + .with(TestAuthorities.asHolderOf(Permission.BOARD_DEVICE_ENROLL))) + .andExpect(status().isNotFound()); + + when(deviceRepository.findById(DEVICE_ID)).thenReturn(Optional.of(Device.builder().id(DEVICE_ID) + .displayName("A").audience(Audience.BOTH).revokedAt(Instant.now()).build())); + mockMvc.perform(post(DEVICES + "/" + DEVICE_ID + "/enrollment-tokens") + .with(TestAuthorities.asHolderOf(Permission.BOARD_DEVICE_ENROLL))) + .andExpect(status().isConflict()); + verifyNoInteractions(enrollmentTokenService); + } +} diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerTest.java index f0629b9..31dd70b 100644 --- a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerTest.java @@ -5,6 +5,8 @@ import com.ibrasoft.lensbridge.model.board.Audience; import com.ibrasoft.lensbridge.model.board.Device; import com.ibrasoft.lensbridge.service.AdminAuditService; +import com.ibrasoft.lensbridge.service.BoardService; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; import com.ibrasoft.lensbridge.repository.sql.DeviceCommandRepository; import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; import com.ibrasoft.lensbridge.service.agent.AgentSession; @@ -13,6 +15,7 @@ import com.ibrasoft.lensbridge.service.agent.CommandDispatcher; import com.ibrasoft.lensbridge.service.agent.EnrollmentTokenService; import com.ibrasoft.lensbridge.service.board.offline.OfflineBundleService; +import com.ibrasoft.lensbridge.service.board.offline.SetupFileService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -55,7 +58,10 @@ void revoke_closesRegisteredAgentSession() throws Exception { new ObjectMapper(), registry, auditService, - mock(OfflineBundleService.class)); + mock(OfflineBundleService.class), + mock(BoardService.class), + mock(ContentChangeNotifier.class), + mock(SetupFileService.class)); UUID deviceId = UUID.randomUUID(); Device device = Device.builder() @@ -102,7 +108,10 @@ void revoke_isANoOpAndDoesNotReAuditWhenAlreadyRevoked() throws Exception { new ObjectMapper(), new AgentSessionRegistry(mock(DeviceEventPublisher.class)), auditService, - mock(OfflineBundleService.class)); + mock(OfflineBundleService.class), + mock(BoardService.class), + mock(ContentChangeNotifier.class), + mock(SetupFileService.class)); UUID deviceId = UUID.randomUUID(); Instant revokedAt = Instant.now().minusSeconds(3600); diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/BoardAdminControllerUpdateDeviceTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerUpdateDeviceTest.java similarity index 79% rename from src/test/java/com/ibrasoft/lensbridge/controller/BoardAdminControllerUpdateDeviceTest.java rename to src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerUpdateDeviceTest.java index aa53564..6f57cc1 100644 --- a/src/test/java/com/ibrasoft/lensbridge/controller/BoardAdminControllerUpdateDeviceTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerUpdateDeviceTest.java @@ -1,15 +1,20 @@ package com.ibrasoft.lensbridge.controller; import com.ibrasoft.lensbridge.dto.board.request.UpdateDeviceRequest; -import com.ibrasoft.lensbridge.handler.BoardStreamHandler; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; import com.ibrasoft.lensbridge.model.auth.Role; import com.ibrasoft.lensbridge.model.board.Audience; import com.ibrasoft.lensbridge.model.board.Device; import com.ibrasoft.lensbridge.service.AdminAuditService; import com.ibrasoft.lensbridge.service.BoardService; -import com.ibrasoft.lensbridge.service.PosterService; -import com.ibrasoft.lensbridge.service.PromotableSocialMediaService; +import com.ibrasoft.lensbridge.repository.sql.DeviceCommandRepository; +import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; +import com.ibrasoft.lensbridge.service.agent.AgentSessionRegistry; +import com.ibrasoft.lensbridge.service.agent.CommandDispatcher; +import com.ibrasoft.lensbridge.service.agent.EnrollmentTokenService; +import com.ibrasoft.lensbridge.service.board.offline.OfflineBundleService; import com.ibrasoft.lensbridge.service.UserService; +import com.ibrasoft.lensbridge.service.board.offline.SetupFileService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; @@ -38,9 +43,9 @@ * about emptiness. The board then showed as unnamed in every admin listing. These tests * pin both halves — the constraints, and the {@code @Valid} that runs them. */ -@WebMvcTest(controllers = BoardAdminController.class) +@WebMvcTest(controllers = DeviceAdminController.class) @Import(MethodSecurityTestConfig.class) -class BoardAdminControllerUpdateDeviceTest { +class DeviceAdminControllerUpdateDeviceTest { private static final String URL = "/api/admin/board/devices/"; @@ -50,16 +55,26 @@ class BoardAdminControllerUpdateDeviceTest { @MockitoBean private BoardService boardService; @MockitoBean - private PosterService posterService; + private DeviceRepository deviceRepository; @MockitoBean - private PromotableSocialMediaService socialMediaService; + private DeviceCommandRepository commandRepository; + @MockitoBean + private CommandDispatcher commandDispatcher; + @MockitoBean + private AgentSessionRegistry sessionRegistry; + @MockitoBean + private OfflineBundleService offlineBundleService; + @MockitoBean + private EnrollmentTokenService enrollmentTokenService; @MockitoBean private AdminAuditService auditService; @MockitoBean - private BoardStreamHandler boardStreamHandler; + private ContentChangeNotifier contentChanges; /** WebConfig registers CurrentUserArgumentResolver, which needs this in the slice. */ @MockitoBean + private SetupFileService setupFileService; + @MockitoBean private UserService userService; private static final UUID DEVICE_ID = UUID.randomUUID(); @@ -121,5 +136,6 @@ void acceptsARealDisplayName() throws Exception { patchBody("{\"displayName\":\"Musallah A\"}", 200); verify(boardService).updateDevice(eq(DEVICE_ID), any()); + verify(contentChanges).deviceChanged(DEVICE_ID, "device"); } } diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/UsbKitControllerTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/UsbKitControllerTest.java new file mode 100644 index 0000000..18645fc --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/controller/UsbKitControllerTest.java @@ -0,0 +1,104 @@ +package com.ibrasoft.lensbridge.controller; + +import com.ibrasoft.lensbridge.model.auth.Permission; +import com.ibrasoft.lensbridge.model.board.Audience; +import com.ibrasoft.lensbridge.model.board.Device; +import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; +import com.ibrasoft.lensbridge.service.AdminAuditService; +import com.ibrasoft.lensbridge.service.UserService; +import com.ibrasoft.lensbridge.service.board.offline.UsbKitService; +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.context.annotation.Import; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(controllers = UsbKitController.class) +@Import(MethodSecurityTestConfig.class) +class UsbKitControllerTest { + + private static final UUID DEVICE_ID = UUID.fromString("3f2a1b4c-0000-4000-8000-000000000001"); + + @Autowired + private MockMvc mockMvc; + + @MockitoBean private UsbKitService usbKitService; + @MockitoBean private DeviceRepository deviceRepository; + @MockitoBean private AdminAuditService auditService; + @MockitoBean private UserService userService; + + private UsbKitService.Kit kit(String filename, List omitted) throws Exception { + Path file = Files.createTempFile("usb-kit-test-", ".zip"); + Files.write(file, new byte[]{'P', 'K', 5, 6}); + return new UsbKitService.Kit(file, filename, omitted); + } + + @Test + void readingDevicesIsEnoughForAContentKit() throws Exception { + Device device = Device.builder().id(DEVICE_ID).displayName("North").audience(Audience.BOTH).build(); + when(deviceRepository.findById(DEVICE_ID)).thenReturn(Optional.of(device)); + UsbKitService.Kit kit = kit("musallahboard-usb-kit-3f2a1b4c-2026-11-19.zip", List.of()); + when(usbKitService.build(eq(List.of(device)), anyString(), eq(31), eq(false), eq(false))).thenReturn(kit); + + byte[] body = mockMvc.perform(get("/api/admin/board/devices/" + DEVICE_ID + "/usb-kit").param("days", "31") + .with(TestAuthorities.asHolderOf(Permission.BOARD_DEVICE_READ))) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", "application/zip")) + .andExpect(header().string("Content-Disposition", org.hamcrest.Matchers.startsWith( + "attachment; filename=\"musallahboard-usb-kit-3f2a1b4c-"))) + .andExpect(header().doesNotExist(UsbKitController.OMITTED_HEADER)) + .andReturn().getResponse().getContentAsByteArray(); + + assertThat(body).containsExactly('P', 'K', 5, 6); + assertThat(Files.exists(kit.file())).as("temp file removed").isFalse(); + verifyNoInteractions(auditService); + } + + /** Setup files can carry a claim secret. */ + @Test + void setupFilesInAKitNeedTheEnrollPermission() throws Exception { + mockMvc.perform(get("/api/admin/board/usb-kit").param("includeSetup", "true") + .with(TestAuthorities.asHolderOf(Permission.BOARD_DEVICE_READ))) + .andExpect(status().isForbidden()); + verifyNoInteractions(usbKitService); + + Device a = Device.builder().id(DEVICE_ID).displayName("North").audience(Audience.BOTH).build(); + when(deviceRepository.findByRevokedAtIsNullOrderByDisplayNameAsc()).thenReturn(List.of(a)); + when(usbKitService.build(any(), anyString(), anyInt(), anyBoolean(), anyBoolean())) + .thenReturn(kit("musallahboard-usb-kit-all-2026-11-19.zip", List.of("agent: could not fetch"))); + + mockMvc.perform(get("/api/admin/board/usb-kit").param("includeSetup", "true").param("online", "true") + .with(TestAuthorities.asHolderOf(Permission.BOARD_DEVICE_READ, Permission.BOARD_DEVICE_ENROLL))) + .andExpect(status().isOk()) + .andExpect(header().string(UsbKitController.OMITTED_HEADER, "agent: could not fetch")); + verify(usbKitService).build(eq(List.of(a)), anyString(), eq(14), eq(true), eq(true)); + } + + @Test + void anUnknownBoardIsA404() throws Exception { + when(deviceRepository.findById(DEVICE_ID)).thenReturn(Optional.empty()); + mockMvc.perform(get("/api/admin/board/devices/" + DEVICE_ID + "/usb-kit") + .with(TestAuthorities.asHolderOf(Permission.BOARD_DEVICE_READ))) + .andExpect(status().isNotFound()); + } +} diff --git a/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandlerTest.java b/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandlerTest.java deleted file mode 100644 index be84aaa..0000000 --- a/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandlerTest.java +++ /dev/null @@ -1,273 +0,0 @@ -package com.ibrasoft.lensbridge.handler; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.ibrasoft.lensbridge.model.board.Device; -import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.web.socket.CloseStatus; -import org.springframework.web.socket.TextMessage; -import org.springframework.web.socket.WebSocketSession; - -import java.net.URI; -import java.time.Instant; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -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 static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -class BoardStreamHandlerTest { - - private final ObjectMapper mapper = new ObjectMapper(); - private DeviceRepository deviceRepository; - private BoardStreamHandler handler; - - @BeforeEach - void setUp() { - deviceRepository = mock(DeviceRepository.class); - when(deviceRepository.findById(any())).thenReturn(Optional.empty()); - handler = new BoardStreamHandler(mapper, deviceRepository); - } - - @Test - void contentPushReachesEveryConnectedBoard() throws Exception { - Session a = connect(enrolled()); - Session b = connect(enrolled()); - - handler.contentChanged("posters"); - - assertThat(a.sent).hasSize(1); - assertThat(b.sent).hasSize(1); - } - - @Test - void configPushReachesOnlyTheTargetBoard() throws Exception { - UUID target = enrolled(); - Session mine = connect(target); - Session theirs = connect(enrolled()); - - handler.configChanged(target); - - assertThat(mine.sent).hasSize(1); - assertThat(theirs.sent).isEmpty(); - } - - @Test - void messageIsJsonCarryingTypeReasonAndTarget() throws Exception { - UUID target = enrolled(); - Session s = connect(target); - - handler.configChanged(target); - - JsonNode body = mapper.readTree(s.sent.get(0)); - assertThat(body.get("type").asText()).isEqualTo("refresh"); - assertThat(body.get("reason").asText()).isEqualTo("config"); - assertThat(body.get("deviceId").asText()).isEqualTo(target.toString()); - assertThat(body.hasNonNull("at")).isTrue(); - } - - // ── enrollment is a precondition, not a state ───────────────────────── - - @Test - void connectionWithoutADeviceIdIsRejected() throws Exception { - Session s = connectWithQuery(null); - - assertThat(s.closedWith).isNotNull(); - assertThat(s.closedWith.getCode()).isEqualTo(4001); - - handler.contentChanged("events"); - assertThat(s.sent).isEmpty(); - } - - @Test - void malformedDeviceIdIsRejected() throws Exception { - Session s = connectWithQuery("deviceId=not-a-uuid"); - - assertThat(s.closedWith.getCode()).isEqualTo(4001); - } - - @Test - void unknownDeviceIsRejected() throws Exception { - // deviceRepository returns empty for anything not explicitly enrolled. - Session s = connectWithQuery("deviceId=" + UUID.randomUUID()); - - assertThat(s.closedWith.getCode()).isEqualTo(4002); - - handler.contentChanged("events"); - assertThat(s.sent).isEmpty(); - } - - @Test - void revokedDeviceIsRejected() throws Exception { - UUID id = UUID.randomUUID(); - Device revoked = Device.builder().id(id).displayName("d").build(); - revoked.setRevokedAt(Instant.now().minusSeconds(60)); - when(deviceRepository.findById(id)).thenReturn(Optional.of(revoked)); - - Session s = connect(id); - - assertThat(s.closedWith.getCode()).isEqualTo(4003); - } - - // ── session lifecycle ───────────────────────────────────────────────── - - @Test - void reconnectSupersedesThePriorSessionForTheSameDevice() throws Exception { - UUID device = enrolled(); - Session first = connect(device); - Session second = connect(device); - - assertThat(first.closedWith).isNotNull(); - - handler.configChanged(device); - assertThat(second.sent).hasSize(1); - assertThat(first.sent).isEmpty(); - } - - /** - * A superseded session's close callback arrives after its replacement is already - * registered. It must not evict the newcomer. - */ - @Test - void lateCloseOfASupersededSessionLeavesTheReplacementRegistered() throws Exception { - UUID device = enrolled(); - Session first = connect(device); - Session second = connect(device); - - handler.afterConnectionClosed(first.ws, CloseStatus.NORMAL); - - handler.configChanged(device); - assertThat(second.sent).hasSize(1); - } - - @Test - void disconnectStopsDelivery() throws Exception { - Session s = connect(enrolled()); - handler.afterConnectionClosed(s.ws, CloseStatus.NORMAL); - - handler.contentChanged("events"); - - assertThat(s.sent).isEmpty(); - } - - @Test - void closedSessionsAreDroppedAndNeverWrittenTo() throws Exception { - Session s = connect(enrolled()); - s.open = false; - - handler.contentChanged("events"); - - assertThat(s.sent).isEmpty(); - } - - /** - * Pushes come from arbitrary admin request threads. The container throws when two threads - * write to one session at once, and that failure used to be swallowed, so a board silently - * missed its refresh. Writes to one board must never overlap and none may be lost. - */ - @Test - void concurrentPushesToOneBoardNeverOverlapOnTheSocket() throws Exception { - UUID target = enrolled(); - Session s = connect(target); - AtomicInteger inFlight = new AtomicInteger(); - AtomicInteger maxInFlight = new AtomicInteger(); - AtomicInteger written = new AtomicInteger(); - doAnswer(inv -> { - maxInFlight.accumulateAndGet(inFlight.incrementAndGet(), Math::max); - Thread.sleep(1); - inFlight.decrementAndGet(); - written.incrementAndGet(); - return null; - }).when(s.ws).sendMessage(any()); - - int threads = 6; - int perThread = 20; - ExecutorService pool = Executors.newFixedThreadPool(threads); - CountDownLatch go = new CountDownLatch(1); - List> done = new ArrayList<>(); - for (int t = 0; t < threads; t++) { - done.add(pool.submit(() -> { - go.await(); - for (int i = 0; i < perThread; i++) handler.configChanged(target); - return null; - })); - } - go.countDown(); - for (Future f : done) f.get(30, TimeUnit.SECONDS); - pool.shutdown(); - - assertThat(maxInFlight.get()).isEqualTo(1); - assertThat(written.get()).isEqualTo(threads * perThread); - } - - @Test - void closeCallbackOfTheRawSessionStillRemovesItsWrapper() throws Exception { - UUID device = enrolled(); - Session s = connect(device); - - handler.afterConnectionClosed(s.ws, CloseStatus.NORMAL); - s.open = true; // a leftover registration would write to it - - handler.configChanged(device); - assertThat(s.sent).isEmpty(); - } - - // ── helpers ─────────────────────────────────────────────────────────── - - /** Registers a device the repository will vouch for, and returns its id. */ - private UUID enrolled() { - UUID id = UUID.randomUUID(); - when(deviceRepository.findById(id)) - .thenReturn(Optional.of(Device.builder().id(id).displayName("board").build())); - return id; - } - - private Session connect(UUID deviceId) throws Exception { - return connectWithQuery("deviceId=" + deviceId); - } - - private Session connectWithQuery(String query) throws Exception { - Session session = new Session(query); - handler.afterConnectionEstablished(session.ws); - return session; - } - - /** Minimal stand-in that records what the handler writes and how it closes. */ - private static class Session { - final WebSocketSession ws = mock(WebSocketSession.class); - final List sent = new ArrayList<>(); - boolean open = true; - CloseStatus closedWith; - - Session(String query) throws Exception { - when(ws.getId()).thenReturn(UUID.randomUUID().toString()); - when(ws.getUri()).thenReturn(URI.create( - "ws://board.local/api/refresh-musallahboard" + (query == null ? "" : "?" + query))); - when(ws.isOpen()).thenAnswer(inv -> open); - when(ws.getAttributes()).thenReturn(new HashMap<>()); - doAnswer(inv -> { - sent.add(((TextMessage) inv.getArgument(0)).getPayload()); - return null; - }).when(ws).sendMessage(any()); - doAnswer(inv -> { - closedWith = inv.getArgument(0); - open = false; - return null; - }).when(ws).close(any(CloseStatus.class)); - } - } -} diff --git a/src/test/java/com/ibrasoft/lensbridge/repository/sql/DeviceRepositoryTest.java b/src/test/java/com/ibrasoft/lensbridge/repository/sql/DeviceRepositoryTest.java index 6ab8be8..6be1c1e 100644 --- a/src/test/java/com/ibrasoft/lensbridge/repository/sql/DeviceRepositoryTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/repository/sql/DeviceRepositoryTest.java @@ -46,4 +46,25 @@ void aHeartbeatFlushDoesNotUndoARevokeCommittedMeanwhile() { assertThat(reloaded.getRevokedAt()).isNotNull(); assertThat(reloaded.getLastHeartbeat()).isNotNull(); } + + /** A board created in the console: no key, no enrollment time; the claim columns from V5 round-trip. */ + @Test + void aPreCreatedDeviceHasNoKeyAndKeepsItsClaimSecret() { + byte[] secret = new byte[32]; + java.util.Arrays.fill(secret, (byte) 7); + Device saved = repository.saveAndFlush(Device.builder() + .displayName("North Musallah") + .audience(Audience.BOTH) + .claimSecret(secret) + .provisionSequence(1795089600250L) + .build()); + em.clear(); + + Device reloaded = repository.findById(saved.getId()).orElseThrow(); + assertThat(reloaded.getPublicKey()).isNull(); + assertThat(reloaded.getEnrolledAt()).isNull(); + assertThat(reloaded.getClaimSecret()).isEqualTo(secret); + assertThat(reloaded.getProvisionSequence()).isEqualTo(1795089600250L); + assertThat(reloaded.toString()).doesNotContain("claimSecret"); + } } diff --git a/src/test/java/com/ibrasoft/lensbridge/repository/sql/PosterRepositoryTest.java b/src/test/java/com/ibrasoft/lensbridge/repository/sql/PosterRepositoryTest.java new file mode 100644 index 0000000..16699d9 --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/repository/sql/PosterRepositoryTest.java @@ -0,0 +1,52 @@ +package com.ibrasoft.lensbridge.repository.sql; + +import com.ibrasoft.lensbridge.model.board.Audience; +import com.ibrasoft.lensbridge.model.board.Poster; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.time.Instant; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * A poster's end date is what keeps it off the days after it (contract C6): each day of a + * content package asks for the posters overlapping that day, on the real schema. + */ +@SqliteDataJpaTest +class PosterRepositoryTest { + + @Autowired + private PosterRepository posters; + + private Poster save(String title, String start, String end, Audience audience) { + return posters.saveAndFlush(Poster.builder().title(title).image("https://media.example.com/" + title + ".jpg") + .duration(10).startTime(Instant.parse(start)).endTime(Instant.parse(end)).audience(audience).build()); + } + + private List titlesOn(String dayStart, String nextDayStart, Audience audience) { + return posters.findPostersForAudienceOverlapping(Instant.parse(dayStart), Instant.parse(nextDayStart), audience) + .stream().map(Poster::getTitle).toList(); + } + + @Test + void aPosterShowsUntilItsEndDateAndNotAfter() { + save("iftar", "2026-11-01T05:00:00Z", "2026-11-20T05:00:00Z", Audience.BOTH); + + assertThat(titlesOn("2026-11-19T05:00:00Z", "2026-11-20T05:00:00Z", Audience.BROTHERS)).containsExactly("iftar"); + assertThat(titlesOn("2026-11-20T05:00:00Z", "2026-11-21T05:00:00Z", Audience.BROTHERS)) + .as("the day after it ends").isEmpty(); + assertThat(titlesOn("2026-10-31T04:00:00Z", "2026-11-01T04:00:00Z", Audience.BROTHERS)) + .as("the day before it starts").isEmpty(); + } + + @Test + void anotherAudiencesPosterIsLeftOut() { + save("sisters-halaqa", "2026-11-01T05:00:00Z", "2026-12-01T05:00:00Z", Audience.SISTERS); + + assertThat(titlesOn("2026-11-19T05:00:00Z", "2026-11-20T05:00:00Z", Audience.BROTHERS)).isEmpty(); + assertThat(titlesOn("2026-11-19T05:00:00Z", "2026-11-20T05:00:00Z", Audience.SISTERS)) + .containsExactly("sisters-halaqa"); + } +} diff --git a/src/test/java/com/ibrasoft/lensbridge/service/BoardServiceTest.java b/src/test/java/com/ibrasoft/lensbridge/service/BoardServiceTest.java index 9e531fd..d13ac67 100644 --- a/src/test/java/com/ibrasoft/lensbridge/service/BoardServiceTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/service/BoardServiceTest.java @@ -3,12 +3,14 @@ import com.ibrasoft.lensbridge.dto.board.request.CreateCalendarEventRequest; import com.ibrasoft.lensbridge.dto.board.request.UpdateBoardConfigRequest; import com.ibrasoft.lensbridge.dto.board.request.UpdateCalendarEventRequest; +import com.ibrasoft.lensbridge.dto.board.request.CreateDeviceRequest; import com.ibrasoft.lensbridge.dto.board.request.UpdateDeviceRequest; import com.ibrasoft.lensbridge.dto.board.request.WeeklyContentRequest; import com.ibrasoft.lensbridge.exception.ApiResponseException; -import com.ibrasoft.lensbridge.handler.BoardStreamHandler; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; import com.ibrasoft.lensbridge.model.board.Audience; import com.ibrasoft.lensbridge.model.board.BoardEvent; +import com.ibrasoft.lensbridge.model.board.CalculationMethod; import com.ibrasoft.lensbridge.model.board.Device; import com.ibrasoft.lensbridge.model.board.IslamicQuote; import com.ibrasoft.lensbridge.model.board.Location; @@ -53,7 +55,7 @@ class BoardServiceTest { @Mock private WeeklyContentRepository weeklyContentRepository; @Mock - private BoardStreamHandler boardStream; + private ContentChangeNotifier contentChanges; @InjectMocks private BoardService service; @@ -299,7 +301,7 @@ void createEventBuildsAndPersists() { assertThat(created.getAudience()).isEqualTo(Audience.BOTH); assertThat(created.getStartTime()).isEqualTo(start); assertThat(created.getEndTime()).isEqualTo(start.plusSeconds(3600)); - verify(boardStream).contentChanged("events"); + verify(contentChanges).contentChanged("events"); } /** allDay is optional in the contract; null must not reach the NOT NULL column. */ @@ -632,35 +634,13 @@ void saveWeeklyContentAcceptsANullJummahTime() { } @Test - void saveWeeklyContentNotifiesImmediatelyWhenThereIsNoTransaction() { + void saveWeeklyContentTellsTheBoards() { when(weeklyContentRepository.findByYearAndWeekNumber(2026, 20)).thenReturn(Optional.empty()); when(weeklyContentRepository.save(any(WeeklyContent.class))).thenAnswer(inv -> inv.getArgument(0)); service.saveWeeklyContent(2026, 20, WeeklyContentRequest.builder().build()); - verify(boardStream).contentChanged("weekly-content"); - } - - /** Notifying before the commit let a board refetch and read the old content. */ - @Test - void saveWeeklyContentNotifiesOnlyAfterTheTransactionCommits() { - when(weeklyContentRepository.findByYearAndWeekNumber(2026, 20)).thenReturn(Optional.empty()); - when(weeklyContentRepository.save(any(WeeklyContent.class))).thenAnswer(inv -> inv.getArgument(0)); - - org.springframework.transaction.support.TransactionSynchronizationManager.initSynchronization(); - try { - service.saveWeeklyContent(2026, 20, WeeklyContentRequest.builder().build()); - - verify(boardStream, never()).contentChanged(any()); - - for (var sync : org.springframework.transaction.support.TransactionSynchronizationManager - .getSynchronizations()) { - sync.afterCommit(); - } - verify(boardStream).contentChanged("weekly-content"); - } finally { - org.springframework.transaction.support.TransactionSynchronizationManager.clearSynchronization(); - } + verify(contentChanges).contentChanged("weekly-content"); } // ==================== slide durations ==================== @@ -787,4 +767,47 @@ void updateDeviceRejectsAnUnknownDevice() { verify(deviceRepository, never()).save(any(Device.class)); } + + // ==================== createDevice ==================== + + @Test + void createDeviceMakesABoardWithNoKeyAndItsConfig() { + UUID id = UUID.randomUUID(); + when(deviceRepository.save(any(Device.class))).thenAnswer(inv -> { + Device d = inv.getArgument(0); + d.setId(id); + return d; + }); + when(boardConfigRepository.save(any(DeviceConfig.class))).thenAnswer(inv -> inv.getArgument(0)); + + Device created = service.createDevice(CreateDeviceRequest.builder() + .displayName(" North Musallah ") + .audience(Audience.SISTERS) + .location(Location.builder().city("Toronto").latitude(43.65).longitude(-79.38).build()) + .build()); + + assertThat(created.getId()).isEqualTo(id); + assertThat(created.getDisplayName()).isEqualTo("North Musallah"); + assertThat(created.getPublicKey()).isNull(); + assertThat(created.getEnrolledAt()).as("not enrolled until it claims").isNull(); + Location location = created.getConfig().getLocation(); + assertThat(location.getCity()).isEqualTo("Toronto"); + assertThat(location.getLatitude()).isEqualTo(43.65); + // Left out of the request: the defaults. + assertThat(location.getTimezone()).isEqualTo("America/Toronto"); + assertThat(location.getMethod()).isEqualTo(CalculationMethod.ISNA); + assertThat(created.getConfig().getDevice()).isSameAs(created); + } + + @Test + void createDeviceRejectsAnUnusableLocation() { + when(deviceRepository.save(any(Device.class))).thenAnswer(inv -> inv.getArgument(0)); + + assertThatThrownBy(() -> service.createDevice(CreateDeviceRequest.builder() + .displayName("A").audience(Audience.BOTH) + .location(Location.builder().timezone("Mars/Olympus").build()).build())) + .isInstanceOfSatisfying(ApiResponseException.class, + e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST)); + verify(boardConfigRepository, never()).save(any()); + } } diff --git a/src/test/java/com/ibrasoft/lensbridge/service/PosterServiceTest.java b/src/test/java/com/ibrasoft/lensbridge/service/PosterServiceTest.java index bd3313d..f6e543a 100644 --- a/src/test/java/com/ibrasoft/lensbridge/service/PosterServiceTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/service/PosterServiceTest.java @@ -3,7 +3,7 @@ import com.ibrasoft.lensbridge.dto.board.request.CreatePosterRequest; import com.ibrasoft.lensbridge.dto.board.request.UpdatePosterRequest; import com.ibrasoft.lensbridge.exception.ApiResponseException; -import com.ibrasoft.lensbridge.handler.BoardStreamHandler; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; import com.ibrasoft.lensbridge.model.board.Audience; import com.ibrasoft.lensbridge.model.board.Poster; import com.ibrasoft.lensbridge.repository.sql.PosterRepository; @@ -42,7 +42,7 @@ class PosterServiceTest { private R2StorageService r2StorageService; @Mock - private BoardStreamHandler boardStream; + private ContentChangeNotifier contentChanges; @InjectMocks private PosterService service; diff --git a/src/test/java/com/ibrasoft/lensbridge/service/PromotableSocialMediaServiceTest.java b/src/test/java/com/ibrasoft/lensbridge/service/PromotableSocialMediaServiceTest.java index b1d0867..5466ba9 100644 --- a/src/test/java/com/ibrasoft/lensbridge/service/PromotableSocialMediaServiceTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/service/PromotableSocialMediaServiceTest.java @@ -3,7 +3,7 @@ import com.ibrasoft.lensbridge.dto.board.request.CreatePromotableSocialMediaRequest; import com.ibrasoft.lensbridge.dto.board.request.UpdatePromotableSocialMediaRequest; import com.ibrasoft.lensbridge.exception.ApiResponseException; -import com.ibrasoft.lensbridge.handler.BoardStreamHandler; +import com.ibrasoft.lensbridge.service.agent.ContentChangeNotifier; import com.ibrasoft.lensbridge.model.board.Audience; import com.ibrasoft.lensbridge.model.board.PromotableSocialMedia; import com.ibrasoft.lensbridge.model.board.SocialType; @@ -33,7 +33,7 @@ class PromotableSocialMediaServiceTest { private PromotableSocialMediaRepository repository; @Mock - private BoardStreamHandler boardStream; + private ContentChangeNotifier contentChanges; @InjectMocks private PromotableSocialMediaService service; @@ -117,7 +117,7 @@ void createPersistsAllFieldsAndNotifiesBoards() { assertThat(created.getDuration()).isEqualTo(13); assertThat(created.getAudience()).isEqualTo(Audience.BOTH); assertThat(created.getHandle()).isEqualTo("@utmmsa"); - verify(boardStream).contentChanged("socials"); + verify(contentChanges).contentChanged("socials"); } @Test @@ -176,7 +176,7 @@ void updateAppliesOnlyNonNullFields() { assertThat(updated.getDuration()).isEqualTo(13); // unchanged assertThat(updated.getAudience()).isEqualTo(Audience.BOTH); // unchanged assertThat(updated.getHandle()).isEqualTo("@utmmsa"); // unchanged - verify(boardStream).contentChanged("socials"); + verify(contentChanges).contentChanged("socials"); } @Test @@ -302,7 +302,7 @@ void deleteRemovesEntityAndNotifiesBoards() { service.delete(existing.getId()); verify(repository).delete(existing); - verify(boardStream).contentChanged("socials"); + verify(contentChanges).contentChanged("socials"); } @Test diff --git a/src/test/java/com/ibrasoft/lensbridge/service/agent/ContentChangeNotifierTest.java b/src/test/java/com/ibrasoft/lensbridge/service/agent/ContentChangeNotifierTest.java new file mode 100644 index 0000000..aba1178 --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/service/agent/ContentChangeNotifierTest.java @@ -0,0 +1,105 @@ +package com.ibrasoft.lensbridge.service.agent; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.ibrasoft.lensbridge.service.agent.events.DeviceEventPublisher; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.web.socket.TextMessage; +import org.springframework.web.socket.WebSocketSession; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class ContentChangeNotifierTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private AgentSessionRegistry registry; + private ContentChangeNotifier notifier; + + @BeforeEach + void setUp() { + registry = new AgentSessionRegistry(mock(DeviceEventPublisher.class)); + notifier = new ContentChangeNotifier(registry); + } + + @AfterEach + void clearTransaction() { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + private AgentSession connected(UUID deviceId) { + WebSocketSession ws = mock(WebSocketSession.class); + when(ws.isOpen()).thenReturn(true); + AgentSession session = new AgentSession(ws, "challenge", mapper); + session.markAuthenticated(deviceId); + registry.register(deviceId, session); + return session; + } + + private JsonNode lastFrame(AgentSession session) throws Exception { + ArgumentCaptor sent = ArgumentCaptor.forClass(TextMessage.class); + verify(session.getTransport(), atLeastOnce()).sendMessage(sent.capture()); + return mapper.readTree(sent.getValue().getPayload()); + } + + /** The frame the agent waits for (contract C5): type content_changed, nothing else but the envelope. */ + @Test + void contentChangedSendsTheFrameToEveryConnectedBoard() throws Exception { + AgentSession a = connected(UUID.randomUUID()); + AgentSession b = connected(UUID.randomUUID()); + + notifier.contentChanged("posters"); + + for (AgentSession s : new AgentSession[]{a, b}) { + JsonNode frame = lastFrame(s); + assertThat(frame.get("type").asText()).isEqualTo("content_changed"); + assertThat(frame.get("seq").asLong()).isPositive(); + assertThat(frame.get("sessionId").asText()).isEqualTo(s.getSessionId().toString()); + assertThat(frame.size()).as("only type and the frame envelope").isEqualTo(3); + } + } + + @Test + void deviceChangedReachesOnlyThatBoard() throws Exception { + UUID target = UUID.randomUUID(); + AgentSession mine = connected(target); + AgentSession other = connected(UUID.randomUUID()); + + notifier.deviceChanged(target, "config"); + + assertThat(lastFrame(mine).get("type").asText()).isEqualTo("content_changed"); + verify(other.getTransport(), never()).sendMessage(any()); + } + + @Test + void aBoardThatIsNotConnectedIsSkipped() { + notifier.deviceChanged(UUID.randomUUID(), "config"); + notifier.contentChanged("events"); + // Nothing to assert beyond "does not throw": there is no session to write to. + } + + /** Sending inside the transaction would let a board fetch before the change is visible. */ + @Test + void waitsForTheTransactionToCommit() throws Exception { + AgentSession s = connected(UUID.randomUUID()); + TransactionSynchronizationManager.initSynchronization(); + + notifier.contentChanged("weekly-content"); + verify(s.getTransport(), never()).sendMessage(any()); + + for (TransactionSynchronization sync : TransactionSynchronizationManager.getSynchronizations()) { + sync.afterCommit(); + } + assertThat(lastFrame(s).get("type").asText()).isEqualTo("content_changed"); + } +} diff --git a/src/test/java/com/ibrasoft/lensbridge/service/agent/DeviceClaimServiceTest.java b/src/test/java/com/ibrasoft/lensbridge/service/agent/DeviceClaimServiceTest.java new file mode 100644 index 0000000..0af40be --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/service/agent/DeviceClaimServiceTest.java @@ -0,0 +1,193 @@ +package com.ibrasoft.lensbridge.service.agent; + +import com.ibrasoft.lensbridge.model.board.Audience; +import com.ibrasoft.lensbridge.model.board.Device; +import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; +import com.ibrasoft.lensbridge.repository.sql.SqliteDataJpaTest; +import jakarta.persistence.EntityManager; +import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Import; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * The online claim (contract C2) against the real schema, so the conditional bind is the + * database's. Uses the cross-repo HMAC test vector the agent's tests use too. + */ +@SqliteDataJpaTest +@Import(DeviceClaimService.class) +class DeviceClaimServiceTest { + + /** + * The shared vector: deviceId ...0001, claimSecret 32 x 0x01, publicKey the Ed25519 key of + * seed 32 x 0x02 (base64 std), msg = deviceId + "\n" + publicKey. Checked independently with + * Python (hmac, cryptography); padded, the proof ends in "=". + */ + static final String VECTOR_DEVICE_ID = "00000000-0000-0000-0000-000000000001"; + static final String VECTOR_PUBLIC_KEY = "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q="; + static final String VECTOR_PROOF = "2_nUd8LSmcq1kdXUvLW5ZQkAr_yDjiTuIh2AzpJH2sA"; + + @Autowired + private DeviceClaimService claims; + @Autowired + private DeviceRepository devices; + @Autowired + private EntityManager em; + + private final byte[] secret = filled(0x01); + private UUID deviceId; + + private static byte[] filled(int value) { + byte[] b = new byte[32]; + Arrays.fill(b, (byte) value); + return b; + } + + private static String publicKeyOfSeed(int value) { + return Base64.getEncoder().encodeToString( + new Ed25519PrivateKeyParameters(filled(value), 0).generatePublicKey().getEncoded()); + } + + private String proof(byte[] withSecret, UUID id, String publicKey) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(DeviceClaimService.proof(withSecret, id, publicKey)); + } + + @BeforeEach + void preCreatedBoard() { + deviceId = devices.saveAndFlush(Device.builder() + .displayName("North Musallah").audience(Audience.BOTH).claimSecret(secret).build()).getId(); + em.clear(); + } + + private DeviceClaimService.Outcome claim(UUID id, String publicKey, String proof) { + DeviceClaimService.Outcome outcome = claims.claim(id, publicKey, proof, "0.5.0", "board-1", "10.0.0.7"); + em.flush(); + em.clear(); + return outcome; + } + + @Test + void theSharedTestVector() { + String publicKey = publicKeyOfSeed(0x02); + String proof = proof(filled(0x01), UUID.fromString(VECTOR_DEVICE_ID), publicKey); + System.out.println("claim HMAC test vector: deviceId=" + VECTOR_DEVICE_ID + " claimSecret=32x0x01 (base64url " + + Base64.getUrlEncoder().withoutPadding().encodeToString(filled(0x01)) + ") publicKey=" + publicKey + + " proof=" + proof); + assertThat(publicKey).isEqualTo(VECTOR_PUBLIC_KEY); + assertThat(proof).isEqualTo(VECTOR_PROOF); + } + + @Test + void aFirstClaimBindsTheKeyAndReturnsTheDevice() { + String key = publicKeyOfSeed(0x02); + + DeviceClaimService.Outcome outcome = claim(deviceId, key, proof(secret, deviceId, key)); + + assertThat(outcome).isInstanceOf(DeviceClaimService.Outcome.Ok.class); + Device bound = devices.findById(deviceId).orElseThrow(); + assertThat(Base64.getEncoder().encodeToString(bound.getPublicKey())).isEqualTo(key); + assertThat(bound.getEnrolledAt()).isNotNull(); + assertThat(bound.getAgentVersion()).isEqualTo("0.5.0"); + assertThat(bound.getLastSeenIp()).isEqualTo("10.0.0.7"); + assertThat(bound.getClaimSecret()).as("kept for retries").isEqualTo(secret); + } + + /** A board whose response was lost retries with the same key. */ + @Test + void claimingAgainWithTheSameKeySucceeds() { + String key = publicKeyOfSeed(0x02); + claim(deviceId, key, proof(secret, deviceId, key)); + Instant first = devices.findById(deviceId).orElseThrow().getEnrolledAt(); + em.clear(); + + assertThat(claim(deviceId, key, proof(secret, deviceId, key))).isInstanceOf(DeviceClaimService.Outcome.Ok.class); + assertThat(devices.findById(deviceId).orElseThrow().getEnrolledAt()).isEqualTo(first); + } + + @Test + void anotherKeyIsAConflictAndTheFirstStays() { + String key = publicKeyOfSeed(0x02); + claim(deviceId, key, proof(secret, deviceId, key)); + String other = publicKeyOfSeed(0x03); + + assertThat(claim(deviceId, other, proof(secret, deviceId, other))) + .isInstanceOf(DeviceClaimService.Outcome.KeyConflict.class); + assertThat(Base64.getEncoder().encodeToString(devices.findById(deviceId).orElseThrow().getPublicKey())) + .isEqualTo(key); + } + + @Test + void aWrongProofIsRefusedAndBindsNothing() { + String key = publicKeyOfSeed(0x02); + + assertThat(claim(deviceId, key, proof(filled(0x09), deviceId, key))) + .as("an older setup file's secret").isInstanceOf(DeviceClaimService.Outcome.Refused.class); + assertThat(claim(deviceId, key, proof(secret, deviceId, publicKeyOfSeed(0x03)))) + .as("a proof for another key").isInstanceOf(DeviceClaimService.Outcome.Refused.class); + assertThat(devices.findById(deviceId).orElseThrow().getPublicKey()).isNull(); + } + + /** The proof covers the exact publicKey string sent, so re-encoding it breaks the proof. */ + @Test + void theProofCoversThePublicKeyStringAsSent() { + String key = publicKeyOfSeed(0x02); + String proof = proof(secret, deviceId, key); + + assertThat(claim(deviceId, key.replace("=", ""), proof)).isInstanceOf(DeviceClaimService.Outcome.Refused.class); + } + + @Test + void paddedAndUnpaddedProofsAreBothAccepted() { + String key = publicKeyOfSeed(0x02); + String padded = Base64.getUrlEncoder().encodeToString(DeviceClaimService.proof(secret, deviceId, key)); + assertThat(padded).endsWith("="); + + assertThat(claim(deviceId, key, padded)).isInstanceOf(DeviceClaimService.Outcome.Ok.class); + } + + @Test + void unknownRevokedAndNeverOnlineDevicesAreRefusedAlike() { + String key = publicKeyOfSeed(0x02); + UUID unknown = UUID.randomUUID(); + assertThat(claim(unknown, key, proof(secret, unknown, key))).isInstanceOf(DeviceClaimService.Outcome.Refused.class); + + UUID offline = devices.saveAndFlush(Device.builder().displayName("Offline").audience(Audience.BOTH).build()).getId(); + assertThat(claim(offline, key, proof(secret, offline, key))).isInstanceOf(DeviceClaimService.Outcome.Refused.class); + + Device revoked = devices.findById(deviceId).orElseThrow(); + revoked.setRevokedAt(Instant.now()); + devices.saveAndFlush(revoked); + em.clear(); + assertThat(claim(deviceId, key, proof(secret, deviceId, key))).isInstanceOf(DeviceClaimService.Outcome.Refused.class); + assertThat(devices.findById(deviceId).orElseThrow().getPublicKey()).isNull(); + } + + @Test + void malformedInputIsABadRequest() { + String key = publicKeyOfSeed(0x02); + assertThat(claim(deviceId, "not base64!", proof(secret, deviceId, key))) + .isInstanceOf(DeviceClaimService.Outcome.BadRequest.class); + assertThat(claim(deviceId, Base64.getEncoder().encodeToString(new byte[31]), proof(secret, deviceId, key))) + .isInstanceOf(DeviceClaimService.Outcome.BadRequest.class); + assertThat(claim(deviceId, key, "+/+/")) + .isInstanceOf(DeviceClaimService.Outcome.BadRequest.class); + } + + /** Two boards racing for one device: the database lets exactly one bind. */ + @Test + void theBindOnlyWinsOnce() { + byte[] a = Base64.getDecoder().decode(publicKeyOfSeed(0x02)); + byte[] b = Base64.getDecoder().decode(publicKeyOfSeed(0x03)); + assertThat(devices.bindPublicKeyIfUnset(deviceId, a)).isEqualTo(1); + assertThat(devices.bindPublicKeyIfUnset(deviceId, b)).isEqualTo(0); + assertThat(devices.findById(deviceId).orElseThrow().getPublicKey()).isEqualTo(a); + } +} diff --git a/src/test/java/com/ibrasoft/lensbridge/service/agent/DeviceEnrollmentServiceTest.java b/src/test/java/com/ibrasoft/lensbridge/service/agent/DeviceEnrollmentServiceTest.java index a26d002..8a5ca03 100644 --- a/src/test/java/com/ibrasoft/lensbridge/service/agent/DeviceEnrollmentServiceTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/service/agent/DeviceEnrollmentServiceTest.java @@ -32,6 +32,8 @@ class DeviceEnrollmentServiceTest { private DeviceRepository deviceRepository; @Mock private BoardConfigRepository boardConfigRepository; + @Mock + private AgentSessionRegistry sessionRegistry; @InjectMocks private DeviceEnrollmentService service; @@ -147,4 +149,64 @@ void enrollRecordsTheRealDeviceIdOnTheTokenAndWritesDefaultConfig() { assertThat(cfg.getValue().getDevice()).isSameAs(saved); assertThat(cfg.getValue().getLocation().getCity()).isEqualTo("Mississauga"); } + + // ==================== tokens issued for a board created in the console ==================== + + private Device preCreated(byte[] key) { + Device d = Device.builder().id(UUID.randomUUID()).displayName("North Musallah") + .audience(Audience.SISTERS).publicKey(key).build(); + when(deviceRepository.findById(d.getId())).thenReturn(Optional.of(d)); + return d; + } + + @Test + void aTokenForAPreCreatedBoardBindsTheKeyToThatRow() { + Device existing = preCreated(null); + EnrollmentToken t = token(); + t.setDeviceId(existing.getId()); + when(enrollmentTokenService.consume("tok")).thenReturn(Optional.of(t)); + byte[] key = new byte[32]; + key[0] = 9; + + var outcome = service.enroll("tok", Base64.getEncoder().encodeToString(key), "host", "RPi4", "0.5.0", "1.2.3.4"); + + assertThat(outcome).isInstanceOf(DeviceEnrollmentService.Outcome.Ok.class); + Device bound = ((DeviceEnrollmentService.Outcome.Ok) outcome).device(); + assertThat(bound.getId()).isEqualTo(existing.getId()); + assertThat(bound.getPublicKey()).isEqualTo(key); + assertThat(bound.getDisplayName()).as("the console's name is kept").isEqualTo("North Musallah"); + assertThat(bound.getEnrolledAt()).isNotNull(); + verify(enrollmentTokenService).recordConsumer(t.getId(), existing.getId()); + verifyNoInteractions(boardConfigRepository); + verify(sessionRegistry, never()).closeIfPresent(any(), any()); + } + + /** The maintainer re-keys a board (new SD card): the old key's session is closed. */ + @Test + void aTokenForABoardWithAKeyReplacesItAndClosesTheOldSession() { + Device existing = preCreated(new byte[32]); + EnrollmentToken t = token(); + t.setDeviceId(existing.getId()); + when(enrollmentTokenService.consume("tok")).thenReturn(Optional.of(t)); + byte[] key = new byte[32]; + key[0] = 9; + + service.enroll("tok", Base64.getEncoder().encodeToString(key), "host", "RPi4", "0.5.0", "1.2.3.4"); + + assertThat(existing.getPublicKey()).isEqualTo(key); + verify(sessionRegistry).closeIfPresent(eq(existing.getId()), any()); + } + + @Test + void aTokenForARevokedBoardIsInvalid() { + Device existing = preCreated(null); + existing.setRevokedAt(java.time.Instant.now()); + EnrollmentToken t = token(); + t.setDeviceId(existing.getId()); + when(enrollmentTokenService.consume("tok")).thenReturn(Optional.of(t)); + + assertThat(service.enroll("tok", validKeyB64, "host", "RPi4", "0.5.0", "1.2.3.4")) + .isInstanceOf(DeviceEnrollmentService.Outcome.InvalidToken.class); + assertThat(existing.getPublicKey()).isNull(); + } } diff --git a/src/test/java/com/ibrasoft/lensbridge/service/board/offline/AgentPackageRules.java b/src/test/java/com/ibrasoft/lensbridge/service/board/offline/AgentPackageRules.java new file mode 100644 index 0000000..cb60423 --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/service/board/offline/AgentPackageRules.java @@ -0,0 +1,125 @@ +package com.ibrasoft.lensbridge.service.board.offline; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * The checks the board's agent applies to every package before it looks at its type + * ({@code agent/internal/mbu}: {@code reader.go} open/classify/VerifySignature and + * {@code manifest.go} ParseManifest), written out independently of the code under test, so a + * content package and a provision package can be held to the same rules. + */ +final class AgentPackageRules { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final Pattern SEGMENT = Pattern.compile("^[A-Za-z0-9_][A-Za-z0-9._-]*$"); + private static final Pattern SHA256 = Pattern.compile("^[0-9a-f]{64}$"); + private static final Pattern UUID_LIKE = Pattern.compile( + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); + private static final Pattern RFC3339_SECONDS_UTC = Pattern.compile("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"); + + /** A package the agent accepted: its zip entries and its parsed manifest. */ + record Verified(Map entries, JsonNode manifest, String signedBy) {} + + private AgentPackageRules() {} + + static Map unzip(byte[] zip) throws Exception { + Map entries = new LinkedHashMap<>(); + try (ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(zip))) { + ZipEntry entry; + while ((entry = in.getNextEntry()) != null) { + assertThat(entries).as("duplicate entry %s", entry.getName()).doesNotContainKey(entry.getName()); + entries.put(entry.getName(), in.readAllBytes()); + } + } + return entries; + } + + static byte[] bytesOf(OfflineBundle bundle) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + bundle.writeTo(out); + return out.toByteArray(); + } + + /** + * @param contentKey raw 32-byte public content key the board has pinned + */ + static Verified verify(byte[] zip, byte[] contentKey) throws Exception { + Map entries = unzip(zip); + for (String name : entries.keySet()) { + assertThat(name.length()).isBetween(1, 200); + String[] segments = name.split("/", -1); + assertThat(segments.length).isLessThanOrEqualTo(8); + for (String s : segments) assertThat(s).matches(SEGMENT); + } + + byte[] rawManifest = entries.get("mbu.json"); + byte[] rawSig = entries.get("mbu.sig"); + assertThat(rawManifest).as("mbu.json").isNotNull(); + assertThat(rawSig).as("mbu.sig (unsigned packages are refused)").isNotNull(); + + // Signature first, over the exact stored manifest bytes. + String keyId = ContentSigningService.keyId(contentKey); + byte[] message = ("musallahboard-mbu-v2\n").getBytes(StandardCharsets.US_ASCII); + byte[] signed = new byte[message.length + rawManifest.length]; + System.arraycopy(message, 0, signed, 0, message.length); + System.arraycopy(rawManifest, 0, signed, message.length, rawManifest.length); + String signedBy = null; + for (JsonNode s : MAPPER.readTree(rawSig).get("signatures")) { + if (!keyId.equals(s.get("keyId").asText())) continue; // unknown keys are ignored + if (ContentSigningServiceTest.jdkVerify(contentKey, signed, Base64.getDecoder().decode(s.get("sig").asText()))) { + signedBy = keyId; + } + } + assertThat(signedBy).as("a signature by the pinned content key verifies").isNotNull(); + + JsonNode m = MAPPER.readTree(rawManifest); + assertThat(m.get("format").asText()).isEqualTo("mbu"); + assertThat(m.get("formatVersion").isInt()).isTrue(); + assertThat(m.get("formatVersion").asInt()).isEqualTo(2); + assertThat(m.get("createdAt").asText()).matches(RFC3339_SECONDS_UTC); + Instant.parse(m.get("createdAt").asText()); + assertThat(m.get("sequence").isIntegralNumber()).isTrue(); + assertThat(m.get("sequence").asLong()).isPositive(); + assertThat(m.get("deviceId").asText()).matches(UUID_LIKE); + + Map listed = new LinkedHashMap<>(); + for (JsonNode f : m.get("files")) { + String path = f.get("path").asText(); + assertThat(path).isNotIn("mbu.json", "mbu.sig"); + assertThat(f.get("sha256").asText()).matches(SHA256); + assertThat(f.get("bytes").asLong()).isNotNegative(); + assertThat(listed.put(path, f)).as("listed twice: %s", path).isNull(); + } + for (Map.Entry e : entries.entrySet()) { + if (e.getKey().equals("mbu.json") || e.getKey().equals("mbu.sig")) continue; + JsonNode f = listed.get(e.getKey()); + assertThat(f).as("%s is in the zip but not in the manifest", e.getKey()).isNotNull(); + assertThat(f.get("bytes").asLong()).isEqualTo(e.getValue().length); + assertThat(f.get("sha256").asText()).isEqualTo(sha256(e.getValue())); + } + for (String path : listed.keySet()) { + assertThat(entries).as("%s is listed but missing", path).containsKey(path); + } + return new Verified(entries, m, signedBy); + } + + static String sha256(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } +} diff --git a/src/test/java/com/ibrasoft/lensbridge/service/board/offline/OfflineBundleServiceTest.java b/src/test/java/com/ibrasoft/lensbridge/service/board/offline/OfflineBundleServiceTest.java index 6a15ee7..407668e 100644 --- a/src/test/java/com/ibrasoft/lensbridge/service/board/offline/OfflineBundleServiceTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/service/board/offline/OfflineBundleServiceTest.java @@ -591,15 +591,16 @@ void anUnfetchableImageFailsTheWholeExportWith502NamingThePoster() throws Except // ==================== Validation ==================== + /** Up to three months between USB visits; the agent's mbu.MaxContentDays is the same 92. */ @Test - void daysOutsideOneToThirtyOneIsA400() { - for (int days : new int[]{0, -1, 32}) { + void daysOutsideOneToNinetyTwoIsA400() { + for (int days : new int[]{0, -1, 93}) { assertThatThrownBy(() -> service().build(DEVICE_ID, days)) .isInstanceOfSatisfying(ApiResponseException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST)); } - assertThat(service().build(DEVICE_ID, 31).entries()) - .filteredOn(e -> e.name().startsWith("payloads/")).hasSize(31); + assertThat(service().build(DEVICE_ID, 92).entries()) + .filteredOn(e -> e.name().startsWith("payloads/")).hasSize(92); } @Test diff --git a/src/test/java/com/ibrasoft/lensbridge/service/board/offline/ReleaseChannelCacheTest.java b/src/test/java/com/ibrasoft/lensbridge/service/board/offline/ReleaseChannelCacheTest.java new file mode 100644 index 0000000..b184909 --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/service/board/offline/ReleaseChannelCacheTest.java @@ -0,0 +1,159 @@ +package com.ibrasoft.lensbridge.service.board.offline; + +import com.sun.net.httpserver.HttpServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.assertj.core.api.Assertions.assertThat; + +/** The release channels as GitHub serves them, from a local HTTP server. */ +class ReleaseChannelCacheTest { + + private static final byte[] PACKAGE = "pretend this is a signed app .mbu".getBytes(StandardCharsets.UTF_8); + + private HttpServer server; + private String base; + private volatile String channelJson; + private volatile boolean up = true; + private final AtomicInteger packageDownloads = new AtomicInteger(); + private Instant now = Instant.parse("2026-11-19T12:00:00Z"); + + @BeforeEach + void start() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/channel.json", ex -> respond(ex, channelJson.getBytes(StandardCharsets.UTF_8))); + // Like GitHub's releases/latest/download: a redirect to where the asset really is. + server.createContext("/latest/app.mbu", ex -> { + ex.getResponseHeaders().add("Location", base + "/assets/app.mbu"); + ex.sendResponseHeaders(302, -1); + ex.close(); + }); + server.createContext("/assets/app.mbu", ex -> { + packageDownloads.incrementAndGet(); + respond(ex, PACKAGE); + }); + server.start(); + base = "http://127.0.0.1:" + server.getAddress().getPort(); + channelJson = channel("2.1.0", PACKAGE.length, sha(PACKAGE)); + } + + private void respond(com.sun.net.httpserver.HttpExchange ex, byte[] body) throws IOException { + if (!up) { + ex.sendResponseHeaders(503, -1); + ex.close(); + return; + } + ex.sendResponseHeaders(200, body.length); + try (OutputStream out = ex.getResponseBody()) { + out.write(body); + } + } + + @AfterEach + void stop() { + server.stop(0); + } + + private String channel(String version, long bytes, String sha) { + return "{\"version\":\"" + version + "\",\"url\":\"" + base + "/latest/app.mbu\",\"sha256\":\"" + sha + + "\",\"bytes\":" + bytes + "}"; + } + + private static String sha(byte[] b) { + return MbuPackager.sha256Hex(b); + } + + private ReleaseChannelCache cache(String appChannel) { + Clock clock = new Clock() { + @Override public ZoneOffset getZone() { return ZoneOffset.UTC; } + @Override public Clock withZone(java.time.ZoneId zone) { return this; } + @Override public Instant instant() { return now; } + }; + return new ReleaseChannelCache(appChannel, "", HttpClient.newBuilder() + .followRedirects(HttpClient.Redirect.NORMAL).build(), clock); + } + + @Test + void fetchesThePackageTheChannelNamesAndNamesItByVersion() { + ReleaseChannelCache.Lookup lookup = cache(base + "/channel.json").latest(ReleaseChannelCache.Kind.APP); + + assertThat(lookup.problem()).isNull(); + assertThat(lookup.pkg().version()).isEqualTo("2.1.0"); + assertThat(lookup.pkg().filename()).isEqualTo("musallahboard-app-2.1.0.mbu"); + assertThat(lookup.pkg().bytes()).isEqualTo(PACKAGE); + } + + @Test + void aDownloadThatDoesNotMatchTheChannelIsRefused() { + channelJson = channel("2.1.0", PACKAGE.length, "0".repeat(64)); + ReleaseChannelCache.Lookup lookup = cache(base + "/channel.json").latest(ReleaseChannelCache.Kind.APP); + assertThat(lookup.pkg()).isNull(); + assertThat(lookup.problem()).contains("sha256"); + + channelJson = channel("2.1.0", PACKAGE.length + 1, sha(PACKAGE)); + assertThat(cache(base + "/channel.json").latest(ReleaseChannelCache.Kind.APP).problem()).contains("bytes"); + } + + @Test + void unreachableWithNothingCachedSaysWhy() { + up = false; + ReleaseChannelCache.Lookup lookup = cache(base + "/channel.json").latest(ReleaseChannelCache.Kind.APP); + assertThat(lookup.pkg()).isNull(); + assertThat(lookup.problem()).contains("board app").contains("HTTP 503"); + } + + @Test + void theLastGoodPackageIsServedWhileGitHubIsDown() { + ReleaseChannelCache cache = cache(base + "/channel.json"); + cache.latest(ReleaseChannelCache.Kind.APP); + up = false; + now = now.plus(Duration.ofHours(2)); + + ReleaseChannelCache.Lookup lookup = cache.latest(ReleaseChannelCache.Kind.APP); + assertThat(lookup.pkg().version()).isEqualTo("2.1.0"); + } + + @Test + void checksAtMostEveryHalfHourAndDownloadsOnlyANewVersion() { + ReleaseChannelCache cache = cache(base + "/channel.json"); + cache.latest(ReleaseChannelCache.Kind.APP); + cache.latest(ReleaseChannelCache.Kind.APP); + now = now.plus(Duration.ofMinutes(31)); + cache.latest(ReleaseChannelCache.Kind.APP); + assertThat(packageDownloads.get()).as("same version: not downloaded again").isEqualTo(1); + + byte[] next = "2.2.0 package".getBytes(StandardCharsets.UTF_8); + server.removeContext("/assets/app.mbu"); + server.createContext("/assets/app.mbu", ex -> respond(ex, next)); + channelJson = channel("2.2.0", next.length, sha(next)); + now = now.plus(Duration.ofMinutes(31)); + assertThat(cache.latest(ReleaseChannelCache.Kind.APP).pkg().filename()).isEqualTo("musallahboard-app-2.2.0.mbu"); + } + + @Test + void aChannelSetToEmptyIsOff() { + ReleaseChannelCache.Lookup lookup = cache("").latest(ReleaseChannelCache.Kind.AGENT); + assertThat(lookup.pkg()).isNull(); + assertThat(lookup.problem()).contains("turned off"); + } + + @Test + void theDefaultsAreTheAgentsChannels() { + assertThat(ReleaseChannelCache.DEFAULT_APP_CHANNEL) + .isEqualTo("https://github.com/LensBridge/MusallahBoard/releases/latest/download/app-channel.json"); + assertThat(ReleaseChannelCache.DEFAULT_AGENT_CHANNEL) + .isEqualTo("https://github.com/LensBridge/agent/releases/latest/download/agent-channel-arm64.json"); + } +} diff --git a/src/test/java/com/ibrasoft/lensbridge/service/board/offline/SetupFileIssuanceTest.java b/src/test/java/com/ibrasoft/lensbridge/service/board/offline/SetupFileIssuanceTest.java new file mode 100644 index 0000000..dea7470 --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/service/board/offline/SetupFileIssuanceTest.java @@ -0,0 +1,280 @@ +package com.ibrasoft.lensbridge.service.board.offline; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.ibrasoft.lensbridge.dto.upload.response.ErrorResponse; +import com.ibrasoft.lensbridge.exception.ApiResponseException; +import com.ibrasoft.lensbridge.model.board.Audience; +import com.ibrasoft.lensbridge.model.board.Device; +import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; +import com.ibrasoft.lensbridge.repository.sql.SqliteDataJpaTest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionTemplate; + +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.List; +import java.util.UUID; +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 static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Setup-file issuance on a real database (SQLite, migrated like production) with real + * commits: what a kit leaves stored when it fails, and what two downloads at once leave. + * Not in a test transaction, so each issuance commits or rolls back on its own as in + * production; the rows are deleted afterwards. + */ +@SqliteDataJpaTest +@Transactional(propagation = Propagation.NOT_SUPPORTED) +class SetupFileIssuanceTest { + + private static final Instant NOW = Instant.parse("2026-11-19T12:00:00.250Z"); + private static final long OLD_SEQUENCE = 1_700_000_000_000L; + private static final String BACKEND = "https://api.example.org"; + + @Autowired + private DeviceRepository repository; + @Autowired + private PlatformTransactionManager transactionManager; + + private final ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() + .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).build(); + private final ContentSigningService signer = new ContentSigningService( + Base64.getEncoder().encodeToString(ContentSigningServiceTest.VECTOR_SEED), ""); + private final byte[] contentKey = Base64.getDecoder().decode(signer.publicKeys().get(0).getPublicKey()); + private final List created = new ArrayList<>(); + + @AfterEach + void deleteDevices() { + repository.deleteAllById(created); + } + + private Device board(String name, byte oldSecret) { + byte[] secret = new byte[32]; + Arrays.fill(secret, oldSecret); + Device device = repository.save(Device.builder().displayName(name).audience(Audience.BOTH) + .provisionSequence(OLD_SEQUENCE).claimSecret(secret).build()); + created.add(device.getId()); + return device; + } + + /** The setup service as wired in production, whose @Transactional the template stands in for. */ + private SetupFileService setupFiles(Clock clock) { + return new SetupFileService(repository, objectMapper, signer, BACKEND, clock, new SecureRandom()); + } + + private OfflineBundle issue(SetupFileService service, UUID deviceId) { + return new TransactionTemplate(transactionManager).execute(s -> service.build(deviceId, true)); + } + + private int advance(UUID id, long now) { + Integer rows = new TransactionTemplate(transactionManager).execute(s -> repository.advanceProvisionSequence(id, now)); + return rows == null ? -1 : rows; + } + + private UsbKitService kit(OfflineBundleService content) { + ReleaseChannelCache releases = mock(ReleaseChannelCache.class); + when(releases.latest(any())).thenReturn(new ReleaseChannelCache.Lookup(null, "offline")); + return new UsbKitService(content, setupFiles(Clock.fixed(NOW, ZoneOffset.UTC)), releases, signer, + transactionManager); + } + + private static OfflineBundle pkg(String marker) { + return new OfflineBundle(marker, List.of(new OfflineBundle.Entry("mbu.json", marker.getBytes(), false))); + } + + private void assertUnchanged(Device before) { + Device now = repository.findById(before.getId()).orElseThrow(); + assertThat(now.getProvisionSequence()).as(before.getDisplayName() + " sequence").isEqualTo(OLD_SEQUENCE); + assertThat(now.getClaimSecret()).as(before.getDisplayName() + " secret").isEqualTo(before.getClaimSecret()); + } + + private record Issued(long sequence, String claimSecret) {} + + private Issued read(OfflineBundle file) throws Exception { + return readBytes(AgentPackageRules.bytesOf(file)); + } + + private Issued readBytes(byte[] file) throws Exception { + AgentPackageRules.Verified pkg = AgentPackageRules.verify(file, contentKey); + var json = new ObjectMapper().readTree(pkg.entries().get(SetupFileService.PROVISION_ENTRY)); + return new Issued(json.get("sequence").asLong(), json.get("claimSecret").asText()); + } + + private static String encoded(byte[] secret) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(secret); + } + + @Test + void aKitWhoseLastBoardsContentFailsChangesNoBoard() { + List boards = List.of(board("A", (byte) 1), board("B", (byte) 2), board("C", (byte) 3)); + OfflineBundleService content = mock(OfflineBundleService.class); + when(content.build(any(), anyInt())).thenReturn(pkg("c")); + when(content.build(eq(boards.get(2).getId()), anyInt())).thenThrow( + new ApiResponseException(HttpStatus.BAD_GATEWAY, ErrorResponse.of("poster"))); + + assertThatThrownBy(() -> kit(content).build(boards, "kit.zip", 14, true, true)) + .isInstanceOf(ApiResponseException.class); + + boards.forEach(this::assertUnchanged); + } + + /** The last board's setup file fails after the others were issued: all of them roll back. */ + @Test + void aKitWhoseLastSetupFileFailsRollsBackEveryBoard() { + List boards = new ArrayList<>(List.of(board("A", (byte) 1), board("B", (byte) 2), board("C", (byte) 3))); + // Setup files are issued in id order; revoke the last one there (after its content was built). + Device last = boards.stream().max(Comparator.comparing(Device::getId)).orElseThrow(); + OfflineBundleService content = mock(OfflineBundleService.class); + when(content.build(any(), anyInt())).thenAnswer(inv -> { + if (inv.getArgument(0).equals(last.getId())) { + Device d = repository.findById(last.getId()).orElseThrow(); + d.setRevokedAt(NOW); + repository.save(d); + } + return pkg("c"); + }); + + assertThatThrownBy(() -> kit(content).build(boards, "kit.zip", 14, true, true)) + .isInstanceOfSatisfying(ApiResponseException.class, + e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.CONFLICT)); + + boards.forEach(this::assertUnchanged); + } + + @Test + void aCompleteKitIssuesEveryBoardANewSequenceAndSecret() throws Exception { + List boards = List.of(board("A", (byte) 1), board("B", (byte) 2)); + OfflineBundleService content = mock(OfflineBundleService.class); + when(content.build(any(), anyInt())).thenReturn(pkg("c")); + + try (UsbKitService.Kit kit = kit(content).build(boards, "kit.zip", 14, true, true)) { + var zip = AgentPackageRules.unzip(java.nio.file.Files.readAllBytes(kit.file())); + for (Device before : boards) { + Device now = repository.findById(before.getId()).orElseThrow(); + byte[] setup = zip.get(UsbKitService.FOLDER + "setup-" + before.getId().toString().substring(0, 8) + ".mbu"); + Issued issued = readBytes(setup); + assertThat(now.getProvisionSequence()).isEqualTo(issued.sequence()).isEqualTo(NOW.toEpochMilli()); + assertThat(encoded(now.getClaimSecret())).isEqualTo(issued.claimSecret()); + } + } + } + + /** + * Downloads racing for one board (a standalone file and a kit, say): each gets its own, + * strictly increasing sequence, and the stored secret is the one in the newest file. The + * clock is frozen, so every file is in the same millisecond and only the row lock keeps + * them apart. + */ + @Test + void concurrentIssuancesForOneBoardAreSerialized() throws Exception { + Device board = board("North", (byte) 9); + SetupFileService service = setupFiles(Clock.fixed(NOW, ZoneOffset.UTC)); + int threads = 4; + CountDownLatch start = new CountDownLatch(1); + ExecutorService pool = Executors.newFixedThreadPool(threads); + try { + List> futures = new ArrayList<>(); + for (int i = 0; i < threads; i++) { + futures.add(pool.submit(() -> { + start.await(); + return read(issue(service, board.getId())); + })); + } + start.countDown(); + List issued = new ArrayList<>(); + for (Future f : futures) issued.add(f.get(30, TimeUnit.SECONDS)); + + List sequences = issued.stream().map(Issued::sequence).sorted().toList(); + assertThat(sequences).doesNotHaveDuplicates() + .containsExactly(NOW.toEpochMilli(), NOW.toEpochMilli() + 1, NOW.toEpochMilli() + 2, + NOW.toEpochMilli() + 3); + Issued newest = issued.stream().max(Comparator.comparingLong(Issued::sequence)).orElseThrow(); + Device stored = repository.findById(board.getId()).orElseThrow(); + assertThat(stored.getProvisionSequence()).isEqualTo(newest.sequence()); + assertThat(encoded(stored.getClaimSecret())).isEqualTo(newest.claimSecret()); + } finally { + pool.shutdownNow(); + } + } + + /** + * One download holds the row (issued, not yet committed) while another starts: the second + * waits for the first to commit and counts from it, rather than reading the old sequence. + */ + @Test + void anIssuanceStartedWhileAnotherIsUncommittedCountsFromIt() throws Exception { + Device board = board("North", (byte) 9); + SetupFileService service = setupFiles(Clock.fixed(NOW, ZoneOffset.UTC)); + CountDownLatch firstIssued = new CountDownLatch(1); + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + Future first = pool.submit(() -> read(new TransactionTemplate(transactionManager).execute(s -> { + OfflineBundle file = service.build(board.getId(), true); + firstIssued.countDown(); + try { + Thread.sleep(500); // still uncommitted while the second one starts + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return file; + }))); + assertThat(firstIssued.await(10, TimeUnit.SECONDS)).isTrue(); + Issued second = read(issue(service, board.getId())); + + assertThat(second.sequence()).isEqualTo(first.get(10, TimeUnit.SECONDS).sequence() + 1); + Device stored = repository.findById(board.getId()).orElseThrow(); + assertThat(stored.getProvisionSequence()).isEqualTo(second.sequence()); + assertThat(encoded(stored.getClaimSecret())).isEqualTo(second.claimSecret()); + } finally { + pool.shutdownNow(); + } + } + + /** The SQL of the sequence: now when greater, else one more; a revoked or unknown board is left alone. */ + @Test + void theSequenceUpdateCountsOnFromTheLastOrTheClock() { + Device fresh = repository.save(Device.builder().displayName("Fresh").audience(Audience.BOTH).build()); + created.add(fresh.getId()); + Device revoked = board("Gone", (byte) 1); + revoked.setRevokedAt(NOW); + repository.save(revoked); + + assertThat(advance(fresh.getId(), 5000)).isEqualTo(1); + assertThat(repository.findById(fresh.getId()).orElseThrow().getProvisionSequence()).isEqualTo(5000); + advance(fresh.getId(), 5000); + assertThat(repository.findById(fresh.getId()).orElseThrow().getProvisionSequence()).isEqualTo(5001); + advance(fresh.getId(), 10); // clock went back + assertThat(repository.findById(fresh.getId()).orElseThrow().getProvisionSequence()).isEqualTo(5002); + advance(fresh.getId(), 9000); + assertThat(repository.findById(fresh.getId()).orElseThrow().getProvisionSequence()).isEqualTo(9000); + + assertThat(advance(revoked.getId(), 9000)).isZero(); + assertThat(repository.findById(revoked.getId()).orElseThrow().getProvisionSequence()).isEqualTo(OLD_SEQUENCE); + assertThat(advance(UUID.randomUUID(), 9000)).isZero(); + } +} diff --git a/src/test/java/com/ibrasoft/lensbridge/service/board/offline/SetupFileServiceTest.java b/src/test/java/com/ibrasoft/lensbridge/service/board/offline/SetupFileServiceTest.java new file mode 100644 index 0000000..9861653 --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/service/board/offline/SetupFileServiceTest.java @@ -0,0 +1,272 @@ +package com.ibrasoft.lensbridge.service.board.offline; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.ibrasoft.lensbridge.exception.ApiResponseException; +import com.ibrasoft.lensbridge.model.board.Audience; +import com.ibrasoft.lensbridge.model.board.Device; +import com.ibrasoft.lensbridge.model.board.Location; +import com.ibrasoft.lensbridge.model.board.embedded.DeviceConfig; +import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; +import com.ibrasoft.lensbridge.service.R2StorageService; +import com.ibrasoft.lensbridge.service.board.BoardPayloadAssembler; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * The setup file (contract C1) with the real signer and packager. The device is the one of + * the claim test vector (see DeviceClaimServiceTest): id ...0001, claim secret 32 x 0x01. + */ +class SetupFileServiceTest { + + static final UUID DEVICE_ID = UUID.fromString("00000000-0000-0000-0000-000000000001"); + private static final Instant NOW = Instant.parse("2026-11-19T12:00:00.250Z"); + private static final String BACKEND = "https://api.example.org"; + + private final ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() + .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).build(); + private final ContentSigningService signer = new ContentSigningService( + Base64.getEncoder().encodeToString(ContentSigningServiceTest.VECTOR_SEED), ""); + private final byte[] contentKey = Base64.getDecoder().decode(signer.publicKeys().get(0).getPublicKey()); + private final DeviceRepository deviceRepository = mock(DeviceRepository.class); + private Device device; + + /** Fills every "random" byte with 0x01, so the claim secret is the test vector's. */ + private static final class OnesRandom extends SecureRandom { + @Override + public void nextBytes(byte[] bytes) { + Arrays.fill(bytes, (byte) 0x01); + } + } + + @BeforeEach + void setUp() { + device = Device.builder().id(DEVICE_ID).displayName("North Musallah").audience(Audience.BOTH).build(); + device.setConfig(DeviceConfig.builder().location(Location.builder().timezone("America/Toronto").build()).build()); + when(deviceRepository.findById(DEVICE_ID)).thenReturn(Optional.of(device)); + when(deviceRepository.existsById(DEVICE_ID)).thenReturn(true); + // What the two conditional updates do in SQL (checked on a real database in + // SetupFileIssuanceTest), applied to the one device. + when(deviceRepository.advanceProvisionSequence(eq(DEVICE_ID), anyLong())).thenAnswer(inv -> { + if (device.getRevokedAt() != null) return 0; + long previous = device.getProvisionSequence() == null ? 0 : device.getProvisionSequence(); + device.setProvisionSequence(Math.max(previous + 1, inv.getArgument(1))); + return 1; + }); + when(deviceRepository.replaceClaimSecret(eq(DEVICE_ID), any())).thenAnswer(inv -> { + device.setClaimSecret(inv.getArgument(1)); + return 1; + }); + } + + private SetupFileService service(Instant now, String backendUrl, SecureRandom random) { + return new SetupFileService(deviceRepository, objectMapper, signer, backendUrl, + Clock.fixed(now, ZoneOffset.UTC), random); + } + + private SetupFileService service() { + return service(NOW, BACKEND, new OnesRandom()); + } + + private static JsonNode provisionJson(AgentPackageRules.Verified pkg) throws Exception { + return new ObjectMapper().readTree(pkg.entries().get(SetupFileService.PROVISION_ENTRY)); + } + + @Test + void anOfflineSetupFilePassesTheAgentsPackageChecks() throws Exception { + OfflineBundle file = service().build(DEVICE_ID, false); + AgentPackageRules.Verified pkg = AgentPackageRules.verify(AgentPackageRules.bytesOf(file), contentKey); + + assertThat(file.filename()).isEqualTo("musallahboard-setup-00000000.mbu"); + JsonNode m = pkg.manifest(); + assertThat(m.get("type").asText()).isEqualTo("provision"); + assertThat(m.get("deviceId").asText()).isEqualTo(DEVICE_ID.toString()); + assertThat(m.get("createdAt").asText()).isEqualTo("2026-11-19T12:00:00Z"); + assertThat(m.get("sequence").asLong()).isEqualTo(NOW.toEpochMilli()); + assertThat(m.get("version").isNull()).isTrue(); + assertThat(m.has("content")).isFalse(); + assertThat(m.get("files")).hasSize(1); + assertThat(m.get("files").get(0).get("path").asText()).isEqualTo("provision.json"); + assertThat(pkg.entries().keySet()).containsExactly("mbu.json", "mbu.sig", "provision.json"); + + JsonNode p = provisionJson(pkg); + assertThat(p.fieldNames()).toIterable() + .containsExactly("format", "deviceId", "displayName", "sequence", "issuedAt"); + assertThat(p.get("format").asInt()).isEqualTo(1); + assertThat(p.get("deviceId").asText()).isEqualTo(DEVICE_ID.toString()); + assertThat(p.get("displayName").asText()).isEqualTo("North Musallah"); + assertThat(p.get("sequence").asLong()).isEqualTo(m.get("sequence").asLong()); + assertThat(p.get("issuedAt").asText()).isEqualTo(m.get("createdAt").asText()); + // An offline file leaves any stored claim secret alone. + assertThat(device.getClaimSecret()).isNull(); + } + + @Test + void anOnlineSetupFileCarriesTheBackendAndANewClaimSecret() throws Exception { + byte[] old = new byte[32]; + device.setClaimSecret(old); + + AgentPackageRules.Verified pkg = AgentPackageRules.verify( + AgentPackageRules.bytesOf(service().build(DEVICE_ID, true)), contentKey); + + JsonNode p = provisionJson(pkg); + assertThat(p.fieldNames()).toIterable().containsExactly( + "format", "deviceId", "displayName", "sequence", "issuedAt", "backendUrl", "claimSecret"); + assertThat(p.get("backendUrl").asText()).isEqualTo(BACKEND); + byte[] ones = new byte[32]; + Arrays.fill(ones, (byte) 0x01); + // base64url without padding: 43 characters for 32 bytes. + assertThat(p.get("claimSecret").asText()) + .isEqualTo("AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE") + .hasSize(43); + assertThat(Base64.getUrlDecoder().decode(p.get("claimSecret").asText())).isEqualTo(ones); + assertThat(device.getClaimSecret()).as("stored for the claim, replacing the old one").isEqualTo(ones); + } + + @Test + void everyOnlineFileRotatesTheSecret() throws Exception { + SetupFileService real = service(NOW, BACKEND, new SecureRandom()); + String first = provisionJson(AgentPackageRules.verify(AgentPackageRules.bytesOf(real.build(DEVICE_ID, true)), contentKey)) + .get("claimSecret").asText(); + String second = provisionJson(AgentPackageRules.verify(AgentPackageRules.bytesOf(real.build(DEVICE_ID, true)), contentKey)) + .get("claimSecret").asText(); + assertThat(second).isNotEqualTo(first); + assertThat(Base64.getUrlEncoder().withoutPadding().encodeToString(device.getClaimSecret())).isEqualTo(second); + } + + /** A board only takes a strictly newer file, so a second download must be newer even within one millisecond. */ + @Test + void theSequenceAlwaysGoesUp() throws Exception { + long first = AgentPackageRules.verify(AgentPackageRules.bytesOf(service().build(DEVICE_ID, false)), contentKey) + .manifest().get("sequence").asLong(); + long sameMilli = AgentPackageRules.verify(AgentPackageRules.bytesOf(service().build(DEVICE_ID, false)), contentKey) + .manifest().get("sequence").asLong(); + long clockWentBack = AgentPackageRules.verify(AgentPackageRules.bytesOf( + service(NOW.minusSeconds(3600), BACKEND, new OnesRandom()).build(DEVICE_ID, false)), contentKey) + .manifest().get("sequence").asLong(); + + assertThat(sameMilli).isGreaterThan(first); + assertThat(clockWentBack).isGreaterThan(sameMilli); + assertThat(device.getProvisionSequence()).isEqualTo(clockWentBack); + } + + /** + * Contract C1: the provision manifest mirrors a content manifest's shape exactly (same + * fields, same order, same signature format and key), minus the content block. Both are + * held to the agent's common package rules. + */ + @Test + void theProvisionManifestHasTheContentManifestsShape() throws Exception { + BoardPayloadAssembler assembler = new BoardPayloadAssembler(List.of(), ZoneId.of("UTC")); + OfflineBundleService content = new OfflineBundleService(assembler, deviceRepository, mock(R2StorageService.class), + objectMapper, signer, Clock.fixed(NOW, ZoneOffset.UTC)); + JsonNode contentManifest = AgentPackageRules.verify( + AgentPackageRules.bytesOf(content.build(DEVICE_ID, 2)), contentKey).manifest(); + JsonNode provisionManifest = AgentPackageRules.verify( + AgentPackageRules.bytesOf(service().build(DEVICE_ID, false)), contentKey).manifest(); + + assertThat(contentManifest.fieldNames()).toIterable().containsExactly( + "format", "formatVersion", "type", "createdAt", "sequence", "deviceId", "version", "files", "content"); + assertThat(provisionManifest.fieldNames()).toIterable().containsExactly( + "format", "formatVersion", "type", "createdAt", "sequence", "deviceId", "version", "files"); + for (String field : List.of("format", "formatVersion", "createdAt", "deviceId", "version")) { + assertThat(provisionManifest.get(field)).as(field).isEqualTo(contentManifest.get(field)); + } + assertThat(provisionManifest.get("files").get(0).fieldNames()).toIterable() + .containsExactly("path", "sha256", "bytes"); + } + + @Test + void tamperingWithProvisionJsonIsCaught() throws Exception { + AgentPackageRules.Verified pkg = AgentPackageRules.verify( + AgentPackageRules.bytesOf(service().build(DEVICE_ID, false)), contentKey); + String listed = pkg.manifest().get("files").get(0).get("sha256").asText(); + byte[] edited = new String(pkg.entries().get("provision.json")).replace("North", "South").getBytes(); + assertThat(AgentPackageRules.sha256(edited)).isNotEqualTo(listed); + } + + @Test + void unknownRevokedAndUnsignedAreRefusedBeforeAnythingIsStored() { + UUID missing = UUID.randomUUID(); + assertStatus(() -> service().build(missing, false), HttpStatus.NOT_FOUND); + + device.setRevokedAt(NOW); + assertStatus(() -> service().build(DEVICE_ID, true), HttpStatus.CONFLICT); + device.setRevokedAt(null); + + SetupFileService unsigned = new SetupFileService(deviceRepository, objectMapper, + new ContentSigningService("", ""), BACKEND, Clock.fixed(NOW, ZoneOffset.UTC), new OnesRandom()); + assertStatus(() -> unsigned.build(DEVICE_ID, true), HttpStatus.SERVICE_UNAVAILABLE); + + assertStatus(() -> service(NOW, null, new OnesRandom()).build(DEVICE_ID, true), HttpStatus.SERVICE_UNAVAILABLE); + verify(deviceRepository, never()).replaceClaimSecret(any(), any()); + assertThat(device.getClaimSecret()).isNull(); + assertThat(device.getProvisionSequence()).isNull(); + } + + @Test + void anOfflineFileNeedsNoBackendUrl() throws Exception { + AgentPackageRules.verify(AgentPackageRules.bytesOf(service(NOW, null, new OnesRandom()).build(DEVICE_ID, false)), + contentKey); + } + + @Test + void theBackendUrlIsConfiguredOrTheAgentSocketsOrigin() { + assertThat(SetupFileService.resolveBackendUrl("https://api.example.org/", "wss://other/api/agent/ws")) + .isEqualTo("https://api.example.org"); + assertThat(SetupFileService.resolveBackendUrl("", "wss://api.example.org/api/agent/ws")) + .isEqualTo("https://api.example.org"); + assertThat(SetupFileService.resolveBackendUrl(null, "ws://localhost:8080/api/agent/ws")) + .isEqualTo("http://localhost:8080"); + assertThat(SetupFileService.resolveBackendUrl("", "")).isNull(); + assertThat(SetupFileService.resolveBackendUrl("", "not a url")).isNull(); + } + + /** + * Writes one real online setup file for the agent's tests to read: device ...0001, claim + * secret 32 x 0x01, signed by the content key of seed 0x01..0x20 (public key + * {@code ContentSigningServiceTest}'s vector). target/sample-provision.mbu. + */ + @Test + void writesASampleForTheAgent() throws Exception { + byte[] zip = AgentPackageRules.bytesOf(service().build(DEVICE_ID, true)); + AgentPackageRules.verify(zip, contentKey); + Path out = Path.of("target", "sample-provision.mbu"); + Files.createDirectories(out.getParent()); + Files.write(out, zip); + System.out.println("sample provision package: " + out.toAbsolutePath() + + " contentPublicKey=" + signer.publicKeys().get(0).getPublicKey() + + " keyId=" + signer.currentKeyId()); + } + + private static void assertStatus(Runnable call, HttpStatus status) { + assertThatThrownBy(call::run).isInstanceOfSatisfying(ApiResponseException.class, + e -> assertThat(e.getStatus()).isEqualTo(status)); + } +} diff --git a/src/test/java/com/ibrasoft/lensbridge/service/board/offline/UsbKitServiceTest.java b/src/test/java/com/ibrasoft/lensbridge/service/board/offline/UsbKitServiceTest.java new file mode 100644 index 0000000..a48d243 --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/service/board/offline/UsbKitServiceTest.java @@ -0,0 +1,203 @@ +package com.ibrasoft.lensbridge.service.board.offline; + +import com.ibrasoft.lensbridge.exception.ApiResponseException; +import com.ibrasoft.lensbridge.model.board.Audience; +import com.ibrasoft.lensbridge.model.board.Device; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.http.HttpStatus; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.SimpleTransactionStatus; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class UsbKitServiceTest { + + private static final Device A = device("aaaaaaaa-0000-4000-8000-000000000001", "North"); + private static final Device B = device("bbbbbbbb-0000-4000-8000-000000000002", "South"); + + private final OfflineBundleService content = mock(OfflineBundleService.class); + private final SetupFileService setup = mock(SetupFileService.class); + private final ReleaseChannelCache releases = mock(ReleaseChannelCache.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final UsbKitService service = new UsbKitService(content, setup, releases, + new ContentSigningService(Base64.getEncoder().encodeToString(ContentSigningServiceTest.VECTOR_SEED), ""), + transactions); + + @BeforeEach + void setUp() { + when(transactions.getTransaction(any())).thenReturn(new SimpleTransactionStatus()); + } + + private static Device device(String id, String name) { + return Device.builder().id(UUID.fromString(id)).displayName(name).audience(Audience.BOTH).build(); + } + + private static OfflineBundle pkg(String marker) { + return new OfflineBundle(marker, List.of(new OfflineBundle.Entry("mbu.json", + marker.getBytes(StandardCharsets.UTF_8), false))); + } + + private void releasesAvailable() { + when(releases.latest(ReleaseChannelCache.Kind.APP)).thenReturn(new ReleaseChannelCache.Lookup( + new ReleaseChannelCache.ReleasePackage(ReleaseChannelCache.Kind.APP, "2.1.0", + "musallahboard-app-2.1.0.mbu", new byte[]{1}), null)); + when(releases.latest(ReleaseChannelCache.Kind.AGENT)).thenReturn(new ReleaseChannelCache.Lookup( + new ReleaseChannelCache.ReleasePackage(ReleaseChannelCache.Kind.AGENT, "0.5.0", + "musallahboard-agent-0.5.0-arm64.mbu", new byte[]{2}), null)); + } + + private Map entries(UsbKitService.Kit kit) throws Exception { + try (kit) { + return AgentPackageRules.unzip(Files.readAllBytes(kit.file())); + } + } + + @Test + void aKitIsOneMusallahBoardFolderWithEveryBoardsFilesAndTheLatestSoftware() throws Exception { + when(content.build(any(), anyInt())).thenAnswer(inv -> pkg("content " + inv.getArgument(0))); + when(setup.build(any(), anyBoolean())).thenAnswer(inv -> pkg("setup " + inv.getArgument(0))); + releasesAvailable(); + + UsbKitService.Kit kit = service.build(List.of(A, B), "kit.zip", 31, true, false); + assertThat(kit.omitted()).isEmpty(); + Map zip = entries(kit); + + assertThat(zip.keySet()).containsExactly( + "MusallahBoard/", + "MusallahBoard/content-aaaaaaaa.mbu", "MusallahBoard/content-bbbbbbbb.mbu", + "MusallahBoard/musallahboard-app-2.1.0.mbu", "MusallahBoard/musallahboard-agent-0.5.0-arm64.mbu", + "MusallahBoard/setup-aaaaaaaa.mbu", "MusallahBoard/setup-bbbbbbbb.mbu"); + assertThat(AgentPackageRules.unzip(zip.get("MusallahBoard/content-bbbbbbbb.mbu")).get("mbu.json")) + .asString().isEqualTo("content " + B.getId()); + verify(content).build(A.getId(), 31); + verify(setup).build(A.getId(), false); + assertThat(Files.exists(kit.file())).as("deleted once sent").isFalse(); + } + + @Test + void setupFilesOnlyWhenAskedFor() throws Exception { + when(content.build(any(), anyInt())).thenReturn(pkg("c")); + releasesAvailable(); + + Map zip = entries(service.build(List.of(A), "kit.zip", 14, false, true)); + + assertThat(zip.keySet()).noneMatch(n -> n.contains("setup-")); + verify(setup, never()).build(any(), anyBoolean()); + verify(transactions, never()).getTransaction(any()); + } + + /** No GitHub: the kit is still made, says what it lacks, and the boards get their content. */ + @Test + void unreachableReleasesAreLeftOutWithANotice() throws Exception { + when(content.build(any(), anyInt())).thenReturn(pkg("c")); + when(releases.latest(any())).thenReturn(new ReleaseChannelCache.Lookup(null, "could not fetch: timeout")); + + UsbKitService.Kit kit = service.build(List.of(A), "kit.zip", 14, false, false); + + assertThat(kit.omitted()).containsExactly("board app: could not fetch: timeout", "agent: could not fetch: timeout"); + assertThat(entries(kit).keySet()).containsExactly("MusallahBoard/", "MusallahBoard/content-aaaaaaaa.mbu"); + } + + /** + * Everything that can be slow or fail (posters, GitHub) comes before the setup files, + * which are all issued in one transaction that commits only after the zip is complete. + */ + @Test + void setupFilesAreIssuedLastInOneTransactionCommittedAfterTheZipIsWritten() throws Exception { + when(content.build(any(), anyInt())).thenReturn(pkg("c")); + when(setup.build(any(), anyBoolean())).thenReturn(pkg("s")); + releasesAvailable(); + + entries(service.build(List.of(B, A), "kit.zip", 14, true, true)); + + InOrder order = inOrder(content, releases, transactions, setup); + order.verify(content).build(B.getId(), 14); + order.verify(content).build(A.getId(), 14); + order.verify(releases).latest(ReleaseChannelCache.Kind.AGENT); + order.verify(transactions).getTransaction(any()); + // Rows are locked in id order whatever the kit's order, so two kits cannot deadlock. + order.verify(setup).build(A.getId(), true); + order.verify(setup).build(B.getId(), true); + order.verify(transactions).commit(any()); + verify(transactions, times(1)).getTransaction(any()); + verify(transactions, never()).rollback(any()); + } + + /** One board's setup file fails: the transaction (every board's rotation) rolls back, no kit is left. */ + @Test + void aSetupFileFailureRollsBackEveryBoardsAndLeavesNoKit() throws Exception { + when(content.build(any(), anyInt())).thenReturn(pkg("c")); + when(setup.build(A.getId(), true)).thenReturn(pkg("s")); + when(setup.build(B.getId(), true)).thenThrow(new ApiResponseException(HttpStatus.CONFLICT, + com.ibrasoft.lensbridge.dto.upload.response.ErrorResponse.of("Device is revoked"))); + releasesAvailable(); + long before = countKits(); + + assertThatThrownBy(() -> service.build(List.of(A, B), "kit.zip", 14, true, true)) + .isInstanceOf(ApiResponseException.class); + + verify(transactions).rollback(any()); + verify(transactions, never()).commit(any()); + assertThat(countKits()).isEqualTo(before); + } + + /** A content failure for the last board comes before any setup file is issued. */ + @Test + void aContentFailureIssuesNoSetupFile() { + when(content.build(A.getId(), 14)).thenReturn(pkg("c")); + when(content.build(B.getId(), 14)).thenThrow(new ApiResponseException(HttpStatus.BAD_GATEWAY, + com.ibrasoft.lensbridge.dto.upload.response.ErrorResponse.of("poster"))); + + assertThatThrownBy(() -> service.build(List.of(A, B), "kit.zip", 14, true, true)) + .isInstanceOf(ApiResponseException.class); + + verify(setup, never()).build(any(), anyBoolean()); + verify(transactions, never()).getTransaction(any()); + } + + @Test + void badDaysAndNoBoardsAreRefused() { + assertThatThrownBy(() -> service.build(List.of(A), "kit.zip", 93, false, false)) + .isInstanceOfSatisfying(ApiResponseException.class, + e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST)); + assertThatThrownBy(() -> service.build(List.of(), "kit.zip", 14, false, false)) + .isInstanceOfSatisfying(ApiResponseException.class, + e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + @Test + void aFailureLeavesNoTempFileBehind() throws Exception { + when(content.build(any(), anyInt())).thenThrow(new ApiResponseException(HttpStatus.BAD_GATEWAY, + com.ibrasoft.lensbridge.dto.upload.response.ErrorResponse.of("poster"))); + long before = countKits(); + + assertThatThrownBy(() -> service.build(List.of(A), "kit.zip", 14, false, false)) + .isInstanceOf(ApiResponseException.class); + assertThat(countKits()).isEqualTo(before); + } + + private static long countKits() throws Exception { + try (var files = Files.list(java.nio.file.Path.of(System.getProperty("java.io.tmpdir")))) { + return files.filter(p -> p.getFileName().toString().startsWith("musallahboard-usb-kit-")).count(); + } + } +} diff --git a/tools/openapi-gen.properties b/tools/openapi-gen.properties index 95fe6f2..03ea9cb 100644 --- a/tools/openapi-gen.properties +++ b/tools/openapi-gen.properties @@ -13,7 +13,6 @@ spring.jpa.open-in-view=false spring.flyway.locations=classpath:db/migration/sqlite frontend.baseurl=http://localhost:5173 -musallahboard.baseurl=http://localhost:3000 musallahboard.agent.websocketUrl=ws://localhost:8080/api/agent/ws cloudflare.r2.endpoint=https://example.invalid