From c18275b86b4124d63985dbbf76687fec38567143 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:11:25 +0000 Subject: [PATCH 1/7] Authenticate the board refresh stream with the device signature /api/refresh-musallahboard accepted any socket that named a known, unrevoked ?deviceId=, and a newcomer closed the existing session for that device. Device ids are not secret, so anyone could keep evicting a board from its push channel and watch when pushes arrive. BoardStreamHandshakeInterceptor now checks the upgrade with the existing X-MB-* device signature (DeviceRequestAuthenticator: GET, the path, an empty body): - a present signature is always verified; a bad or partial one is 401; - the device comes from the signature, and a ?deviceId= naming another device is 400 (the query is not signed); - each signed upgrade must carry a newer timestamp than the last one accepted for that device, because the scheme accepts replays inside its five-minute window and here a replay would displace the board; - an unsigned upgrade is 401 when musallahboard.board-stream.require-signature is true. While it is false (the default, for boards still on an older agent) it is accepted and logged, and the handler never lets it displace a signed session for the same device (closed with 4004 signed_session_active). BoardStreamHandler gains disconnect(deviceId) for revokes, and its javadoc now describes the agent it serves rather than kiosk pages and a ten-minute poll. BoardStreamHandshakeInterceptorTest verifies the agent's golden vector (fixed key and time) with the real authenticator, so the two sides agree on the signed message. --- .../lensbridge/config/WebSocketConfig.java | 8 +- .../handler/BoardStreamHandler.java | 103 +++++-- .../BoardStreamHandshakeInterceptor.java | 154 +++++++++++ .../http/DeviceRequestAuthenticator.java | 9 +- .../resources/application.properties.example | 6 + .../config/WebSocketConfigTest.java | 22 +- .../handler/BoardStreamHandlerTest.java | 123 ++++++++- .../BoardStreamHandshakeInterceptorTest.java | 258 ++++++++++++++++++ 8 files changed, 649 insertions(+), 34 deletions(-) create mode 100644 src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptor.java create mode 100644 src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptorTest.java diff --git a/src/main/java/com/ibrasoft/lensbridge/config/WebSocketConfig.java b/src/main/java/com/ibrasoft/lensbridge/config/WebSocketConfig.java index a2469c0..eb08ae9 100644 --- a/src/main/java/com/ibrasoft/lensbridge/config/WebSocketConfig.java +++ b/src/main/java/com/ibrasoft/lensbridge/config/WebSocketConfig.java @@ -10,6 +10,7 @@ import com.ibrasoft.lensbridge.handler.AgentWebSocketHandler; import com.ibrasoft.lensbridge.handler.BoardStreamHandler; +import com.ibrasoft.lensbridge.handler.BoardStreamHandshakeInterceptor; import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration; import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; @@ -18,6 +19,7 @@ public class WebSocketConfig implements WebSocketConfigurer { private final BoardStreamHandler boardStreamHandler; + private final BoardStreamHandshakeInterceptor boardStreamHandshakeInterceptor; private final AgentWebSocketHandler agentWebSocketHandler; @Value("${frontend.baseurl}") @@ -27,15 +29,19 @@ public class WebSocketConfig implements WebSocketConfigurer { String musallahBoardBaseUrl; public WebSocketConfig(BoardStreamHandler boardStreamHandler, + BoardStreamHandshakeInterceptor boardStreamHandshakeInterceptor, AgentWebSocketHandler agentWebSocketHandler) { this.boardStreamHandler = boardStreamHandler; + this.boardStreamHandshakeInterceptor = boardStreamHandshakeInterceptor; this.agentWebSocketHandler = agentWebSocketHandler; } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { - // Path is the deployed kiosk's; boards scope themselves with ?deviceId=. + // Board agents connect here. The upgrade is device-signed (X-MB-* headers), checked by + // the interceptor; older agents only name themselves with ?deviceId=. registry.addHandler(boardStreamHandler, "/api/refresh-musallahboard") + .addInterceptors(boardStreamHandshakeInterceptor) .setAllowedOrigins(frontendBaseUrl, musallahBoardBaseUrl); // Agents authenticate per-frame inside the channel; the WS upgrade itself is open. diff --git a/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandler.java b/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandler.java index 57cfe5a..2a25667 100644 --- a/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandler.java +++ b/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandler.java @@ -14,6 +14,7 @@ import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator; import org.springframework.web.socket.handler.TextWebSocketHandler; +import java.net.URI; import java.time.Instant; import java.util.LinkedHashMap; import java.util.Map; @@ -22,14 +23,22 @@ 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. + * Push channel for board agents: tells a board its content or config changed, so the agent + * syncs content ten seconds later instead of waiting for its 30-minute schedule (agent + * {@code docs/architecture.md}, section 9.1). A missed push only costs that wait. *

+ * Every board on this channel is an enrolled, unrevoked device; there is no anonymous or + * pre-enrollment state here. Who the device is comes from the upgrade request: + *

    + *
  • Signed: {@link BoardStreamHandshakeInterceptor} verified the device's + * {@code X-MB-*} signature and recorded the device it proved.
  • + *
  • Unsigned, from an agent that predates signing, and only while + * {@code musallahboard.board-stream.require-signature} is false: the device named by + * {@code ?deviceId=}. Anyone who knows the id can make that claim, so an unsigned + * connection never displaces a signed one for the same device.
  • + *
+ * Revoking a device closes its connection here ({@link #disconnect(UUID)}), as it does the + * agent's own socket. */ @Component @RequiredArgsConstructor @@ -41,6 +50,8 @@ public class BoardStreamHandler extends TextWebSocketHandler { 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"); + /** An unsigned connection for a device that already holds a signed one. */ + static final CloseStatus CLOSE_SIGNED_SESSION_ACTIVE = new CloseStatus(4004, "signed_session_active"); /** * A push that has been stuck this long means the board has stopped reading; the decorator @@ -59,9 +70,10 @@ public class BoardStreamHandler extends TextWebSocketHandler { 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. + * Live boards keyed by device. One session per device: a reconnecting agent can open its + * replacement before the server notices the old socket is gone, so the newcomer wins + * and the stale one is closed rather than left to accumulate, except that an unsigned + * newcomer never wins over a signed session. *

* Sessions are stored wrapped in a {@link ConcurrentWebSocketSessionDecorator}. Pushes * come from whichever admin request thread changed the content, and the container allows @@ -69,11 +81,17 @@ public class BoardStreamHandler extends TextWebSocketHandler { * failure was being swallowed, so a board silently missed its refresh. The decorator * serialises the writes. */ - private final Map sessions = new ConcurrentHashMap<>(); + private final Map sessions = new ConcurrentHashMap<>(); + + /** A registered connection, and whether its upgrade carried a verified device signature. */ + private record Board(ConcurrentWebSocketSessionDecorator session, boolean signed) { + } @Override public void afterConnectionEstablished(@NonNull WebSocketSession session) { - UUID deviceId = parseDeviceId(session); + UUID signedDevice = (UUID) session.getAttributes().get(BoardStreamHandshakeInterceptor.SIGNED_DEVICE_ATTR); + boolean signed = signedDevice != null; + UUID deviceId = signed ? signedDevice : parseDeviceId(session.getUri()); if (deviceId == null) { close(session, CLOSE_NO_DEVICE); return; @@ -91,16 +109,41 @@ public void afterConnectionEstablished(@NonNull WebSocketSession session) { 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) { + Board incoming = new Board(safe, signed); + Board[] displaced = {null}; + Board current = sessions.compute(deviceId, (id, existing) -> { + if (!signed && existing != null && existing.signed() && existing.session().isOpen()) { + return existing; + } + displaced[0] = existing; + return incoming; + }); + if (current != incoming) { + log.warn("Board stream refused unsigned session={} for device {}: it holds signed session {}", + session.getId(), deviceId, current.session().getId()); + close(session, CLOSE_SIGNED_SESSION_ACTIVE); + return; + } + session.getAttributes().put(DEVICE_ATTR, deviceId); + if (displaced[0] != null) { log.info("Board stream device {} superseded session {} with {}", - deviceId, previous.getId(), session.getId()); - close(previous, CLOSE_SUPERSEDED); + deviceId, displaced[0].session().getId(), session.getId()); + close(displaced[0].session(), CLOSE_SUPERSEDED); } - log.info("Board stream connected: session={} device={}", session.getId(), deviceId); + log.info("Board stream connected: session={} device={} signed={}", session.getId(), deviceId, signed); + } + + /** + * Closes the device's connection, if it has one, for a revoke. Its reconnect is refused: + * a revoked device fails both the signature check and the enrollment check. + */ + public void disconnect(UUID deviceId) { + Board board = sessions.remove(deviceId); + if (board == null) return; + log.info("Board stream closing session={} device={}: device revoked", board.session().getId(), deviceId); + close(board.session(), CLOSE_REVOKED); } @Override @@ -110,7 +153,7 @@ public void afterConnectionClosed(@NonNull WebSocketSession session, @NonNull Cl // 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); + sessions.computeIfPresent(deviceId, (id, current) -> current.session().getDelegate() == session ? null : current); log.info("Board stream disconnected: session={} device={} status={}", session.getId(), deviceId, status); } @@ -142,29 +185,30 @@ private void push(String reason, UUID 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", + Board board = sessions.get(target); + if (board == null) { + log.debug("Board stream reason={} device={} not connected — it will pick the change up on its next sync", reason, target); return; } - if (send(target, session, json)) { + if (send(target, board, json)) { log.debug("Board stream push reason={} device={}", reason, target); } return; } int sent = 0; - for (Map.Entry entry : sessions.entrySet()) { + 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) { + private boolean send(UUID deviceId, Board board, String json) { + ConcurrentWebSocketSessionDecorator session = board.session(); if (!session.isOpen()) { - sessions.remove(deviceId, session); + sessions.remove(deviceId, board); return false; } try { @@ -193,8 +237,9 @@ private String serialize(String reason, UUID target) { } } - private static UUID parseDeviceId(WebSocketSession session) { - String query = session.getUri() == null ? null : session.getUri().getQuery(); + /** The {@code deviceId} query parameter, or null when it is missing or not a UUID. */ + static UUID parseDeviceId(URI uri) { + String query = uri == null ? null : uri.getQuery(); if (query == null) return null; for (String param : query.split("&")) { if (!param.startsWith("deviceId=")) continue; @@ -202,7 +247,7 @@ private static UUID parseDeviceId(WebSocketSession session) { try { return UUID.fromString(raw); } catch (IllegalArgumentException e) { - log.warn("Board stream session={} sent a malformed deviceId: {}", session.getId(), raw); + log.warn("Board stream upgrade sent a malformed deviceId"); return null; } } diff --git a/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptor.java b/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptor.java new file mode 100644 index 0000000..ffd21bd --- /dev/null +++ b/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptor.java @@ -0,0 +1,154 @@ +package com.ibrasoft.lensbridge.handler; + +import com.ibrasoft.lensbridge.exception.ApiResponseException; +import com.ibrasoft.lensbridge.model.board.Device; +import com.ibrasoft.lensbridge.service.agent.http.DeviceRequestAuthenticator; +import jakarta.servlet.http.HttpServletRequest; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.http.server.ServerHttpResponse; +import org.springframework.http.server.ServletServerHttpRequest; +import org.springframework.lang.NonNull; +import org.springframework.stereotype.Component; +import org.springframework.web.socket.WebSocketHandler; +import org.springframework.web.socket.server.HandshakeInterceptor; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Authenticates the upgrade request of {@code /api/refresh-musallahboard} with the device's + * enrolled key, the same {@code X-MB-*} signature the agent puts on its HTTP requests + * ({@link DeviceRequestAuthenticator}, agent {@code docs/architecture.md} section 9.2): a + * {@code GET} of the path with an empty body. + *

+ * The rules, during the staged rollout: + *

    + *
  • A signature that is present (any of the three headers) is always verified, and a bad + * one is always refused with 401. A {@code ?deviceId=} that names a different device is + * refused too: the query is not covered by the signature, so the header is what counts.
  • + *
  • Each accepted signed upgrade must carry a newer timestamp than the last one accepted for + * that device. The scheme itself accepts replays inside its five-minute window, which is + * harmless for idempotent reads but not here, where a replayed upgrade would take the + * board's place on its channel. The agent signs every dial afresh.
  • + *
  • An unsigned upgrade (an agent that predates signing) is refused when + * {@code musallahboard.board-stream.require-signature} is true. While it is false it is + * accepted and logged, and {@link BoardStreamHandler} never lets it displace a signed + * connection for the same device.
  • + *
+ * Turn the property on once the logs stop showing unsigned connections: then the whole fleet + * runs an agent that signs. + */ +@Component +@Slf4j +public class BoardStreamHandshakeInterceptor implements HandshakeInterceptor { + + /** Handshake attribute: the device the signature proved, when the upgrade was signed. */ + static final String SIGNED_DEVICE_ATTR = "board.signedDeviceId"; + + private static final byte[] NO_BODY = new byte[0]; + + private final DeviceRequestAuthenticator authenticator; + private final boolean requireSignature; + + /** Newest accepted timestamp per device, so a captured upgrade cannot be replayed. */ + private final Map lastTimestamp = new ConcurrentHashMap<>(); + + public BoardStreamHandshakeInterceptor( + DeviceRequestAuthenticator authenticator, + @Value("${musallahboard.board-stream.require-signature:false}") boolean requireSignature) { + this.authenticator = authenticator; + this.requireSignature = requireSignature; + if (!requireSignature) { + log.info("Board stream accepts unsigned upgrades from older agents " + + "(musallahboard.board-stream.require-signature=false)"); + } + } + + @Override + public boolean beforeHandshake(@NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response, + @NonNull WebSocketHandler wsHandler, @NonNull Map attributes) { + if (!(request instanceof ServletServerHttpRequest servletRequest)) { + response.setStatusCode(HttpStatus.BAD_REQUEST); + return false; + } + HttpServletRequest http = servletRequest.getServletRequest(); + UUID named = BoardStreamHandler.parseDeviceId(request.getURI()); + + if (!hasSignatureHeader(http)) { + if (requireSignature) { + log.warn("Board stream refused an unsigned upgrade for device {} ({})", named, userAgent(http)); + response.setStatusCode(HttpStatus.UNAUTHORIZED); + return false; + } + // Logged every time on purpose: when these stop, the fleet has migrated and + // require-signature can be turned on. + log.warn("Board stream accepted an unsigned upgrade for device {} ({}); " + + "the board needs an agent that signs it before " + + "musallahboard.board-stream.require-signature is turned on", named, userAgent(http)); + return true; + } + + Device device; + try { + device = authenticator.authenticate(http, NO_BODY); + } catch (ApiResponseException e) { + // The authenticator has already logged which check failed. + response.setStatusCode(HttpStatus.UNAUTHORIZED); + return false; + } + UUID deviceId = device.getId(); + if (named != null && !named.equals(deviceId)) { + log.warn("Board stream refused a signed upgrade for device {} that names device {} in its query", + deviceId, named); + response.setStatusCode(HttpStatus.BAD_REQUEST); + return false; + } + // Already parsed and range-checked by the authenticator. + long timestamp = Long.parseLong(http.getHeader(DeviceRequestAuthenticator.TIMESTAMP_HEADER).trim()); + if (!advance(deviceId, timestamp)) { + log.warn("Board stream refused a replayed upgrade for device {} (timestamp {} not newer than the last)", + deviceId, timestamp); + response.setStatusCode(HttpStatus.UNAUTHORIZED); + return false; + } + attributes.put(SIGNED_DEVICE_ATTR, deviceId); + return true; + } + + @Override + public void afterHandshake(@NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response, + @NonNull WebSocketHandler wsHandler, Exception exception) { + // Nothing to do: the handler registers the session once it is established. + } + + /** True, and remembered, when {@code timestamp} is newer than any accepted for the device. */ + private boolean advance(UUID deviceId, long timestamp) { + boolean[] fresh = {false}; + lastTimestamp.compute(deviceId, (id, previous) -> { + if (previous == null || timestamp > previous) { + fresh[0] = true; + return timestamp; + } + return previous; + }); + return fresh[0]; + } + + private static boolean hasSignatureHeader(HttpServletRequest request) { + return request.getHeader(DeviceRequestAuthenticator.DEVICE_ID_HEADER) != null + || request.getHeader(DeviceRequestAuthenticator.TIMESTAMP_HEADER) != null + || request.getHeader(DeviceRequestAuthenticator.SIGNATURE_HEADER) != null; + } + + private static String userAgent(HttpServletRequest request) { + String ua = request.getHeader("User-Agent"); + if (ua == null) return "no User-Agent"; + // Logged verbatim otherwise: keep a hostile value to one short line. + String cleaned = ua.replaceAll("[\\p{Cntrl}]", "?"); + return cleaned.length() > 80 ? cleaned.substring(0, 80) + "..." : cleaned; + } +} diff --git a/src/main/java/com/ibrasoft/lensbridge/service/agent/http/DeviceRequestAuthenticator.java b/src/main/java/com/ibrasoft/lensbridge/service/agent/http/DeviceRequestAuthenticator.java index 4365ea2..be2f787 100644 --- a/src/main/java/com/ibrasoft/lensbridge/service/agent/http/DeviceRequestAuthenticator.java +++ b/src/main/java/com/ibrasoft/lensbridge/service/agent/http/DeviceRequestAuthenticator.java @@ -47,7 +47,11 @@ * {@code permitAll} in {@code WebSecurityConfig}; this is their authentication. *

* Replays inside the five-minute window are accepted. That is by design: the endpoints this - * guards are idempotent reads, so a replay only fetches the same content again. + * guards are idempotent reads, so a replay only fetches the same content again. The query + * string is not signed either, so nothing in it may matter to an authenticated endpoint. The + * board refresh stream is the exception on both counts and checks them itself + * ({@code BoardStreamHandshakeInterceptor}): a replayed upgrade would displace the board, and + * its {@code ?deviceId=} must agree with the signed device. */ @Component @Slf4j @@ -71,7 +75,8 @@ public DeviceRequestAuthenticator(DeviceRepository deviceRepository, Ed25519Veri this(deviceRepository, verifier, Clock.systemUTC()); } - DeviceRequestAuthenticator(DeviceRepository deviceRepository, Ed25519Verifier verifier, Clock clock) { + /** With a fixed clock, for tests that check signatures made at a known time. */ + public DeviceRequestAuthenticator(DeviceRepository deviceRepository, Ed25519Verifier verifier, Clock clock) { this.deviceRepository = deviceRepository; this.verifier = verifier; this.clock = clock; diff --git a/src/main/resources/application.properties.example b/src/main/resources/application.properties.example index e420971..1ba8351 100644 --- a/src/main/resources/application.properties.example +++ b/src/main/resources/application.properties.example @@ -55,6 +55,12 @@ musallahboard.agent.sweepIntervalMs=5000 # 0 or less keeps them forever. musallahboard.telemetry.retentionDays=14 musallahboard.telemetry.pruneCron=0 30 3 * * * +# Board refresh stream (/api/refresh-musallahboard). Agents that sign its upgrade with the device +# key (X-MB-* headers) are always verified, and a bad signature is always refused. While this is +# false, agents that predate signing may still connect unsigned (logged as "Board stream accepted +# an unsigned upgrade ..."), but can never take over from a signed connection. Set it to true +# once those log lines stop: every board then runs an agent that signs. +musallahboard.board-stream.require-signature=false # Raises the WebSocket text buffer to fit a screenshot result from the agent (base64, up to # 8 MiB). On by default; set false only if the container already configures this. lensbridge.websocket.container-customizer.enabled=true diff --git a/src/test/java/com/ibrasoft/lensbridge/config/WebSocketConfigTest.java b/src/test/java/com/ibrasoft/lensbridge/config/WebSocketConfigTest.java index 12195b6..2813b97 100644 --- a/src/test/java/com/ibrasoft/lensbridge/config/WebSocketConfigTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/config/WebSocketConfigTest.java @@ -2,17 +2,37 @@ import com.ibrasoft.lensbridge.handler.AgentWebSocketHandler; import com.ibrasoft.lensbridge.handler.BoardStreamHandler; +import com.ibrasoft.lensbridge.handler.BoardStreamHandshakeInterceptor; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; +import org.springframework.web.socket.config.annotation.ServletWebSocketHandlerRegistry; import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; +import org.springframework.web.socket.server.support.WebSocketHttpRequestHandler; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; class WebSocketConfigTest { + private final BoardStreamHandshakeInterceptor boardStreamInterceptor = mock(BoardStreamHandshakeInterceptor.class); private final WebSocketConfig config = - new WebSocketConfig(mock(BoardStreamHandler.class), mock(AgentWebSocketHandler.class)); + new WebSocketConfig(mock(BoardStreamHandler.class), boardStreamInterceptor, + mock(AgentWebSocketHandler.class)); + + /** Without the interceptor the refresh stream would accept anyone who knows a device id. */ + @Test + void boardStreamUpgradeGoesThroughTheSignatureInterceptor() { + config.frontendBaseUrl = "https://admin.example"; + config.musallahBoardBaseUrl = "https://board.example"; + ServletWebSocketHandlerRegistry registry = new ServletWebSocketHandlerRegistry(); + config.registerWebSocketHandlers(registry); + + SimpleUrlHandlerMapping mapping = (SimpleUrlHandlerMapping) registry.getHandlerMapping(); + WebSocketHttpRequestHandler stream = + (WebSocketHttpRequestHandler) mapping.getUrlMap().get("/api/refresh-musallahboard"); + assertThat(stream.getHandshakeInterceptors()).contains(boardStreamInterceptor); + } /** * 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/handler/BoardStreamHandlerTest.java b/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandlerTest.java index be84aaa..36575b7 100644 --- a/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandlerTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandlerTest.java @@ -15,6 +15,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -226,6 +227,117 @@ void closeCallbackOfTheRawSessionStillRemovesItsWrapper() throws Exception { assertThat(s.sent).isEmpty(); } + // ── signed and unsigned connections (staged rollout) ────────────────── + + @Test + void signedConnectionTakesTheDeviceFromTheVerifiedSignatureNotTheQuery() throws Exception { + UUID device = enrolled(); + Session s = connectSigned(device, null); + + handler.configChanged(device); + + assertThat(s.closedWith).isNull(); + assertThat(s.sent).hasSize(1); + } + + @Test + void unsignedConnectionCannotEvictASignedOne() throws Exception { + UUID device = enrolled(); + Session board = connectSigned(device, "deviceId=" + device); + Session intruder = connect(device); + + assertThat(intruder.closedWith.getCode()).isEqualTo(4004); + assertThat(board.closedWith).isNull(); + handler.configChanged(device); + assertThat(board.sent).hasSize(1); + assertThat(intruder.sent).isEmpty(); + + // The refused session's close callback must not unregister the board. + handler.afterConnectionClosed(intruder.ws, CloseStatus.NORMAL); + handler.configChanged(device); + assertThat(board.sent).hasSize(2); + } + + @Test + void signedConnectionSupersedesAnUnsignedOne() throws Exception { + UUID device = enrolled(); + Session squatter = connect(device); + Session board = connectSigned(device, "deviceId=" + device); + + assertThat(squatter.closedWith).isEqualTo(BoardStreamHandler.CLOSE_SUPERSEDED); + handler.configChanged(device); + assertThat(board.sent).hasSize(1); + } + + @Test + void signedReconnectSupersedesTheBoardsOwnStaleSignedSession() throws Exception { + UUID device = enrolled(); + Session stale = connectSigned(device, null); + Session fresh = connectSigned(device, null); + + assertThat(stale.closedWith).isEqualTo(BoardStreamHandler.CLOSE_SUPERSEDED); + handler.configChanged(device); + assertThat(fresh.sent).hasSize(1); + } + + /** A legacy board reconnecting replaces its own earlier unsigned socket, as before. */ + @Test + void unsignedReconnectStillSupersedesAnUnsignedSession() throws Exception { + UUID device = enrolled(); + Session first = connect(device); + Session second = connect(device); + + assertThat(first.closedWith).isEqualTo(BoardStreamHandler.CLOSE_SUPERSEDED); + assertThat(second.closedWith).isNull(); + } + + @Test + void unsignedConnectionMayRegisterOnceTheSignedSessionHasGone() throws Exception { + UUID device = enrolled(); + Session board = connectSigned(device, null); + board.open = false; // dropped, close callback not yet delivered + Session legacy = connect(device); + + assertThat(legacy.closedWith).isNull(); + handler.configChanged(device); + assertThat(legacy.sent).hasSize(1); + } + + @Test + void signedConnectionForARevokedDeviceIsStillRefused() throws Exception { + UUID id = UUID.randomUUID(); + Device revoked = Device.builder().id(id).displayName("d").build(); + revoked.setRevokedAt(Instant.now()); + when(deviceRepository.findById(id)).thenReturn(Optional.of(revoked)); + + Session s = connectSigned(id, null); + + assertThat(s.closedWith.getCode()).isEqualTo(4003); + } + + // ── revoke ──────────────────────────────────────────────────────────── + + @Test + void disconnectClosesTheDevicesSessionAsRevokedAndStopsDelivery() throws Exception { + UUID device = enrolled(); + Session mine = connectSigned(device, null); + Session other = connect(enrolled()); + + handler.disconnect(device); + + assertThat(mine.closedWith).isEqualTo(BoardStreamHandler.CLOSE_REVOKED); + assertThat(other.closedWith).isNull(); + mine.open = true; // a leftover registration would write to it + handler.contentChanged("posters"); + assertThat(mine.sent).isEmpty(); + assertThat(other.sent).hasSize(1); + } + + @Test + void disconnectOfABoardWithNoSessionIsANoOp() { + handler.disconnect(UUID.randomUUID()); + } + // ── helpers ─────────────────────────────────────────────────────────── /** Registers a device the repository will vouch for, and returns its id. */ @@ -246,10 +358,19 @@ private Session connectWithQuery(String query) throws Exception { return session; } + /** A connection whose upgrade signature {@link BoardStreamHandshakeInterceptor} verified. */ + private Session connectSigned(UUID deviceId, String query) throws Exception { + Session session = new Session(query); + session.attributes.put(BoardStreamHandshakeInterceptor.SIGNED_DEVICE_ATTR, deviceId); + 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<>(); + final Map attributes = new HashMap<>(); boolean open = true; CloseStatus closedWith; @@ -258,7 +379,7 @@ private static class Session { 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<>()); + when(ws.getAttributes()).thenReturn(attributes); doAnswer(inv -> { sent.add(((TextMessage) inv.getArgument(0)).getPayload()); return null; diff --git a/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptorTest.java b/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptorTest.java new file mode 100644 index 0000000..1283eab --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptorTest.java @@ -0,0 +1,258 @@ +package com.ibrasoft.lensbridge.handler; + +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.agent.Ed25519TestUtil; +import com.ibrasoft.lensbridge.service.agent.handshake.Ed25519Verifier; +import com.ibrasoft.lensbridge.service.agent.http.DeviceRequestAuthenticator; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.server.ServletServerHttpRequest; +import org.springframework.http.server.ServletServerHttpResponse; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.web.socket.WebSocketHandler; + +import java.security.KeyPair; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; +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.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * The upgrade of {@code /api/refresh-musallahboard}: device signatures are verified with the + * real {@link DeviceRequestAuthenticator}, and unsigned upgrades are let through only while + * {@code musallahboard.board-stream.require-signature} is off. + */ +class BoardStreamHandshakeInterceptorTest { + + private static final String PATH = "/api/refresh-musallahboard"; + private static final UUID DEVICE_ID = UUID.fromString("3f2a1b4c-5d6e-4f70-8a9b-0c1d2e3f4a5b"); + + private final DeviceRepository deviceRepository = mock(DeviceRepository.class); + private final DeviceRequestAuthenticator authenticator = + new DeviceRequestAuthenticator(deviceRepository, new Ed25519Verifier()); + private KeyPair keys; + private Device device; + + @BeforeEach + void setUp() { + keys = Ed25519TestUtil.generate(); + device = Device.builder().id(DEVICE_ID).displayName("Lobby board").audience(Audience.BOTH) + .publicKey(Ed25519TestUtil.rawPublicKey(keys.getPublic())).build(); + when(deviceRepository.findById(any())).thenReturn(Optional.empty()); + when(deviceRepository.findById(DEVICE_ID)).thenReturn(Optional.of(device)); + } + + // ── signed upgrades ─────────────────────────────────────────────────── + + @Test + void validSignatureIsAcceptedAndRecordsTheDevice() { + Result r = handshake(interceptor(false), signed("deviceId=" + DEVICE_ID, now())); + + assertThat(r.accepted).isTrue(); + assertThat(r.attributes).containsEntry(BoardStreamHandshakeInterceptor.SIGNED_DEVICE_ATTR, DEVICE_ID); + } + + @Test + void signedUpgradeNeedsNoQuery() { + Result r = handshake(interceptor(true), signed(null, now())); + + assertThat(r.accepted).isTrue(); + assertThat(r.attributes).containsEntry(BoardStreamHandshakeInterceptor.SIGNED_DEVICE_ATTR, DEVICE_ID); + } + + /** A present signature is checked whatever the flag says: being lenient is for its absence only. */ + @Test + void badSignatureIsRefusedEvenWhileUnsignedUpgradesAreAllowed() { + MockHttpServletRequest request = signed("deviceId=" + DEVICE_ID, now()); + byte[] other = Ed25519TestUtil.sign(Ed25519TestUtil.generate().getPrivate(), new byte[]{1}); + request.removeHeader(DeviceRequestAuthenticator.SIGNATURE_HEADER); + request.addHeader(DeviceRequestAuthenticator.SIGNATURE_HEADER, Base64.getEncoder().encodeToString(other)); + + Result r = handshake(interceptor(false), request); + + assertThat(r.accepted).isFalse(); + assertThat(r.status).isEqualTo(401); + assertThat(r.attributes).isEmpty(); + } + + @Test + void partialSignatureHeadersCountAsASignatureAndAreRefused() { + MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); + request.setQueryString("deviceId=" + DEVICE_ID); + request.addHeader(DeviceRequestAuthenticator.DEVICE_ID_HEADER, DEVICE_ID.toString()); + + Result r = handshake(interceptor(false), request); + + assertThat(r.accepted).isFalse(); + assertThat(r.status).isEqualTo(401); + } + + @Test + void signatureForAnotherPathIsRefused() { + long ts = now(); + MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); + sign(request, "/api/agent/weather", ts); + + assertThat(handshake(interceptor(false), request).status).isEqualTo(401); + } + + @Test + void staleTimestampIsRefused() { + Result r = handshake(interceptor(false), signed(null, now() - 6 * 60_000)); + + assertThat(r.accepted).isFalse(); + assertThat(r.status).isEqualTo(401); + } + + @Test + void revokedDeviceIsRefused() { + device.setRevokedAt(Instant.now()); + + assertThat(handshake(interceptor(false), signed(null, now())).status).isEqualTo(401); + } + + /** The query is not signed, so it may not name a different device than the signature. */ + @Test + void queryNamingAnotherDeviceIsRefused() { + Result r = handshake(interceptor(false), signed("deviceId=" + UUID.randomUUID(), now())); + + assertThat(r.accepted).isFalse(); + assertThat(r.status).isEqualTo(400); + } + + /** Replaying a captured upgrade inside the five-minute window would evict the board. */ + @Test + void replayedUpgradeIsRefused() { + BoardStreamHandshakeInterceptor interceptor = interceptor(false); + long ts = now(); + + assertThat(handshake(interceptor, signed(null, ts)).accepted).isTrue(); + Result replay = handshake(interceptor, signed(null, ts)); + assertThat(replay.accepted).isFalse(); + assertThat(replay.status).isEqualTo(401); + assertThat(handshake(interceptor, signed(null, ts - 1)).accepted).isFalse(); + + assertThat(handshake(interceptor, signed(null, ts + 1)).accepted).isTrue(); + } + + @Test + void refusedSignatureDoesNotAdvanceTheReplayGuard() { + BoardStreamHandshakeInterceptor interceptor = interceptor(false); + long ts = now(); + MockHttpServletRequest forged = signed(null, ts); + forged.removeHeader(DeviceRequestAuthenticator.SIGNATURE_HEADER); + forged.addHeader(DeviceRequestAuthenticator.SIGNATURE_HEADER, + Base64.getEncoder().encodeToString(new byte[64])); + + assertThat(handshake(interceptor, forged).accepted).isFalse(); + assertThat(handshake(interceptor, signed(null, ts)).accepted).isTrue(); + } + + // ── unsigned upgrades ───────────────────────────────────────────────── + + @Test + void unsignedUpgradeIsAcceptedWhileSignaturesAreNotRequired() { + MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); + request.setQueryString("deviceId=" + DEVICE_ID); + + Result r = handshake(interceptor(false), request); + + assertThat(r.accepted).isTrue(); + // No proven device: the handler treats it as an unsigned claim. + assertThat(r.attributes).doesNotContainKey(BoardStreamHandshakeInterceptor.SIGNED_DEVICE_ATTR); + } + + @Test + void unsignedUpgradeIsRefusedOnceSignaturesAreRequired() { + MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); + request.setQueryString("deviceId=" + DEVICE_ID); + + Result r = handshake(interceptor(true), request); + + assertThat(r.accepted).isFalse(); + assertThat(r.status).isEqualTo(401); + } + + // ── agreement with the agent ────────────────────────────────────────── + + /** + * The same vector as the agent's {@code TestRefreshHeaderSignedGolden} + * (internal/boardsync/boardsync_test.go): its device key is the Ed25519 seed of 32 bytes + * of 7, and the signature below is exactly what the agent sends on the refresh upgrade at + * that time. If either side changes the signed message, one of the two tests fails. + */ + @Test + void agentGoldenVectorVerifies() { + long ts = 1790258531123L; + Device agentDevice = Device.builder().id(DEVICE_ID).displayName("golden").audience(Audience.BOTH) + .publicKey(Base64.getDecoder().decode("6kpsY+KcUgq+9VB7Ey7F+ZVHdq6+vnuSQh7qaRRG0iw=")) + .build(); + DeviceRepository repository = mock(DeviceRepository.class); + when(repository.findById(DEVICE_ID)).thenReturn(Optional.of(agentDevice)); + DeviceRequestAuthenticator fixedClock = new DeviceRequestAuthenticator(repository, new Ed25519Verifier(), + Clock.fixed(Instant.ofEpochMilli(ts), ZoneOffset.UTC)); + BoardStreamHandshakeInterceptor interceptor = new BoardStreamHandshakeInterceptor(fixedClock, true); + + MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); + request.setQueryString("deviceId=" + DEVICE_ID); + request.addHeader("User-Agent", "musallahboard-agent/0.3.0"); + request.addHeader(DeviceRequestAuthenticator.DEVICE_ID_HEADER, DEVICE_ID.toString()); + request.addHeader(DeviceRequestAuthenticator.TIMESTAMP_HEADER, Long.toString(ts)); + request.addHeader(DeviceRequestAuthenticator.SIGNATURE_HEADER, + "TGTiOMTSt8N/7ad06yMvmWo9a68Yz01LNGYnDOPGfedeiPTPjC9hqtKa/yLAOa7rXlDa5UfKTpmI28tdSME4Dg=="); + + Result r = handshake(interceptor, request); + + assertThat(r.accepted).isTrue(); + assertThat(r.attributes).containsEntry(BoardStreamHandshakeInterceptor.SIGNED_DEVICE_ATTR, DEVICE_ID); + } + + // ── helpers ─────────────────────────────────────────────────────────── + + private BoardStreamHandshakeInterceptor interceptor(boolean requireSignature) { + return new BoardStreamHandshakeInterceptor(authenticator, requireSignature); + } + + private static long now() { + return System.currentTimeMillis(); + } + + /** An upgrade signed exactly as the agent signs it: GET, the path, an empty body. */ + private MockHttpServletRequest signed(String query, long timestamp) { + MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); + request.setQueryString(query); + sign(request, PATH, timestamp); + return request; + } + + private void sign(MockHttpServletRequest request, String signedPath, long timestamp) { + byte[] message = DeviceRequestAuthenticator.message("GET", signedPath, DEVICE_ID, timestamp, new byte[0]); + request.addHeader(DeviceRequestAuthenticator.DEVICE_ID_HEADER, DEVICE_ID.toString()); + request.addHeader(DeviceRequestAuthenticator.TIMESTAMP_HEADER, Long.toString(timestamp)); + request.addHeader(DeviceRequestAuthenticator.SIGNATURE_HEADER, + Base64.getEncoder().encodeToString(Ed25519TestUtil.sign(keys.getPrivate(), message))); + } + + private static Result handshake(BoardStreamHandshakeInterceptor interceptor, MockHttpServletRequest request) { + MockHttpServletResponse response = new MockHttpServletResponse(); + Map attributes = new HashMap<>(); + boolean accepted = interceptor.beforeHandshake(new ServletServerHttpRequest(request), + new ServletServerHttpResponse(response), mock(WebSocketHandler.class), attributes); + return new Result(accepted, response.getStatus(), attributes); + } + + private record Result(boolean accepted, int status, Map attributes) { + } +} From 7bad652cca00a3e1863dd869fd5dc8d9bed9e66b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:11:25 +0000 Subject: [PATCH 2/7] Close a revoked device's refresh stream too Revoking a device closed only its agent WebSocket; the board stream stayed open and kept receiving pushes until the board disconnected on its own. revoke now also calls BoardStreamHandler.disconnect, which closes it with 4003 device_revoked; the reconnect fails both the signature and the enrollment check. --- .../lensbridge/controller/DeviceAdminController.java | 5 ++++- .../DeviceAdminControllerOfflineBundleTest.java | 3 +++ .../lensbridge/controller/DeviceAdminControllerTest.java | 9 +++++++-- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java b/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java index 38f8c4e..62d7621 100644 --- a/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java +++ b/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java @@ -8,6 +8,7 @@ import com.ibrasoft.lensbridge.dto.board.response.DeviceSummary; import com.ibrasoft.lensbridge.dto.board.response.IssueEnrollmentTokenResponse; 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.auth.Permission; import com.ibrasoft.lensbridge.model.board.Device; @@ -69,6 +70,7 @@ public class DeviceAdminController { private final AgentSessionRegistry sessionRegistry; private final AdminAuditService auditService; private final OfflineBundleService offlineBundleService; + private final BoardStreamHandler boardStream; @Operation(operationId = "listDevices", summary = "List every enrolled board device") @GetMapping @@ -126,7 +128,7 @@ public ResponseEntity issueEnrollmentToken( @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.") + description = "Closes any live agent session and refresh stream. Idempotent: re-revoking an already revoked device is a no-op.") @ApiResponses({ @ApiResponse(responseCode = "200", description = "Device revoked"), @ApiResponse(responseCode = "404", description = "No device with that id", @@ -146,6 +148,7 @@ public ResponseEntity revoke(@PathVariable UUID deviceId, d.setRevokedAt(Instant.now()); deviceRepository.save(d); sessionRegistry.closeIfPresent(deviceId, CloseStatus.POLICY_VIOLATION.withReason("device_revoked")); + boardStream.disconnect(deviceId); log.warn("Device {} revoked by {}", deviceId, getCurrentUserEmail()); auditService.logAuditEvent(getCurrentUserEmail(), AuditAction.REVOKE_DEVICE, diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerOfflineBundleTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerOfflineBundleTest.java index c6bdbbc..91c3e16 100644 --- a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerOfflineBundleTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerOfflineBundleTest.java @@ -6,6 +6,7 @@ import com.ibrasoft.lensbridge.model.auth.Role; import com.ibrasoft.lensbridge.repository.sql.DeviceCommandRepository; import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; +import com.ibrasoft.lensbridge.handler.BoardStreamHandler; import com.ibrasoft.lensbridge.service.AdminAuditService; import com.ibrasoft.lensbridge.service.UserService; import com.ibrasoft.lensbridge.service.agent.AgentSessionRegistry; @@ -70,6 +71,8 @@ class DeviceAdminControllerOfflineBundleTest { private AgentSessionRegistry sessionRegistry; @MockitoBean private AdminAuditService auditService; + @MockitoBean + private BoardStreamHandler boardStream; /** Needed by WebConfig's CurrentUserArgumentResolver; see BoardAdminControllerPermissionTest. */ @MockitoBean diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerTest.java index f0629b9..bb1c4fd 100644 --- a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerTest.java @@ -1,6 +1,7 @@ package com.ibrasoft.lensbridge.controller; import com.fasterxml.jackson.databind.ObjectMapper; +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.Device; @@ -46,6 +47,7 @@ void revoke_closesRegisteredAgentSession() throws Exception { CommandDispatcher commandDispatcher = mock(CommandDispatcher.class); AgentSessionRegistry registry = new AgentSessionRegistry(mock(DeviceEventPublisher.class)); AdminAuditService auditService = mock(AdminAuditService.class); + BoardStreamHandler boardStream = mock(BoardStreamHandler.class); DeviceAdminController controller = new DeviceAdminController( enrollmentTokenService, @@ -55,7 +57,8 @@ void revoke_closesRegisteredAgentSession() throws Exception { new ObjectMapper(), registry, auditService, - mock(OfflineBundleService.class)); + mock(OfflineBundleService.class), + boardStream); UUID deviceId = UUID.randomUUID(); Device device = Device.builder() @@ -84,6 +87,7 @@ void revoke_closesRegisteredAgentSession() throws Exception { verify(transport).close(argThat(status -> status.getCode() == CloseStatus.POLICY_VIOLATION.getCode() && "device_revoked".equals(status.getReason()))); + verify(boardStream).disconnect(deviceId); verify(auditService).logAuditEvent( eq("root@example.com"), eq(AuditAction.REVOKE_DEVICE), eq("Device"), eq(deviceId), eq("10.0.0.1")); @@ -102,7 +106,8 @@ void revoke_isANoOpAndDoesNotReAuditWhenAlreadyRevoked() throws Exception { new ObjectMapper(), new AgentSessionRegistry(mock(DeviceEventPublisher.class)), auditService, - mock(OfflineBundleService.class)); + mock(OfflineBundleService.class), + mock(BoardStreamHandler.class)); UUID deviceId = UUID.randomUUID(); Instant revokedAt = Instant.now().minusSeconds(3600); From 889a1478665e93f50050d068b22372638e114e6d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:14:33 +0000 Subject: [PATCH 3/7] Take the client address only from trusted proxies server.forward-headers-strategy=framework installs Spring's ForwardedHeaderFilter, which believes X-Forwarded-For and Forwarded from any peer. getRemoteAddr(), and with it the rate-limit bucket, the audit log address and an enrolling board's lastSeenIp, was whatever the caller wrote: a fresh header per request was a fresh bucket. The example configuration now uses the native strategy. Tomcat's RemoteIpValve honours X-Forwarded-For only on a connection from a trusted proxy (server.tomcat.remoteip.internal-proxies; unset, loopback and the private ranges), reads it from the right and stops at the first untrusted address, so entries a client prepends are never used. On other connections the socket address stands and X-Forwarded-* are ignored; the RFC 7239 Forwarded header is never read. A trusted proxy's X-Forwarded-Proto/-Host/-Port still give the app https, secure requests and the public host, which the WebSocket same-origin check uses. The valve rather than an application filter: it runs in the container before any filter, so nothing in the app can be ordered ahead of it, and it is the configuration Spring Boot already maintains. ClientAddressProxyIntegrationTest sends real requests to an embedded Tomcat set up from these properties, with the production WebConfig and RateLimitingFilter (MockMvc would skip the valve). From an untrusted peer, rotating X-Forwarded-For or Forwarded: for= keeps charging one bucket until 429; through a trusted proxy each client gets its own, and the client's prepended entries are ignored. With the old strategy the untrusted-peer tests fail. --- .../controller/AgentEnrollmentController.java | 6 +- .../lensbridge/security/ClientAddress.java | 13 +- .../resources/application.properties.example | 24 ++- .../ClientAddressProxyIntegrationTest.java | 173 ++++++++++++++++++ .../lensbridge/security/ProxyTestApp.java | 58 ++++++ 5 files changed, 258 insertions(+), 16 deletions(-) create mode 100644 src/test/java/com/ibrasoft/lensbridge/security/ClientAddressProxyIntegrationTest.java create mode 100644 src/test/java/com/ibrasoft/lensbridge/security/ProxyTestApp.java diff --git a/src/main/java/com/ibrasoft/lensbridge/controller/AgentEnrollmentController.java b/src/main/java/com/ibrasoft/lensbridge/controller/AgentEnrollmentController.java index aa91005..ba18289 100644 --- a/src/main/java/com/ibrasoft/lensbridge/controller/AgentEnrollmentController.java +++ b/src/main/java/com/ibrasoft/lensbridge/controller/AgentEnrollmentController.java @@ -57,9 +57,9 @@ public class AgentEnrollmentController { @PostMapping("/enroll") public ResponseEntity enroll(@Valid @RequestBody AgentEnrollRequest request, HttpServletRequest httpRequest) { - // Not X-Forwarded-For: any client can send that header. With server.forward-headers-strategy - // set, the container has already resolved it from the trusted proxy and getRemoteAddr() - // returns that address (or the socket peer when there is no proxy). + // Not X-Forwarded-For: any client can send that header. With + // server.forward-headers-strategy=native, Tomcat has already resolved it, from trusted + // proxies only, and getRemoteAddr() returns that address (or the socket peer otherwise). String remoteIp = httpRequest.getRemoteAddr(); Outcome outcome = enrollmentService.enroll( diff --git a/src/main/java/com/ibrasoft/lensbridge/security/ClientAddress.java b/src/main/java/com/ibrasoft/lensbridge/security/ClientAddress.java index 7971648..cf7fd31 100644 --- a/src/main/java/com/ibrasoft/lensbridge/security/ClientAddress.java +++ b/src/main/java/com/ibrasoft/lensbridge/security/ClientAddress.java @@ -6,11 +6,14 @@ * The single place that decides which address counts as "the client" for rate limiting and * logging. * - *

This is deliberately just {@code getRemoteAddr()}. Proxy headers such as X-Forwarded-For - * are resolved by Spring ({@code server.forward-headers-strategy}), which only honours them - * from trusted proxies and then reports the real client through {@code getRemoteAddr()}. Reading - * the header by hand would take the leftmost entry, which the client itself controls, so any - * caller could pick a fresh rate-limit bucket per request. + *

This is deliberately just {@code getRemoteAddr()}. With + * {@code server.forward-headers-strategy=native}, Tomcat's RemoteIpValve has already replaced it + * with the client address from X-Forwarded-For, and only when the connection came from a trusted + * proxy ({@code server.tomcat.remoteip.internal-proxies}); anyone else keeps their socket + * address. Reading the header by hand would take the leftmost entry, which the client itself + * controls, so any caller could pick a fresh rate-limit bucket per request. The + * {@code framework} strategy has the same flaw: Spring's ForwardedHeaderFilter believes the + * header from any peer. {@code ClientAddressProxyIntegrationTest} pins this down. */ public final class ClientAddress { diff --git a/src/main/resources/application.properties.example b/src/main/resources/application.properties.example index 1ba8351..a217712 100644 --- a/src/main/resources/application.properties.example +++ b/src/main/resources/application.properties.example @@ -141,14 +141,22 @@ lensbridge.app.maxRefreshTokensPerUser=5 auth.token.verification-expiration-ms=86400000 auth.token.password-reset-expiration-ms=3600000 -# Behind a reverse proxy (nginx): honor X-Forwarded-* headers. The client address used for rate -# limiting and audit logs is request.getRemoteAddr(), which this setting derives from -# X-Forwarded-For. That header is only as trustworthy as the proxy that writes it: nginx's -# $proxy_add_x_forwarded_for appends to whatever the client sent. Either have the edge proxy -# overwrite it (proxy_set_header X-Forwarded-For $remote_addr), or use -# server.forward-headers-strategy=native with server.tomcat.remoteip.internal-proxies, which -# reads the header from the right and skips only trusted proxies. -server.forward-headers-strategy=framework +# Behind a reverse proxy (nginx). The client address used for rate limiting, audit logs and a +# board's last-seen IP is request.getRemoteAddr(). "native" lets Tomcat's RemoteIpValve set it +# from X-Forwarded-For, but only when the connection comes from a trusted proxy: it reads the +# header from the right and stops at the first address that is not a trusted proxy, so whatever a +# client puts in front is never used. A direct connection from anywhere else keeps its socket +# address, and its X-Forwarded-* headers are ignored. X-Forwarded-Proto/-Host/-Port from a +# trusted proxy set the scheme, host and port (https, secure requests, WebSocket same-origin). +# The RFC 7239 Forwarded header is not read at all. +# Do NOT use "framework": Spring's ForwardedHeaderFilter believes these headers from any peer. +server.forward-headers-strategy=native +# Trusted proxies, a Java regex over the peer's IP address. Unset, Tomcat trusts loopback and the +# private ranges (10/8, 172.16/12, 192.168/16, 169.254/16, 100.64/10, fc00::/7, ...), which suits +# nginx on the same host or on the Docker network, provided the app port itself is not reachable +# from those networks by anyone else (docker-compose.yml binds it to 127.0.0.1). To pin it to the +# proxy only, e.g. the Docker bridge gateway or nginx's container address: +# server.tomcat.remoteip.internal-proxies=172\\.18\\.0\\.\\d{1,3} # Actuator (prod): only health, no details leak management.endpoints.web.exposure.include=health diff --git a/src/test/java/com/ibrasoft/lensbridge/security/ClientAddressProxyIntegrationTest.java b/src/test/java/com/ibrasoft/lensbridge/security/ClientAddressProxyIntegrationTest.java new file mode 100644 index 0000000..eaca72e --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/security/ClientAddressProxyIntegrationTest.java @@ -0,0 +1,173 @@ +package com.ibrasoft.lensbridge.security; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.ibrasoft.lensbridge.service.UserService; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.bean.override.mockito.MockitoBean; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Properties; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Which address the rate limiter (and the audit log, and a board's last-seen IP) keys on, with + * requests sent over a real socket to an embedded Tomcat configured the way + * {@code application.properties.example} configures production: the forwarded-header handling + * lives in the container (RemoteIpValve), which MockMvc would bypass. + *

+ * The test client always connects from 127.0.0.1, so "untrusted peer" and "trusted proxy" are + * two configurations of who the trusted proxies are. Each request reports what the application + * saw, and {@code X-Rate-Limit-Remaining} shows which bucket it was charged to. + */ +class ClientAddressProxyIntegrationTest { + + static final int LIMIT = 5; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final HttpClient HTTP = HttpClient.newBuilder().proxy(HttpClient.Builder.NO_PROXY).build(); + + /** The shipped example must keep the strategy these tests exercise. */ + @Test + void exampleConfigurationUsesTheNativeStrategy() throws IOException { + Properties example = new Properties(); + try (var in = Files.newInputStream(Path.of("src/main/resources/application.properties.example"))) { + example.load(in); + } + assertThat(example.getProperty("server.forward-headers-strategy")).isEqualTo("native"); + } + + /** A client talking to the app directly, not through the proxy: its headers are lies. */ + @Nested + @SpringBootTest(classes = ProxyTestApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { + "server.forward-headers-strategy=native", + // The proxy is somewhere else; this test's client is not it. + "server.tomcat.remoteip.internal-proxies=10\\.255\\.255\\.254", + "ratelimit.requests=" + LIMIT}) + @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) + class UntrustedPeer { + + @LocalServerPort + int port; + @MockitoBean + UserService userService; + + @Test + void spoofedXForwardedForDoesNotChangeTheRateLimitKey() throws Exception { + for (int i = 1; i <= LIMIT; i++) { + HttpResponse r = get(port, "X-Forwarded-For", "203.0.113." + i); + assertThat(r.statusCode()).isEqualTo(200); + assertThat(seen(r).get("clientAddress").asText()).isEqualTo("127.0.0.1"); + // One bucket for all of them: the remaining allowance keeps falling. + assertThat(remaining(r)).isEqualTo(LIMIT - i); + } + HttpResponse over = get(port, "X-Forwarded-For", "198.51.100.77"); + assertThat(over.statusCode()).isEqualTo(429); + } + + @Test + void spoofedForwardedForDoesNotChangeTheRateLimitKey() throws Exception { + for (int i = 1; i <= LIMIT; i++) { + HttpResponse r = get(port, "Forwarded", "for=203.0.113." + i + ";proto=https"); + assertThat(seen(r).get("clientAddress").asText()).isEqualTo("127.0.0.1"); + assertThat(seen(r).get("secure").asBoolean()).isFalse(); + assertThat(remaining(r)).isEqualTo(LIMIT - i); + } + assertThat(get(port, "Forwarded", "for=198.51.100.77").statusCode()).isEqualTo(429); + } + + @Test + void spoofedSchemeAndHostAreIgnored() throws Exception { + HttpResponse r = get(port, "X-Forwarded-Proto", "https", + "X-Forwarded-Host", "evil.example", "X-Forwarded-Port", "443"); + JsonNode seen = seen(r); + assertThat(seen.get("scheme").asText()).isEqualTo("http"); + assertThat(seen.get("secure").asBoolean()).isFalse(); + assertThat(seen.get("serverName").asText()).isEqualTo("127.0.0.1"); + assertThat(seen.get("serverPort").asInt()).isEqualTo(port); + } + } + + /** nginx on the same host or the Docker network: Tomcat's default trusted ranges apply. */ + @Nested + @SpringBootTest(classes = ProxyTestApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = {"server.forward-headers-strategy=native", "ratelimit.requests=" + LIMIT}) + @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) + class TrustedProxy { + + @LocalServerPort + int port; + @MockitoBean + UserService userService; + + @Test + void proxysXForwardedForIsTheClientAndEachClientHasItsOwnBucket() throws Exception { + for (int i = 1; i <= LIMIT + 2; i++) { + HttpResponse r = get(port, "X-Forwarded-For", "203.0.113." + i); + assertThat(r.statusCode()).isEqualTo(200); + assertThat(seen(r).get("clientAddress").asText()).isEqualTo("203.0.113." + i); + assertThat(remaining(r)).isEqualTo(LIMIT - 1); + } + } + + /** + * A proxy that appends ($proxy_add_x_forwarded_for) passes the client's own entries + * through. The address is read from the right, so those are never used: rotating them + * still charges the one real client. + */ + @Test + void entriesTheClientPrependedAreIgnored() throws Exception { + for (int i = 1; i <= LIMIT; i++) { + HttpResponse r = get(port, "X-Forwarded-For", "198.51.100." + i + ", 203.0.113.9"); + assertThat(seen(r).get("clientAddress").asText()).isEqualTo("203.0.113.9"); + assertThat(remaining(r)).isEqualTo(LIMIT - i); + } + assertThat(get(port, "X-Forwarded-For", "198.51.100.99, 203.0.113.9").statusCode()).isEqualTo(429); + } + + @Test + void proxysSchemeHostAndPortAreHonoured() throws Exception { + JsonNode seen = seen(get(port, "X-Forwarded-For", "203.0.113.1", "X-Forwarded-Proto", "https", + "X-Forwarded-Host", "api.example.org", "X-Forwarded-Port", "443")); + assertThat(seen.get("scheme").asText()).isEqualTo("https"); + assertThat(seen.get("secure").asBoolean()).isTrue(); + assertThat(seen.get("serverName").asText()).isEqualTo("api.example.org"); + assertThat(seen.get("serverPort").asInt()).isEqualTo(443); + } + + /** Only X-Forwarded-For is read; the RFC 7239 header is not, even from the proxy. */ + @Test + void forwardedHeaderIsNotRead() throws Exception { + JsonNode seen = seen(get(port, "Forwarded", "for=203.0.113.5")); + assertThat(seen.get("clientAddress").asText()).isEqualTo("127.0.0.1"); + } + } + + static HttpResponse get(int port, String... headers) throws IOException, InterruptedException { + HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/api/test/client")); + for (int i = 0; i < headers.length; i += 2) { + request.header(headers[i], headers[i + 1]); + } + return HTTP.send(request.build(), HttpResponse.BodyHandlers.ofString()); + } + + static JsonNode seen(HttpResponse response) throws IOException { + assertThat(response.statusCode()).isEqualTo(200); + return MAPPER.readTree(response.body()); + } + + static long remaining(HttpResponse response) { + return Long.parseLong(response.headers().firstValue("X-Rate-Limit-Remaining").orElseThrow()); + } +} diff --git a/src/test/java/com/ibrasoft/lensbridge/security/ProxyTestApp.java b/src/test/java/com/ibrasoft/lensbridge/security/ProxyTestApp.java new file mode 100644 index 0000000..d8f8bf0 --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/security/ProxyTestApp.java @@ -0,0 +1,58 @@ +package com.ibrasoft.lensbridge.security; + +import com.ibrasoft.lensbridge.config.RateLimitingFilter; +import com.ibrasoft.lensbridge.config.WebConfig; +import com.ibrasoft.lensbridge.service.agent.http.AuthenticatedDeviceArgumentResolver; +import com.ibrasoft.lensbridge.service.agent.http.DeviceAuthInterceptor; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; +import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration; +import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration; +import org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration; +import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; +import org.springframework.context.annotation.Import; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * The smallest real web application that still has everything deciding the client address: + * embedded Tomcat configured by Spring Boot from {@code server.forward-headers-strategy} and + * {@code server.tomcat.remoteip.*} (which installs, or does not install, RemoteIpValve or + * ForwardedHeaderFilter), and the production {@link WebConfig} registering + * {@link RateLimitingFilter} on {@code /api/*}. No database or security: neither takes part. + */ +@SpringBootConfiguration +@ImportAutoConfiguration({ + PropertyPlaceholderAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class, + EmbeddedWebServerFactoryCustomizerAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, + WebMvcAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, + JacksonAutoConfiguration.class}) +@Import({WebConfig.class, RateLimitingFilter.class, CurrentUserArgumentResolver.class, + AuthenticatedDeviceArgumentResolver.class, DeviceAuthInterceptor.class, ProxyTestApp.Echo.class}) +class ProxyTestApp { + + /** What the application sees of a request after the container and the filters. */ + @RestController + static class Echo { + @GetMapping("/api/test/client") + Map client(HttpServletRequest request) { + Map seen = new LinkedHashMap<>(); + seen.put("clientAddress", ClientAddress.of(request)); + seen.put("scheme", request.getScheme()); + seen.put("secure", request.isSecure()); + seen.put("serverName", request.getServerName()); + seen.put("serverPort", request.getServerPort()); + return seen; + } + } +} From 17f1dabe96788303b94f3ad8ade5157a8550b56f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:14:33 +0000 Subject: [PATCH 4/7] Keep the app port off public interfaces; nginx overwrites X-Forwarded-For - docker-compose.yml published 8085 on every interface, so the proxy could be bypassed. It now binds 127.0.0.1 unless LENSBRIDGE_BIND_ADDRESS says otherwise. - nginx is the edge, so it sets X-Forwarded-For to $remote_addr instead of appending to the client's, with a note on restoring the client address first when a CDN sits in front. It also drops any client Forwarded and X-Forwarded-Prefix headers. - The nginx upstream pointed at lensbridge:8080; the app listens on 8085. --- README.md | 2 ++ docker-compose.yml | 6 +++++- docker/nginx/nginx.conf | 19 ++++++++++++++++--- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 49ae4d7..d65009a 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,8 @@ docker compose up --build ...aaaand that's it. Pretty anti-climactic. Make sure to include your SSL certs in the `docker/nginx/certs` directory and configure the environment variables accordingly. Once the container is running, the API will be accessible at `https://localhost/api/`. +The app container publishes port 8085 on `127.0.0.1` only (override with `LENSBRIDGE_BIND_ADDRESS`); put nginx in front of it with `docker/nginx/nginx.conf`. The app takes the client address from `X-Forwarded-For` only when the connection comes from a trusted proxy (`server.forward-headers-strategy=native`, see `application.properties.example`), so rate limits and audit logs cannot be steered by a client's own headers. + ## API Documentation This project uses SpringDoc OpenAPI to generate API documentation. Once the application is running, you can access the API docs at: diff --git a/docker-compose.yml b/docker-compose.yml index 0cffd53..a3d59ec 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -47,8 +47,12 @@ services: MUSALLAHBOARD_AGENT_WS_URL: ${MUSALLAHBOARD_AGENT_WS_URL} MUSALLAHBOARD_CONTENT_SIGNING_KEY: ${MUSALLAHBOARD_CONTENT_SIGNING_KEY:-} OPENWEATHER_API_KEY: ${OPENWEATHER_API_KEY} + # Loopback only by default, so the app is reached through the reverse proxy and never + # directly: it trusts X-Forwarded-For from private and loopback peers (see + # server.forward-headers-strategy in application.properties.example). Set + # LENSBRIDGE_BIND_ADDRESS (e.g. 0.0.0.0) only for a deployment that needs the port elsewhere. ports: - - "8085:8085" + - "${LENSBRIDGE_BIND_ADDRESS:-127.0.0.1}:8085:8085" networks: - lensbridge-net healthcheck: diff --git a/docker/nginx/nginx.conf b/docker/nginx/nginx.conf index dff1b4c..5527271 100644 --- a/docker/nginx/nginx.conf +++ b/docker/nginx/nginx.conf @@ -44,8 +44,9 @@ http { '' close; } + # The app listens on 8085 (Dockerfile EXPOSE, compose port, healthcheck). upstream lensbridge_upstream { - server lensbridge:8080; + server lensbridge:8085; keepalive 32; } @@ -93,12 +94,24 @@ http { proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + # This is the edge: overwrite, never append. $proxy_add_x_forwarded_for would pass + # on whatever the client sent. The app (server.forward-headers-strategy=native) + # reads the rightmost untrusted entry, so appending would still be safe there, but + # one address is what every reader of this header should see. + # If a CDN (e.g. Cloudflare) sits in front of nginx, $remote_addr is the CDN's + # address: first restore the client with the realip module, listing only the CDN's + # published ranges, for example: + # set_real_ip_from 173.245.48.0/20; # ...and the rest of the CDN's list + # real_ip_header CF-Connecting-IP; + proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Port $server_port; + # Not read by the app; dropped so a client's copy can never matter if that changes. + proxy_set_header Forwarded ""; + proxy_set_header X-Forwarded-Prefix ""; - # WebSocket support (/api/agent/ws, /api/dashboard/ws/**) + # WebSocket support (/api/agent/ws, /api/refresh-musallahboard, /api/dashboard/ws/**) proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; From 79c416fb1033755ede6c2cbcbc46f3aa0bbc326d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:20:10 +0000 Subject: [PATCH 5/7] Bound command TTL and deadline per kind; validate payloads on issue IssueCommandRequest only required deadlineMs and ttlSeconds to be positive, and the dispatcher stored whatever payload JSON it was given. A system.reboot issued with a year-long TTL would fire whenever an offline board next connected, and any payload reached the board as sent. - Each CommandKind now carries a maximum time-to-live: 10 minutes for the disruptive kinds (kiosk.restart, system.reboot, update.install_now), 15 for chrome.screenshot and logs.tail, an hour for chrome.reload and config.refresh. The 5-minute default fits all of them. ttlSeconds is also capped at an hour on the DTO, deadlineMs at 15 minutes (the console gives update.install_now 10). - Each kind has a payload rule. Parameterless kinds take none: absent, null or {} (what the admin console sends); anything else is refused. logs.tail takes {"lines": n} with n a whole number from 1 to 500, the agent's bounds, and no other field. What is stored and sent is rebuilt from the checked values. - Every failure is a 400 whose message names the field and the limit. DeviceAdminControllerIssueCommandTest replays the exact requests CommandLauncher.jsx sends and expects them accepted. --- .../controller/DeviceAdminController.java | 9 +- .../board/request/IssueCommandRequest.java | 33 +++- .../model/board/commands/CommandKind.java | 54 ++++-- .../model/board/commands/CommandPayloads.java | 76 +++++++++ .../commands/InvalidCommandException.java | 13 ++ .../service/agent/CommandDispatcher.java | 32 +++- ...DeviceAdminControllerIssueCommandTest.java | 158 ++++++++++++++++++ .../model/board/commands/CommandKindTest.java | 26 +++ .../board/commands/CommandPayloadsTest.java | 94 +++++++++++ .../service/agent/CommandDbFake.java | 5 + .../service/agent/CommandDispatcherTest.java | 80 +++++++++ 11 files changed, 551 insertions(+), 29 deletions(-) create mode 100644 src/main/java/com/ibrasoft/lensbridge/model/board/commands/CommandPayloads.java create mode 100644 src/main/java/com/ibrasoft/lensbridge/model/board/commands/InvalidCommandException.java create mode 100644 src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerIssueCommandTest.java create mode 100644 src/test/java/com/ibrasoft/lensbridge/model/board/commands/CommandPayloadsTest.java diff --git a/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java b/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java index 62d7621..3402d29 100644 --- a/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java +++ b/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java @@ -167,9 +167,16 @@ public ResponseEntity revoke(@PathVariable UUID deviceId, summary = "Queue a command for a device", description = "Returns as soon as the command is queued; delivery and execution are reported " + "asynchronously over the agent websocket. The permission required depends on the " - + "command kind: board:command:benign, :disruptive, or :inspect.") + + "command kind: board:command:benign, :disruptive, or :inspect. ttlSeconds is capped per " + + "kind (10 minutes for kiosk.restart, system.reboot and update.install_now; 15 for " + + "chrome.screenshot and logs.tail; an hour for chrome.reload and config.refresh), " + + "deadlineMs at 15 minutes. Only logs.tail takes a payload, {\"lines\": 1..500}; for " + + "the others it must be absent, null or {}.") @ApiResponses({ @ApiResponse(responseCode = "202", description = "Command accepted and queued for delivery"), + @ApiResponse(responseCode = "400", description = "Unknown kind, a payload the kind does not take, " + + "or a deadline or time-to-live over its limit", + content = @Content(schema = @Schema(implementation = MessageResponse.class))), @ApiResponse(responseCode = "403", description = "Caller lacks the permission for this command kind", content = @Content(schema = @Schema(implementation = MessageResponse.class))) }) diff --git a/src/main/java/com/ibrasoft/lensbridge/dto/board/request/IssueCommandRequest.java b/src/main/java/com/ibrasoft/lensbridge/dto/board/request/IssueCommandRequest.java index 5ef881d..bf9c28c 100644 --- a/src/main/java/com/ibrasoft/lensbridge/dto/board/request/IssueCommandRequest.java +++ b/src/main/java/com/ibrasoft/lensbridge/dto/board/request/IssueCommandRequest.java @@ -1,6 +1,7 @@ package com.ibrasoft.lensbridge.dto.board.request; import com.fasterxml.jackson.databind.JsonNode; +import jakarta.validation.constraints.Max; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Positive; @@ -10,19 +11,33 @@ *

* {@code kind} is the command's wire name and must be one of * {@link com.ibrasoft.lensbridge.model.board.commands.CommandKind}; anything else is a 400. - * {@code payload} is the kind-specific JSON body (may be empty for parameterless commands). It - * is stored and forwarded as given, not interpreted here: the agent validates it. + * {@code payload} is the kind-specific JSON body, checked against the kind's rule when the + * command is issued: parameterless kinds take none (absent, null or {@code {}}), and + * {@code logs.tail} takes {@code {"lines": 1..500}}. Anything else is a 400. *

- * {@code deadlineMs} bounds execution once the agent starts. {@code ttlSeconds} bounds how - * long the command stays deliverable while the device is offline. Keep it short for - * anything disruptive (a reboot that fires a day late is a bug, not a feature ;) ). Both fall - * back to server defaults when null (30 s to execute, 5 min to be delivered). + * {@code deadlineMs} bounds execution once the agent starts, at most {@value #MAX_DEADLINE_MS} + * ms. {@code ttlSeconds} bounds how long the command stays deliverable while the device is + * offline, at most the kind's own limit (ten minutes for disruptive kinds such as + * {@code system.reboot}, an hour at most for any kind). Both fall back to server defaults + * when null (30 s to execute, 5 min to be delivered). */ public record IssueCommandRequest( @NotBlank @Pattern(regexp = "[a-z]+\\.[a-z_]+", message = "kind must be in dotted lowercase form, e.g. chrome.reload") String kind, JsonNode payload, - @Positive Integer deadlineMs, - @Positive Integer ttlSeconds -) {} + @Positive @Max(value = MAX_DEADLINE_MS, message = "deadlineMs must be at most " + MAX_DEADLINE_MS) + Integer deadlineMs, + @Positive @Max(value = MAX_TTL_SECONDS, message = "ttlSeconds must be at most " + MAX_TTL_SECONDS + + "; disruptive commands allow less") + Integer ttlSeconds +) { + /** + * Longest execution deadline for any command: 15 minutes. The admin console gives + * {@code update.install_now} 10 minutes to download and install a release. + */ + public static final int MAX_DEADLINE_MS = 15 * 60 * 1000; + + /** Longest time-to-live of any kind (the benign ones); each kind may allow less. */ + public static final int MAX_TTL_SECONDS = 60 * 60; +} diff --git a/src/main/java/com/ibrasoft/lensbridge/model/board/commands/CommandKind.java b/src/main/java/com/ibrasoft/lensbridge/model/board/commands/CommandKind.java index 396a233..492a88e 100644 --- a/src/main/java/com/ibrasoft/lensbridge/model/board/commands/CommandKind.java +++ b/src/main/java/com/ibrasoft/lensbridge/model/board/commands/CommandKind.java @@ -1,38 +1,48 @@ package com.ibrasoft.lensbridge.model.board.commands; +import com.fasterxml.jackson.databind.JsonNode; import com.ibrasoft.lensbridge.model.auth.Permission; +import java.time.Duration; import java.util.Arrays; import java.util.Optional; /** - * The registry of issuable command kinds and their {@link CommandRisk}. + * The registry of issuable command kinds: each one's {@link CommandRisk}, the longest it may + * wait undelivered for an offline board, and its payload rule ({@link CommandPayloads}). *

- * The dispatcher never interprets a command's payload: it stores the raw JSON and hands it to - * the agent, which owns each kind's payload shape and validation. So classification, and with - * it authorization (see {@code CommandAuthorizer}), hangs off the wire string alone. Adding a - * command kind is a constant here (which forces a risk classification) plus the agent-side - * handler. + * Authorization (see {@code CommandAuthorizer}) hangs off the wire string alone. Adding a + * command kind is a constant here, which forces a risk classification, a maximum time-to-live + * and a payload rule, plus the agent-side handler. + *

+ * The time-to-live is short for disruptive kinds on purpose: a reboot or kiosk restart that + * fires when a board comes back from a long outage is a surprise in a prayer space, not a + * delayed success. Benign kinds may wait longer; a refresh when the board returns is useful. */ public enum CommandKind { - CHROME_RELOAD("chrome.reload", CommandRisk.BENIGN), - CONFIG_REFRESH("config.refresh", CommandRisk.BENIGN), + CHROME_RELOAD("chrome.reload", CommandRisk.BENIGN, Duration.ofHours(1), CommandPayloads::none), + CONFIG_REFRESH("config.refresh", CommandRisk.BENIGN, Duration.ofHours(1), CommandPayloads::none), - KIOSK_RESTART("kiosk.restart", CommandRisk.DISRUPTIVE), - SYSTEM_REBOOT("system.reboot", CommandRisk.DISRUPTIVE), + KIOSK_RESTART("kiosk.restart", CommandRisk.DISRUPTIVE, Duration.ofMinutes(10), CommandPayloads::none), + SYSTEM_REBOOT("system.reboot", CommandRisk.DISRUPTIVE, Duration.ofMinutes(10), CommandPayloads::none), /** Takes the board off its content for the update screen, and may restart the agent. */ - UPDATE_INSTALL_NOW("update.install_now", CommandRisk.DISRUPTIVE), + UPDATE_INSTALL_NOW("update.install_now", CommandRisk.DISRUPTIVE, Duration.ofMinutes(10), CommandPayloads::none), - CHROME_SCREENSHOT("chrome.screenshot", CommandRisk.INSPECT), - LOGS_TAIL("logs.tail", CommandRisk.INSPECT); + /** Captures whatever is on the screen when it runs, so it must not run long after it was asked for. */ + CHROME_SCREENSHOT("chrome.screenshot", CommandRisk.INSPECT, Duration.ofMinutes(15), CommandPayloads::none), + LOGS_TAIL("logs.tail", CommandRisk.INSPECT, Duration.ofMinutes(15), CommandPayloads::logsTail); private final String wireName; private final CommandRisk risk; + private final Duration maxTtl; + private final CommandPayloads.Rule payloadRule; - CommandKind(String wireName, CommandRisk risk) { + CommandKind(String wireName, CommandRisk risk, Duration maxTtl, CommandPayloads.Rule payloadRule) { this.wireName = wireName; this.risk = risk; + this.maxTtl = maxTtl; + this.payloadRule = payloadRule; } /** The dotted discriminator sent over the wire, e.g. {@code chrome.reload}. */ @@ -48,6 +58,22 @@ public Permission getRequiredPermission() { return risk.getRequiredPermission(); } + /** The longest this kind may stay deliverable while its board is offline. */ + public Duration getMaxTtl() { + return maxTtl; + } + + /** + * Checks a payload for this kind. + * + * @param payload as the admin sent it; null when absent + * @return the payload to store and send to the board (JSON null for none) + * @throws InvalidCommandException when this kind does not accept it + */ + public JsonNode validatePayload(JsonNode payload) { + return payloadRule.check(this, payload); + } + public static Optional from(String wireName) { if (wireName == null) return Optional.empty(); return Arrays.stream(values()) diff --git a/src/main/java/com/ibrasoft/lensbridge/model/board/commands/CommandPayloads.java b/src/main/java/com/ibrasoft/lensbridge/model/board/commands/CommandPayloads.java new file mode 100644 index 0000000..1b5962e --- /dev/null +++ b/src/main/java/com/ibrasoft/lensbridge/model/board/commands/CommandPayloads.java @@ -0,0 +1,76 @@ +package com.ibrasoft.lensbridge.model.board.commands; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.NullNode; + +import java.util.Iterator; + +/** + * Payload rules per command kind, checked when a command is issued. What passes is + * re-serialized from the checked values, so nothing the client tacked on reaches a board. + *

+ * The agent (internal/commands in the agent repo) still validates on its side; these rules + * mirror it, so an admin gets a 400 now instead of a "rejected" result from the board later, + * and a payload field added there without a rule here is refused rather than passed through. + */ +public final class CommandPayloads { + + /** {@code logs.tail} bounds, as the agent's internal/commands/logs_tail.go enforces them. */ + public static final int LOGS_TAIL_MIN_LINES = 1; + public static final int LOGS_TAIL_MAX_LINES = 500; + + private CommandPayloads() { + } + + /** Checks one kind's payload and returns what to store and send. */ + @FunctionalInterface + interface Rule { + JsonNode check(CommandKind kind, JsonNode payload); + } + + /** + * No payload. Absent, JSON null and an empty object (what the admin console sends for a + * parameterless command) all mean none; anything else is refused rather than ignored. + */ + static JsonNode none(CommandKind kind, JsonNode payload) { + if (isEmpty(payload)) return NullNode.getInstance(); + throw new InvalidCommandException(kind.getWireName() + " takes no payload"); + } + + /** + * {@code {"lines": n}} with n a whole number from 1 to 500, or no payload (or no + * {@code lines}) for the agent's default of 100. + */ + static JsonNode logsTail(CommandKind kind, JsonNode payload) { + if (isEmpty(payload)) return NullNode.getInstance(); + String bounds = "a whole number from " + LOGS_TAIL_MIN_LINES + " to " + LOGS_TAIL_MAX_LINES; + if (!payload.isObject()) { + throw new InvalidCommandException(kind.getWireName() + + " payload must be an object like {\"lines\": 100}"); + } + for (Iterator names = payload.fieldNames(); names.hasNext(); ) { + String name = names.next(); + if (!"lines".equals(name)) { + throw new InvalidCommandException(kind.getWireName() + " payload has an unknown field \"" + + truncate(name) + "\"; only \"lines\" is accepted"); + } + } + JsonNode lines = payload.get("lines"); + if (lines == null || lines.isNull()) return NullNode.getInstance(); + if (!lines.isIntegralNumber() || !lines.canConvertToInt() + || lines.intValue() < LOGS_TAIL_MIN_LINES || lines.intValue() > LOGS_TAIL_MAX_LINES) { + throw new InvalidCommandException(kind.getWireName() + " lines must be " + bounds); + } + return JsonNodeFactory.instance.objectNode().put("lines", lines.intValue()); + } + + static boolean isEmpty(JsonNode payload) { + return payload == null || payload.isNull() || payload.isMissingNode() + || (payload.isObject() && payload.isEmpty()); + } + + private static String truncate(String s) { + return s.length() > 40 ? s.substring(0, 40) + "..." : s; + } +} diff --git a/src/main/java/com/ibrasoft/lensbridge/model/board/commands/InvalidCommandException.java b/src/main/java/com/ibrasoft/lensbridge/model/board/commands/InvalidCommandException.java new file mode 100644 index 0000000..fd65500 --- /dev/null +++ b/src/main/java/com/ibrasoft/lensbridge/model/board/commands/InvalidCommandException.java @@ -0,0 +1,13 @@ +package com.ibrasoft.lensbridge.model.board.commands; + +/** + * A command request its kind does not accept: a payload of the wrong shape, or a time-to-live + * longer than the kind allows. The message is written for the admin who issued it, and is + * returned as the 400's message. + */ +public class InvalidCommandException extends IllegalArgumentException { + + public InvalidCommandException(String message) { + super(message); + } +} diff --git a/src/main/java/com/ibrasoft/lensbridge/service/agent/CommandDispatcher.java b/src/main/java/com/ibrasoft/lensbridge/service/agent/CommandDispatcher.java index 02ea493..c6a511b 100644 --- a/src/main/java/com/ibrasoft/lensbridge/service/agent/CommandDispatcher.java +++ b/src/main/java/com/ibrasoft/lensbridge/service/agent/CommandDispatcher.java @@ -13,6 +13,7 @@ import com.ibrasoft.lensbridge.model.board.DeviceCommand; import com.ibrasoft.lensbridge.model.board.DeviceCommandStatus; import com.ibrasoft.lensbridge.model.board.commands.CommandKind; +import com.ibrasoft.lensbridge.model.board.commands.InvalidCommandException; import com.ibrasoft.lensbridge.repository.sql.DeviceCommandRepository; import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; import com.ibrasoft.lensbridge.service.agent.events.DeviceEventPublisher; @@ -62,7 +63,8 @@ public class CommandDispatcher { /** * How long an undelivered command stays deliverable. Long enough to survive a kiosk * restart or a brief WiFi drop, short enough that nothing surprising fires after an - * outage. Overridable per command via {@code ttlSeconds}. + * outage. Overridable per command via {@code ttlSeconds}, up to the kind's + * {@link CommandKind#getMaxTtl()}; it must not exceed the shortest of those. */ private static final Duration DEFAULT_TTL = Duration.ofMinutes(5); @@ -81,16 +83,38 @@ public class CommandDispatcher { private final ObjectMapper objectMapper; private final DeviceEventPublisher events; + /** + * Validates and queues a command. The kind, its payload, the deadline and the time-to-live + * are all checked before anything is looked up or stored: each failure is a 400 naming + * the field. + */ public CommandIssuedResponse issue(UUID deviceId, String issuedBy, IssueCommandRequest request) { CommandKind kind = CommandKind.from(request.kind()).orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unknown command kind: " + request.kind())); + JsonNode payload; + try { + payload = kind.validatePayload(request.payload()); + } catch (InvalidCommandException e) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage()); + } + int deadline = request.deadlineMs() == null ? DEFAULT_DEADLINE_MS : request.deadlineMs(); + // Also enforced on the request DTO; checked again for callers that skip bean validation. + if (deadline <= 0 || deadline > IssueCommandRequest.MAX_DEADLINE_MS) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, + "deadlineMs must be from 1 to " + IssueCommandRequest.MAX_DEADLINE_MS); + } + Duration ttl = request.ttlSeconds() == null ? DEFAULT_TTL : Duration.ofSeconds(request.ttlSeconds()); + if (ttl.isNegative() || ttl.isZero() || ttl.compareTo(kind.getMaxTtl()) > 0) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ttlSeconds for " + kind.getWireName() + + " must be from 1 to " + kind.getMaxTtl().toSeconds()); + } + Device device = deviceRepository.findById(deviceId) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Device not found")); if (device.getRevokedAt() != null) { throw new ResponseStatusException(HttpStatus.CONFLICT, "Device is revoked"); } - JsonNode payload = request.payload() == null ? NullNode.getInstance() : request.payload(); String payloadJson; try { payloadJson = objectMapper.writeValueAsString(payload); @@ -98,13 +122,11 @@ public CommandIssuedResponse issue(UUID deviceId, String issuedBy, IssueCommandR throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid payload"); } - int deadline = request.deadlineMs() == null ? DEFAULT_DEADLINE_MS : request.deadlineMs(); - Duration ttl = request.ttlSeconds() == null ? DEFAULT_TTL : Duration.ofSeconds(request.ttlSeconds()); Instant issuedAt = Instant.now(); DeviceCommand cmd = commandRepository.save(DeviceCommand.builder() .deviceId(deviceId) - .kind(request.kind()) + .kind(kind.getWireName()) .payloadJson(payloadJson) .issuedBy(issuedBy) .deadlineMs(deadline) diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerIssueCommandTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerIssueCommandTest.java new file mode 100644 index 0000000..08d81ac --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerIssueCommandTest.java @@ -0,0 +1,158 @@ +package com.ibrasoft.lensbridge.controller; + +import com.ibrasoft.lensbridge.handler.BoardStreamHandler; +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.DeviceCommand; +import com.ibrasoft.lensbridge.repository.sql.DeviceCommandRepository; +import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; +import com.ibrasoft.lensbridge.security.CommandAuthorizer; +import com.ibrasoft.lensbridge.service.AdminAuditService; +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.EnrollmentTokenService; +import com.ibrasoft.lensbridge.service.agent.events.DeviceEventPublisher; +import com.ibrasoft.lensbridge.service.board.offline.OfflineBundleService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; + +import java.util.Optional; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.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/admin/board/devices/{id}/commands} with the real {@link CommandDispatcher}: + * the requests the admin console sends (CommandLauncher.jsx) still go through, and a TTL, + * deadline or payload the kind does not accept is a 400 whose message names the problem. + */ +@WebMvcTest(controllers = DeviceAdminController.class) +@Import({MethodSecurityTestConfig.class, CommandDispatcher.class, DeviceAdminControllerIssueCommandTest.Authorizer.class}) +class DeviceAdminControllerIssueCommandTest { + + /** Under the bean name the endpoint's @PreAuthorize expression refers to. */ + @TestConfiguration + static class Authorizer { + @Bean + CommandAuthorizer commandAuthorizer() { + return new CommandAuthorizer(); + } + } + + private static final UUID DEVICE_ID = UUID.fromString("3f2a1b4c-0000-4000-8000-000000000002"); + private static final String URL = "/api/admin/board/devices/" + DEVICE_ID + "/commands"; + + @Autowired + private MockMvc mockMvc; + + @MockitoBean + private DeviceRepository deviceRepository; + @MockitoBean + private DeviceCommandRepository commandRepository; + @MockitoBean + private AgentSessionRegistry sessionRegistry; + @MockitoBean + private DeviceEventPublisher events; + @MockitoBean + private OfflineBundleService offlineBundleService; + @MockitoBean + private EnrollmentTokenService enrollmentTokenService; + @MockitoBean + private AdminAuditService auditService; + @MockitoBean + private BoardStreamHandler boardStream; + @MockitoBean + private UserService userService; + + @BeforeEach + void setUp() { + when(deviceRepository.findById(DEVICE_ID)).thenReturn(Optional.of(Device.builder() + .id(DEVICE_ID).displayName("Lobby").audience(Audience.BOTH).publicKey(new byte[32]).build())); + when(commandRepository.save(any())).thenAnswer(inv -> { + DeviceCommand cmd = inv.getArgument(0); + cmd.setId(UUID.randomUUID()); + return cmd; + }); + } + + private ResultActions issue(String body) throws Exception { + return mockMvc.perform(post(URL) + .with(TestAuthorities.asHolderOf(Permission.BOARD_COMMAND_BENIGN, + Permission.BOARD_COMMAND_DISRUPTIVE, Permission.BOARD_COMMAND_INSPECT)) + .contentType(MediaType.APPLICATION_JSON) + .content(body)); + } + + /** Exactly what CommandLauncher.jsx sends today: {} payloads and its per-kind deadlines. */ + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "{\"kind\":\"chrome.reload\",\"payload\":{},\"deadlineMs\":30000}", + "{\"kind\":\"config.refresh\",\"payload\":{},\"deadlineMs\":30000}", + "{\"kind\":\"chrome.screenshot\",\"payload\":{},\"deadlineMs\":30000}", + "{\"kind\":\"kiosk.restart\",\"payload\":{},\"deadlineMs\":30000}", + "{\"kind\":\"system.reboot\",\"payload\":{},\"deadlineMs\":30000}", + "{\"kind\":\"update.install_now\",\"payload\":{},\"deadlineMs\":600000}", + "{\"kind\":\"logs.tail\",\"payload\":{\"lines\":100},\"deadlineMs\":45000}", + "{\"kind\":\"logs.tail\",\"payload\":{\"lines\":500},\"deadlineMs\":45000}"}) + void theAdminConsolesRequestsAreAccepted(String body) throws Exception { + issue(body).andExpect(status().isAccepted()); + } + + @Test + void aRebootWithAYearLongTtlIsABadRequest() throws Exception { + issue("{\"kind\":\"system.reboot\",\"ttlSeconds\":31536000}") + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value( + "ttlSeconds: ttlSeconds must be at most 3600; disruptive commands allow less")); + verify(commandRepository, never()).save(any()); + } + + @Test + void aRebootTtlOverItsOwnLimitIsABadRequest() throws Exception { + issue("{\"kind\":\"system.reboot\",\"ttlSeconds\":3600}") + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value("ttlSeconds for system.reboot must be from 1 to 600")); + verify(commandRepository, never()).save(any()); + } + + @Test + void aDeadlineOverTheCapIsABadRequest() throws Exception { + issue("{\"kind\":\"update.install_now\",\"deadlineMs\":86400000}") + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value("deadlineMs: deadlineMs must be at most 900000")); + } + + @Test + void aPayloadOnAParameterlessKindIsABadRequest() throws Exception { + issue("{\"kind\":\"kiosk.restart\",\"payload\":{\"unit\":\"ssh.service\"}}") + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value("kiosk.restart takes no payload")); + verify(commandRepository, never()).save(any()); + } + + @Test + void logsTailOutsideItsBoundsIsABadRequest() throws Exception { + issue("{\"kind\":\"logs.tail\",\"payload\":{\"lines\":999999999}}") + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value("logs.tail lines must be a whole number from 1 to 500")); + } +} diff --git a/src/test/java/com/ibrasoft/lensbridge/model/board/commands/CommandKindTest.java b/src/test/java/com/ibrasoft/lensbridge/model/board/commands/CommandKindTest.java index 88f3b42..5ad0a35 100644 --- a/src/test/java/com/ibrasoft/lensbridge/model/board/commands/CommandKindTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/model/board/commands/CommandKindTest.java @@ -74,4 +74,30 @@ void screenshotRequiresInspectRatherThanDisruptive() { assertThat(screenshot.get().getRequiredPermission()) .isEqualTo(Permission.BOARD_COMMAND_INSPECT); } + + // ==================== Time-to-live ==================== + + /** A disruptive command that fires long after it was asked for is a bug, not a feature. */ + @Test + void disruptiveKindsWaitAtMostTenMinutes() { + for (CommandKind kind : CommandKind.values()) { + if (kind.getRisk() == CommandRisk.DISRUPTIVE) { + assertThat(kind.getMaxTtl()).as(kind.getWireName()).isLessThanOrEqualTo(java.time.Duration.ofMinutes(10)); + } + } + } + + @Test + void noKindWaitsLongerThanTheRequestLimitAllows() { + long longest = java.util.Arrays.stream(CommandKind.values()) + .mapToLong(k -> k.getMaxTtl().toSeconds()).max().orElseThrow(); + assertThat(longest).isEqualTo(com.ibrasoft.lensbridge.dto.board.request.IssueCommandRequest.MAX_TTL_SECONDS); + } + + /** The default TTL (5 minutes) applies when the console sends none; every kind must allow it. */ + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.EnumSource(CommandKind.class) + void everyKindAllowsTheDefaultTtl(CommandKind kind) { + assertThat(kind.getMaxTtl()).isGreaterThanOrEqualTo(java.time.Duration.ofMinutes(5)); + } } diff --git a/src/test/java/com/ibrasoft/lensbridge/model/board/commands/CommandPayloadsTest.java b/src/test/java/com/ibrasoft/lensbridge/model/board/commands/CommandPayloadsTest.java new file mode 100644 index 0000000..8193bfe --- /dev/null +++ b/src/test/java/com/ibrasoft/lensbridge/model/board/commands/CommandPayloadsTest.java @@ -0,0 +1,94 @@ +package com.ibrasoft.lensbridge.model.board.commands; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class CommandPayloadsTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static JsonNode json(String s) { + try { + return MAPPER.readTree(s); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + + // ── kinds without a payload ─────────────────────────────────────────── + + /** The admin console sends {} for every button; absent and null mean the same. */ + @ParameterizedTest + @EnumSource(value = CommandKind.class, names = "LOGS_TAIL", mode = EnumSource.Mode.EXCLUDE) + void parameterlessKindsAcceptNoPayloadAndStoreNull(CommandKind kind) { + assertThat(kind.validatePayload(null).isNull()).isTrue(); + assertThat(kind.validatePayload(json("null")).isNull()).isTrue(); + assertThat(kind.validatePayload(json("{}")).isNull()).isTrue(); + } + + @ParameterizedTest + @EnumSource(value = CommandKind.class, names = "LOGS_TAIL", mode = EnumSource.Mode.EXCLUDE) + void parameterlessKindsRefuseAnyPayload(CommandKind kind) { + for (String payload : new String[]{"{\"url\":\"https://evil.example\"}", "[]", "[1]", "\"x\"", "1", "true"}) { + assertThatThrownBy(() -> kind.validatePayload(json(payload))) + .as(payload) + .isInstanceOf(InvalidCommandException.class) + .hasMessage(kind.getWireName() + " takes no payload"); + } + } + + // ── logs.tail ───────────────────────────────────────────────────────── + + @ParameterizedTest + @ValueSource(ints = {1, 100, 500}) + void logsTailAcceptsTheAgentsRange(int lines) { + assertThat(CommandKind.LOGS_TAIL.validatePayload(json("{\"lines\":" + lines + "}"))) + .isEqualTo(json("{\"lines\":" + lines + "}")); + } + + /** No lines means the agent's default of 100; nothing is invented here. */ + @ParameterizedTest + @ValueSource(strings = {"null", "{}", "{\"lines\":null}"}) + void logsTailWithoutLinesLeavesTheDefaultToTheAgent(String payload) { + assertThat(CommandKind.LOGS_TAIL.validatePayload(json(payload)).isNull()).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"{\"lines\":0}", "{\"lines\":-1}", "{\"lines\":501}", "{\"lines\":999999999}", + "{\"lines\":99999999999999999999}", "{\"lines\":2.5}", "{\"lines\":100.0}", "{\"lines\":\"100\"}", + "{\"lines\":true}", "{\"lines\":[100]}"}) + void logsTailRefusesLinesOutsideOneToFiveHundred(String payload) { + assertThatThrownBy(() -> CommandKind.LOGS_TAIL.validatePayload(json(payload))) + .isInstanceOf(InvalidCommandException.class) + .hasMessage("logs.tail lines must be a whole number from 1 to 500"); + } + + @ParameterizedTest + @ValueSource(strings = {"{\"lines\":100,\"unit\":\"sshd\"}", "{\"since\":\"1h\"}"}) + void logsTailRefusesUnknownFields(String payload) { + assertThatThrownBy(() -> CommandKind.LOGS_TAIL.validatePayload(json(payload))) + .isInstanceOf(InvalidCommandException.class) + .hasMessageContaining("unknown field"); + } + + @ParameterizedTest + @ValueSource(strings = {"[]", "100", "\"lines\""}) + void logsTailRefusesANonObject(String payload) { + assertThatThrownBy(() -> CommandKind.LOGS_TAIL.validatePayload(json(payload))) + .isInstanceOf(InvalidCommandException.class) + .hasMessageContaining("must be an object"); + } + + /** The agent bounds (internal/commands/logs_tail.go) and these must stay the same. */ + @org.junit.jupiter.api.Test + void logsTailBoundsMatchTheAgent() { + assertThat(CommandPayloads.LOGS_TAIL_MIN_LINES).isEqualTo(1); + assertThat(CommandPayloads.LOGS_TAIL_MAX_LINES).isEqualTo(500); + } +} diff --git a/src/test/java/com/ibrasoft/lensbridge/service/agent/CommandDbFake.java b/src/test/java/com/ibrasoft/lensbridge/service/agent/CommandDbFake.java index 3004d5f..c0aca6d 100644 --- a/src/test/java/com/ibrasoft/lensbridge/service/agent/CommandDbFake.java +++ b/src/test/java/com/ibrasoft/lensbridge/service/agent/CommandDbFake.java @@ -50,6 +50,11 @@ DeviceCommand insert(DeviceCommand cmd) { return cmd; } + /** Every row, for asserting that nothing was stored. */ + java.util.Collection rows() { + return table.values(); + } + /** The row as the database currently has it. */ DeviceCommand row(UUID id) { return table.get(id); diff --git a/src/test/java/com/ibrasoft/lensbridge/service/agent/CommandDispatcherTest.java b/src/test/java/com/ibrasoft/lensbridge/service/agent/CommandDispatcherTest.java index a4fd65d..7e71273 100644 --- a/src/test/java/com/ibrasoft/lensbridge/service/agent/CommandDispatcherTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/service/agent/CommandDispatcherTest.java @@ -525,6 +525,86 @@ void issue_honoursExplicitTtl() { assertEquals(30, resp.expiresAt().getEpochSecond() - resp.issuedAt().getEpochSecond()); } + // ── limits and payloads ─────────────────────────────────────────────── + + /** The finding: a reboot with a year-long TTL would fire whenever the board reconnects. */ + @Test + void issue_rejectsARebootThatWouldWaitForAYear() { + UUID deviceId = registerDevice(); + + ResponseStatusException ex = assertThrows(ResponseStatusException.class, () -> dispatcher.issue(deviceId, + "admin", new IssueCommandRequest("system.reboot", null, null, 365 * 24 * 3600))); + + assertEquals(400, ex.getStatusCode().value()); + assertEquals("ttlSeconds for system.reboot must be from 1 to 600", ex.getReason()); + assertTrue(db.rows().isEmpty()); + } + + @Test + void issue_appliesEachKindsOwnTtlLimit() { + UUID deviceId = registerDevice(); + + assertThrows(ResponseStatusException.class, () -> dispatcher.issue(deviceId, "admin", + new IssueCommandRequest("kiosk.restart", null, null, 601))); + CommandIssuedResponse reboot = dispatcher.issue(deviceId, "admin", + new IssueCommandRequest("system.reboot", null, null, 600)); + CommandIssuedResponse reload = dispatcher.issue(deviceId, "admin", + new IssueCommandRequest("chrome.reload", null, null, 3600)); + + assertEquals(600, reboot.expiresAt().getEpochSecond() - reboot.issuedAt().getEpochSecond()); + assertEquals(3600, reload.expiresAt().getEpochSecond() - reload.issuedAt().getEpochSecond()); + } + + @Test + void issue_rejectsADeadlineOverTheCap() { + UUID deviceId = registerDevice(); + + ResponseStatusException ex = assertThrows(ResponseStatusException.class, () -> dispatcher.issue(deviceId, + "admin", new IssueCommandRequest("update.install_now", null, IssueCommandRequest.MAX_DEADLINE_MS + 1, null))); + + assertEquals(400, ex.getStatusCode().value()); + CommandIssuedResponse ok = dispatcher.issue(deviceId, "admin", + new IssueCommandRequest("update.install_now", null, 600_000, null)); + assertEquals(600_000, db.row(ok.commandId()).getDeadlineMs()); + } + + @Test + void issue_rejectsAPayloadTheKindDoesNotTake() { + UUID deviceId = registerDevice(); + + ResponseStatusException ex = assertThrows(ResponseStatusException.class, () -> dispatcher.issue(deviceId, + "admin", new IssueCommandRequest("system.reboot", mapper.createObjectNode().put("delay", 1), null, null))); + + assertEquals(400, ex.getStatusCode().value()); + assertEquals("system.reboot takes no payload", ex.getReason()); + assertTrue(db.rows().isEmpty()); + } + + @Test + void issue_rejectsLogsTailOutsideTheAgentsBounds() { + UUID deviceId = registerDevice(); + + ResponseStatusException ex = assertThrows(ResponseStatusException.class, () -> dispatcher.issue(deviceId, + "admin", new IssueCommandRequest("logs.tail", mapper.createObjectNode().put("lines", 999_999_999), null, null))); + + assertEquals(400, ex.getStatusCode().value()); + assertEquals("logs.tail lines must be a whole number from 1 to 500", ex.getReason()); + } + + /** What is stored and sent is rebuilt from the checked values, not the client's JSON. */ + @Test + void issue_storesTheCheckedPayload() throws Exception { + UUID deviceId = registerDevice(); + + CommandIssuedResponse tail = dispatcher.issue(deviceId, "admin", + new IssueCommandRequest("logs.tail", mapper.readTree("{ \"lines\" : 250 }"), null, null)); + CommandIssuedResponse reload = dispatcher.issue(deviceId, "admin", + new IssueCommandRequest("chrome.reload", mapper.createObjectNode(), null, null)); + + assertEquals("{\"lines\":250}", db.row(tail.commandId()).getPayloadJson()); + assertEquals("null", db.row(reload.commandId()).getPayloadJson()); + } + // ── helpers ─────────────────────────────────────────────────────────── private UUID registerDevice() { From 612faa0a0d9ea65f400810a3d4f7ecbc88d0f0fe Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:20:10 +0000 Subject: [PATCH 6/7] Regenerate openapi.yaml - issueDeviceCommand documents its 400 and the per-kind limits; IssueCommandRequest gains maximum 900000 on deadlineMs and 3600 on ttlSeconds. - revokeDevice says it also closes the refresh stream. --- openapi.yaml | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/openapi.yaml b/openapi.yaml index 22ab338..9d07e0d 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -614,7 +614,12 @@ paths: post: description: "Returns as soon as the command is queued; delivery and execution\ \ are reported asynchronously over the agent websocket. The permission required\ - \ depends on the command kind: board:command:benign, :disruptive, or :inspect." + \ depends on the command kind: board:command:benign, :disruptive, or :inspect.\ + \ ttlSeconds is capped per kind (10 minutes for kiosk.restart, system.reboot\ + \ and update.install_now; 15 for chrome.screenshot and logs.tail; an hour\ + \ for chrome.reload and config.refresh), deadlineMs at 15 minutes. Only logs.tail\ + \ takes a payload, {\"lines\": 1..500}; for the others it must be absent,\ + \ null or {}." operationId: issueDeviceCommand parameters: - in: path @@ -636,6 +641,13 @@ paths: schema: $ref: "#/components/schemas/CommandIssuedResponse" description: Command accepted and queued for delivery + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/MessageResponse" + description: "Unknown kind, a payload the kind does not take, or a deadline\ + \ or time-to-live over its limit" "403": content: application/json: @@ -733,8 +745,8 @@ paths: - device-admin-controller /api/admin/board/devices/{deviceId}/revoke: post: - description: "Closes any live agent session. Idempotent: re-revoking an already\ - \ revoked device is a no-op." + description: "Closes any live agent session and refresh stream. Idempotent:\ + \ re-revoking an already revoked device is a no-op." operationId: revokeDevice parameters: - in: path @@ -3906,6 +3918,7 @@ components: deadlineMs: type: integer format: int32 + maximum: 900000 minimum: 0 kind: type: string @@ -3916,6 +3929,7 @@ components: ttlSeconds: type: integer format: int32 + maximum: 3600 minimum: 0 required: - kind From 6d5189054ae94c3c71f7f3e097c428191668e97c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 04:52:56 +0000 Subject: [PATCH 7/7] Drop the refresh-stream signature check and revoke hook The refresh stream is being removed in favour of a content-changed message on the agent WebSocket. This reverts commits c18275b and 7bad652. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YY5BHXmNUhs48eubkKCNuE --- .../lensbridge/config/WebSocketConfig.java | 8 +- .../controller/DeviceAdminController.java | 5 +- .../handler/BoardStreamHandler.java | 103 ++----- .../BoardStreamHandshakeInterceptor.java | 154 ----------- .../http/DeviceRequestAuthenticator.java | 9 +- .../resources/application.properties.example | 6 - .../config/WebSocketConfigTest.java | 22 +- ...eviceAdminControllerOfflineBundleTest.java | 3 - .../controller/DeviceAdminControllerTest.java | 9 +- .../handler/BoardStreamHandlerTest.java | 123 +-------- .../BoardStreamHandshakeInterceptorTest.java | 258 ------------------ 11 files changed, 37 insertions(+), 663 deletions(-) delete mode 100644 src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptor.java delete mode 100644 src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptorTest.java diff --git a/src/main/java/com/ibrasoft/lensbridge/config/WebSocketConfig.java b/src/main/java/com/ibrasoft/lensbridge/config/WebSocketConfig.java index eb08ae9..a2469c0 100644 --- a/src/main/java/com/ibrasoft/lensbridge/config/WebSocketConfig.java +++ b/src/main/java/com/ibrasoft/lensbridge/config/WebSocketConfig.java @@ -10,7 +10,6 @@ import com.ibrasoft.lensbridge.handler.AgentWebSocketHandler; import com.ibrasoft.lensbridge.handler.BoardStreamHandler; -import com.ibrasoft.lensbridge.handler.BoardStreamHandshakeInterceptor; import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration; import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; @@ -19,7 +18,6 @@ public class WebSocketConfig implements WebSocketConfigurer { private final BoardStreamHandler boardStreamHandler; - private final BoardStreamHandshakeInterceptor boardStreamHandshakeInterceptor; private final AgentWebSocketHandler agentWebSocketHandler; @Value("${frontend.baseurl}") @@ -29,19 +27,15 @@ public class WebSocketConfig implements WebSocketConfigurer { String musallahBoardBaseUrl; public WebSocketConfig(BoardStreamHandler boardStreamHandler, - BoardStreamHandshakeInterceptor boardStreamHandshakeInterceptor, AgentWebSocketHandler agentWebSocketHandler) { this.boardStreamHandler = boardStreamHandler; - this.boardStreamHandshakeInterceptor = boardStreamHandshakeInterceptor; this.agentWebSocketHandler = agentWebSocketHandler; } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { - // Board agents connect here. The upgrade is device-signed (X-MB-* headers), checked by - // the interceptor; older agents only name themselves with ?deviceId=. + // Path is the deployed kiosk's; boards scope themselves with ?deviceId=. registry.addHandler(boardStreamHandler, "/api/refresh-musallahboard") - .addInterceptors(boardStreamHandshakeInterceptor) .setAllowedOrigins(frontendBaseUrl, musallahBoardBaseUrl); // Agents authenticate per-frame inside the channel; the WS upgrade itself is open. diff --git a/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java b/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java index 3402d29..40aabe0 100644 --- a/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java +++ b/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java @@ -8,7 +8,6 @@ import com.ibrasoft.lensbridge.dto.board.response.DeviceSummary; import com.ibrasoft.lensbridge.dto.board.response.IssueEnrollmentTokenResponse; 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.auth.Permission; import com.ibrasoft.lensbridge.model.board.Device; @@ -70,7 +69,6 @@ public class DeviceAdminController { private final AgentSessionRegistry sessionRegistry; private final AdminAuditService auditService; private final OfflineBundleService offlineBundleService; - private final BoardStreamHandler boardStream; @Operation(operationId = "listDevices", summary = "List every enrolled board device") @GetMapping @@ -128,7 +126,7 @@ public ResponseEntity issueEnrollmentToken( @Operation(operationId = "revokeDevice", summary = "Revoke a device's enrollment", - 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.") @ApiResponses({ @ApiResponse(responseCode = "200", description = "Device revoked"), @ApiResponse(responseCode = "404", description = "No device with that id", @@ -148,7 +146,6 @@ public ResponseEntity revoke(@PathVariable UUID deviceId, d.setRevokedAt(Instant.now()); deviceRepository.save(d); sessionRegistry.closeIfPresent(deviceId, CloseStatus.POLICY_VIOLATION.withReason("device_revoked")); - boardStream.disconnect(deviceId); log.warn("Device {} revoked by {}", deviceId, getCurrentUserEmail()); auditService.logAuditEvent(getCurrentUserEmail(), AuditAction.REVOKE_DEVICE, diff --git a/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandler.java b/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandler.java index 2a25667..57cfe5a 100644 --- a/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandler.java +++ b/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandler.java @@ -14,7 +14,6 @@ import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator; import org.springframework.web.socket.handler.TextWebSocketHandler; -import java.net.URI; import java.time.Instant; import java.util.LinkedHashMap; import java.util.Map; @@ -23,22 +22,14 @@ import java.util.concurrent.ConcurrentHashMap; /** - * Push channel for board agents: tells a board its content or config changed, so the agent - * syncs content ten seconds later instead of waiting for its 30-minute schedule (agent - * {@code docs/architecture.md}, section 9.1). A missed push only costs that wait. + * 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. *

- * Every board on this channel is an enrolled, unrevoked device; there is no anonymous or - * pre-enrollment state here. Who the device is comes from the upgrade request: - *

    - *
  • Signed: {@link BoardStreamHandshakeInterceptor} verified the device's - * {@code X-MB-*} signature and recorded the device it proved.
  • - *
  • Unsigned, from an agent that predates signing, and only while - * {@code musallahboard.board-stream.require-signature} is false: the device named by - * {@code ?deviceId=}. Anyone who knows the id can make that claim, so an unsigned - * connection never displaces a signed one for the same device.
  • - *
- * Revoking a device closes its connection here ({@link #disconnect(UUID)}), as it does the - * agent's own socket. */ @Component @RequiredArgsConstructor @@ -50,8 +41,6 @@ public class BoardStreamHandler extends TextWebSocketHandler { 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"); - /** An unsigned connection for a device that already holds a signed one. */ - static final CloseStatus CLOSE_SIGNED_SESSION_ACTIVE = new CloseStatus(4004, "signed_session_active"); /** * A push that has been stuck this long means the board has stopped reading; the decorator @@ -70,10 +59,9 @@ public class BoardStreamHandler extends TextWebSocketHandler { private final DeviceRepository deviceRepository; /** - * Live boards keyed by device. One session per device: a reconnecting agent can open its - * replacement before the server notices the old socket is gone, so the newcomer wins - * and the stale one is closed rather than left to accumulate, except that an unsigned - * newcomer never wins over a signed session. + * 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 @@ -81,17 +69,11 @@ public class BoardStreamHandler extends TextWebSocketHandler { * failure was being swallowed, so a board silently missed its refresh. The decorator * serialises the writes. */ - private final Map sessions = new ConcurrentHashMap<>(); - - /** A registered connection, and whether its upgrade carried a verified device signature. */ - private record Board(ConcurrentWebSocketSessionDecorator session, boolean signed) { - } + private final Map sessions = new ConcurrentHashMap<>(); @Override public void afterConnectionEstablished(@NonNull WebSocketSession session) { - UUID signedDevice = (UUID) session.getAttributes().get(BoardStreamHandshakeInterceptor.SIGNED_DEVICE_ATTR); - boolean signed = signedDevice != null; - UUID deviceId = signed ? signedDevice : parseDeviceId(session.getUri()); + UUID deviceId = parseDeviceId(session); if (deviceId == null) { close(session, CLOSE_NO_DEVICE); return; @@ -109,41 +91,16 @@ public void afterConnectionEstablished(@NonNull WebSocketSession session) { return; } + session.getAttributes().put(DEVICE_ATTR, deviceId); ConcurrentWebSocketSessionDecorator safe = new ConcurrentWebSocketSessionDecorator(session, SEND_TIME_LIMIT_MS, SEND_BUFFER_LIMIT_BYTES); - Board incoming = new Board(safe, signed); - Board[] displaced = {null}; - Board current = sessions.compute(deviceId, (id, existing) -> { - if (!signed && existing != null && existing.signed() && existing.session().isOpen()) { - return existing; - } - displaced[0] = existing; - return incoming; - }); - if (current != incoming) { - log.warn("Board stream refused unsigned session={} for device {}: it holds signed session {}", - session.getId(), deviceId, current.session().getId()); - close(session, CLOSE_SIGNED_SESSION_ACTIVE); - return; - } - session.getAttributes().put(DEVICE_ATTR, deviceId); - if (displaced[0] != null) { + ConcurrentWebSocketSessionDecorator previous = sessions.put(deviceId, safe); + if (previous != null) { log.info("Board stream device {} superseded session {} with {}", - deviceId, displaced[0].session().getId(), session.getId()); - close(displaced[0].session(), CLOSE_SUPERSEDED); + deviceId, previous.getId(), session.getId()); + close(previous, CLOSE_SUPERSEDED); } - log.info("Board stream connected: session={} device={} signed={}", session.getId(), deviceId, signed); - } - - /** - * Closes the device's connection, if it has one, for a revoke. Its reconnect is refused: - * a revoked device fails both the signature check and the enrollment check. - */ - public void disconnect(UUID deviceId) { - Board board = sessions.remove(deviceId); - if (board == null) return; - log.info("Board stream closing session={} device={}: device revoked", board.session().getId(), deviceId); - close(board.session(), CLOSE_REVOKED); + log.info("Board stream connected: session={} device={}", session.getId(), deviceId); } @Override @@ -153,7 +110,7 @@ public void afterConnectionClosed(@NonNull WebSocketSession session, @NonNull Cl // 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.session().getDelegate() == session ? null : current); + sessions.computeIfPresent(deviceId, (id, current) -> current.getDelegate() == session ? null : current); log.info("Board stream disconnected: session={} device={} status={}", session.getId(), deviceId, status); } @@ -185,30 +142,29 @@ private void push(String reason, UUID target) { if (json == null) return; if (target != null) { - Board board = sessions.get(target); - if (board == null) { - log.debug("Board stream reason={} device={} not connected — it will pick the change up on its next sync", + 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, board, json)) { + if (send(target, session, json)) { log.debug("Board stream push reason={} device={}", reason, target); } return; } int sent = 0; - for (Map.Entry entry : sessions.entrySet()) { + 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, Board board, String json) { - ConcurrentWebSocketSessionDecorator session = board.session(); + private boolean send(UUID deviceId, ConcurrentWebSocketSessionDecorator session, String json) { if (!session.isOpen()) { - sessions.remove(deviceId, board); + sessions.remove(deviceId, session); return false; } try { @@ -237,9 +193,8 @@ private String serialize(String reason, UUID target) { } } - /** The {@code deviceId} query parameter, or null when it is missing or not a UUID. */ - static UUID parseDeviceId(URI uri) { - String query = uri == null ? null : uri.getQuery(); + 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; @@ -247,7 +202,7 @@ static UUID parseDeviceId(URI uri) { try { return UUID.fromString(raw); } catch (IllegalArgumentException e) { - log.warn("Board stream upgrade sent a malformed deviceId"); + log.warn("Board stream session={} sent a malformed deviceId: {}", session.getId(), raw); return null; } } diff --git a/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptor.java b/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptor.java deleted file mode 100644 index ffd21bd..0000000 --- a/src/main/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptor.java +++ /dev/null @@ -1,154 +0,0 @@ -package com.ibrasoft.lensbridge.handler; - -import com.ibrasoft.lensbridge.exception.ApiResponseException; -import com.ibrasoft.lensbridge.model.board.Device; -import com.ibrasoft.lensbridge.service.agent.http.DeviceRequestAuthenticator; -import jakarta.servlet.http.HttpServletRequest; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; -import org.springframework.http.server.ServerHttpRequest; -import org.springframework.http.server.ServerHttpResponse; -import org.springframework.http.server.ServletServerHttpRequest; -import org.springframework.lang.NonNull; -import org.springframework.stereotype.Component; -import org.springframework.web.socket.WebSocketHandler; -import org.springframework.web.socket.server.HandshakeInterceptor; - -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Authenticates the upgrade request of {@code /api/refresh-musallahboard} with the device's - * enrolled key, the same {@code X-MB-*} signature the agent puts on its HTTP requests - * ({@link DeviceRequestAuthenticator}, agent {@code docs/architecture.md} section 9.2): a - * {@code GET} of the path with an empty body. - *

- * The rules, during the staged rollout: - *

    - *
  • A signature that is present (any of the three headers) is always verified, and a bad - * one is always refused with 401. A {@code ?deviceId=} that names a different device is - * refused too: the query is not covered by the signature, so the header is what counts.
  • - *
  • Each accepted signed upgrade must carry a newer timestamp than the last one accepted for - * that device. The scheme itself accepts replays inside its five-minute window, which is - * harmless for idempotent reads but not here, where a replayed upgrade would take the - * board's place on its channel. The agent signs every dial afresh.
  • - *
  • An unsigned upgrade (an agent that predates signing) is refused when - * {@code musallahboard.board-stream.require-signature} is true. While it is false it is - * accepted and logged, and {@link BoardStreamHandler} never lets it displace a signed - * connection for the same device.
  • - *
- * Turn the property on once the logs stop showing unsigned connections: then the whole fleet - * runs an agent that signs. - */ -@Component -@Slf4j -public class BoardStreamHandshakeInterceptor implements HandshakeInterceptor { - - /** Handshake attribute: the device the signature proved, when the upgrade was signed. */ - static final String SIGNED_DEVICE_ATTR = "board.signedDeviceId"; - - private static final byte[] NO_BODY = new byte[0]; - - private final DeviceRequestAuthenticator authenticator; - private final boolean requireSignature; - - /** Newest accepted timestamp per device, so a captured upgrade cannot be replayed. */ - private final Map lastTimestamp = new ConcurrentHashMap<>(); - - public BoardStreamHandshakeInterceptor( - DeviceRequestAuthenticator authenticator, - @Value("${musallahboard.board-stream.require-signature:false}") boolean requireSignature) { - this.authenticator = authenticator; - this.requireSignature = requireSignature; - if (!requireSignature) { - log.info("Board stream accepts unsigned upgrades from older agents " - + "(musallahboard.board-stream.require-signature=false)"); - } - } - - @Override - public boolean beforeHandshake(@NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response, - @NonNull WebSocketHandler wsHandler, @NonNull Map attributes) { - if (!(request instanceof ServletServerHttpRequest servletRequest)) { - response.setStatusCode(HttpStatus.BAD_REQUEST); - return false; - } - HttpServletRequest http = servletRequest.getServletRequest(); - UUID named = BoardStreamHandler.parseDeviceId(request.getURI()); - - if (!hasSignatureHeader(http)) { - if (requireSignature) { - log.warn("Board stream refused an unsigned upgrade for device {} ({})", named, userAgent(http)); - response.setStatusCode(HttpStatus.UNAUTHORIZED); - return false; - } - // Logged every time on purpose: when these stop, the fleet has migrated and - // require-signature can be turned on. - log.warn("Board stream accepted an unsigned upgrade for device {} ({}); " - + "the board needs an agent that signs it before " - + "musallahboard.board-stream.require-signature is turned on", named, userAgent(http)); - return true; - } - - Device device; - try { - device = authenticator.authenticate(http, NO_BODY); - } catch (ApiResponseException e) { - // The authenticator has already logged which check failed. - response.setStatusCode(HttpStatus.UNAUTHORIZED); - return false; - } - UUID deviceId = device.getId(); - if (named != null && !named.equals(deviceId)) { - log.warn("Board stream refused a signed upgrade for device {} that names device {} in its query", - deviceId, named); - response.setStatusCode(HttpStatus.BAD_REQUEST); - return false; - } - // Already parsed and range-checked by the authenticator. - long timestamp = Long.parseLong(http.getHeader(DeviceRequestAuthenticator.TIMESTAMP_HEADER).trim()); - if (!advance(deviceId, timestamp)) { - log.warn("Board stream refused a replayed upgrade for device {} (timestamp {} not newer than the last)", - deviceId, timestamp); - response.setStatusCode(HttpStatus.UNAUTHORIZED); - return false; - } - attributes.put(SIGNED_DEVICE_ATTR, deviceId); - return true; - } - - @Override - public void afterHandshake(@NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response, - @NonNull WebSocketHandler wsHandler, Exception exception) { - // Nothing to do: the handler registers the session once it is established. - } - - /** True, and remembered, when {@code timestamp} is newer than any accepted for the device. */ - private boolean advance(UUID deviceId, long timestamp) { - boolean[] fresh = {false}; - lastTimestamp.compute(deviceId, (id, previous) -> { - if (previous == null || timestamp > previous) { - fresh[0] = true; - return timestamp; - } - return previous; - }); - return fresh[0]; - } - - private static boolean hasSignatureHeader(HttpServletRequest request) { - return request.getHeader(DeviceRequestAuthenticator.DEVICE_ID_HEADER) != null - || request.getHeader(DeviceRequestAuthenticator.TIMESTAMP_HEADER) != null - || request.getHeader(DeviceRequestAuthenticator.SIGNATURE_HEADER) != null; - } - - private static String userAgent(HttpServletRequest request) { - String ua = request.getHeader("User-Agent"); - if (ua == null) return "no User-Agent"; - // Logged verbatim otherwise: keep a hostile value to one short line. - String cleaned = ua.replaceAll("[\\p{Cntrl}]", "?"); - return cleaned.length() > 80 ? cleaned.substring(0, 80) + "..." : cleaned; - } -} diff --git a/src/main/java/com/ibrasoft/lensbridge/service/agent/http/DeviceRequestAuthenticator.java b/src/main/java/com/ibrasoft/lensbridge/service/agent/http/DeviceRequestAuthenticator.java index be2f787..4365ea2 100644 --- a/src/main/java/com/ibrasoft/lensbridge/service/agent/http/DeviceRequestAuthenticator.java +++ b/src/main/java/com/ibrasoft/lensbridge/service/agent/http/DeviceRequestAuthenticator.java @@ -47,11 +47,7 @@ * {@code permitAll} in {@code WebSecurityConfig}; this is their authentication. *

* Replays inside the five-minute window are accepted. That is by design: the endpoints this - * guards are idempotent reads, so a replay only fetches the same content again. The query - * string is not signed either, so nothing in it may matter to an authenticated endpoint. The - * board refresh stream is the exception on both counts and checks them itself - * ({@code BoardStreamHandshakeInterceptor}): a replayed upgrade would displace the board, and - * its {@code ?deviceId=} must agree with the signed device. + * guards are idempotent reads, so a replay only fetches the same content again. */ @Component @Slf4j @@ -75,8 +71,7 @@ public DeviceRequestAuthenticator(DeviceRepository deviceRepository, Ed25519Veri this(deviceRepository, verifier, Clock.systemUTC()); } - /** With a fixed clock, for tests that check signatures made at a known time. */ - public DeviceRequestAuthenticator(DeviceRepository deviceRepository, Ed25519Verifier verifier, Clock clock) { + DeviceRequestAuthenticator(DeviceRepository deviceRepository, Ed25519Verifier verifier, Clock clock) { this.deviceRepository = deviceRepository; this.verifier = verifier; this.clock = clock; diff --git a/src/main/resources/application.properties.example b/src/main/resources/application.properties.example index a217712..967ac2c 100644 --- a/src/main/resources/application.properties.example +++ b/src/main/resources/application.properties.example @@ -55,12 +55,6 @@ musallahboard.agent.sweepIntervalMs=5000 # 0 or less keeps them forever. musallahboard.telemetry.retentionDays=14 musallahboard.telemetry.pruneCron=0 30 3 * * * -# Board refresh stream (/api/refresh-musallahboard). Agents that sign its upgrade with the device -# key (X-MB-* headers) are always verified, and a bad signature is always refused. While this is -# false, agents that predate signing may still connect unsigned (logged as "Board stream accepted -# an unsigned upgrade ..."), but can never take over from a signed connection. Set it to true -# once those log lines stop: every board then runs an agent that signs. -musallahboard.board-stream.require-signature=false # Raises the WebSocket text buffer to fit a screenshot result from the agent (base64, up to # 8 MiB). On by default; set false only if the container already configures this. lensbridge.websocket.container-customizer.enabled=true diff --git a/src/test/java/com/ibrasoft/lensbridge/config/WebSocketConfigTest.java b/src/test/java/com/ibrasoft/lensbridge/config/WebSocketConfigTest.java index 2813b97..12195b6 100644 --- a/src/test/java/com/ibrasoft/lensbridge/config/WebSocketConfigTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/config/WebSocketConfigTest.java @@ -2,37 +2,17 @@ import com.ibrasoft.lensbridge.handler.AgentWebSocketHandler; import com.ibrasoft.lensbridge.handler.BoardStreamHandler; -import com.ibrasoft.lensbridge.handler.BoardStreamHandshakeInterceptor; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; -import org.springframework.web.socket.config.annotation.ServletWebSocketHandlerRegistry; import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; -import org.springframework.web.socket.server.support.WebSocketHttpRequestHandler; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; class WebSocketConfigTest { - private final BoardStreamHandshakeInterceptor boardStreamInterceptor = mock(BoardStreamHandshakeInterceptor.class); private final WebSocketConfig config = - new WebSocketConfig(mock(BoardStreamHandler.class), boardStreamInterceptor, - mock(AgentWebSocketHandler.class)); - - /** Without the interceptor the refresh stream would accept anyone who knows a device id. */ - @Test - void boardStreamUpgradeGoesThroughTheSignatureInterceptor() { - config.frontendBaseUrl = "https://admin.example"; - config.musallahBoardBaseUrl = "https://board.example"; - ServletWebSocketHandlerRegistry registry = new ServletWebSocketHandlerRegistry(); - config.registerWebSocketHandlers(registry); - - SimpleUrlHandlerMapping mapping = (SimpleUrlHandlerMapping) registry.getHandlerMapping(); - WebSocketHttpRequestHandler stream = - (WebSocketHttpRequestHandler) mapping.getUrlMap().get("/api/refresh-musallahboard"); - assertThat(stream.getHandshakeInterceptors()).contains(boardStreamInterceptor); - } + new WebSocketConfig(mock(BoardStreamHandler.class), 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/DeviceAdminControllerOfflineBundleTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerOfflineBundleTest.java index 91c3e16..c6bdbbc 100644 --- a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerOfflineBundleTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerOfflineBundleTest.java @@ -6,7 +6,6 @@ import com.ibrasoft.lensbridge.model.auth.Role; import com.ibrasoft.lensbridge.repository.sql.DeviceCommandRepository; import com.ibrasoft.lensbridge.repository.sql.DeviceRepository; -import com.ibrasoft.lensbridge.handler.BoardStreamHandler; import com.ibrasoft.lensbridge.service.AdminAuditService; import com.ibrasoft.lensbridge.service.UserService; import com.ibrasoft.lensbridge.service.agent.AgentSessionRegistry; @@ -71,8 +70,6 @@ class DeviceAdminControllerOfflineBundleTest { private AgentSessionRegistry sessionRegistry; @MockitoBean private AdminAuditService auditService; - @MockitoBean - private BoardStreamHandler boardStream; /** Needed by WebConfig's CurrentUserArgumentResolver; see BoardAdminControllerPermissionTest. */ @MockitoBean diff --git a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerTest.java b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerTest.java index bb1c4fd..f0629b9 100644 --- a/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/controller/DeviceAdminControllerTest.java @@ -1,7 +1,6 @@ package com.ibrasoft.lensbridge.controller; import com.fasterxml.jackson.databind.ObjectMapper; -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.Device; @@ -47,7 +46,6 @@ void revoke_closesRegisteredAgentSession() throws Exception { CommandDispatcher commandDispatcher = mock(CommandDispatcher.class); AgentSessionRegistry registry = new AgentSessionRegistry(mock(DeviceEventPublisher.class)); AdminAuditService auditService = mock(AdminAuditService.class); - BoardStreamHandler boardStream = mock(BoardStreamHandler.class); DeviceAdminController controller = new DeviceAdminController( enrollmentTokenService, @@ -57,8 +55,7 @@ void revoke_closesRegisteredAgentSession() throws Exception { new ObjectMapper(), registry, auditService, - mock(OfflineBundleService.class), - boardStream); + mock(OfflineBundleService.class)); UUID deviceId = UUID.randomUUID(); Device device = Device.builder() @@ -87,7 +84,6 @@ void revoke_closesRegisteredAgentSession() throws Exception { verify(transport).close(argThat(status -> status.getCode() == CloseStatus.POLICY_VIOLATION.getCode() && "device_revoked".equals(status.getReason()))); - verify(boardStream).disconnect(deviceId); verify(auditService).logAuditEvent( eq("root@example.com"), eq(AuditAction.REVOKE_DEVICE), eq("Device"), eq(deviceId), eq("10.0.0.1")); @@ -106,8 +102,7 @@ void revoke_isANoOpAndDoesNotReAuditWhenAlreadyRevoked() throws Exception { new ObjectMapper(), new AgentSessionRegistry(mock(DeviceEventPublisher.class)), auditService, - mock(OfflineBundleService.class), - mock(BoardStreamHandler.class)); + mock(OfflineBundleService.class)); UUID deviceId = UUID.randomUUID(); Instant revokedAt = Instant.now().minusSeconds(3600); diff --git a/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandlerTest.java b/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandlerTest.java index 36575b7..be84aaa 100644 --- a/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandlerTest.java +++ b/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandlerTest.java @@ -15,7 +15,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -227,117 +226,6 @@ void closeCallbackOfTheRawSessionStillRemovesItsWrapper() throws Exception { assertThat(s.sent).isEmpty(); } - // ── signed and unsigned connections (staged rollout) ────────────────── - - @Test - void signedConnectionTakesTheDeviceFromTheVerifiedSignatureNotTheQuery() throws Exception { - UUID device = enrolled(); - Session s = connectSigned(device, null); - - handler.configChanged(device); - - assertThat(s.closedWith).isNull(); - assertThat(s.sent).hasSize(1); - } - - @Test - void unsignedConnectionCannotEvictASignedOne() throws Exception { - UUID device = enrolled(); - Session board = connectSigned(device, "deviceId=" + device); - Session intruder = connect(device); - - assertThat(intruder.closedWith.getCode()).isEqualTo(4004); - assertThat(board.closedWith).isNull(); - handler.configChanged(device); - assertThat(board.sent).hasSize(1); - assertThat(intruder.sent).isEmpty(); - - // The refused session's close callback must not unregister the board. - handler.afterConnectionClosed(intruder.ws, CloseStatus.NORMAL); - handler.configChanged(device); - assertThat(board.sent).hasSize(2); - } - - @Test - void signedConnectionSupersedesAnUnsignedOne() throws Exception { - UUID device = enrolled(); - Session squatter = connect(device); - Session board = connectSigned(device, "deviceId=" + device); - - assertThat(squatter.closedWith).isEqualTo(BoardStreamHandler.CLOSE_SUPERSEDED); - handler.configChanged(device); - assertThat(board.sent).hasSize(1); - } - - @Test - void signedReconnectSupersedesTheBoardsOwnStaleSignedSession() throws Exception { - UUID device = enrolled(); - Session stale = connectSigned(device, null); - Session fresh = connectSigned(device, null); - - assertThat(stale.closedWith).isEqualTo(BoardStreamHandler.CLOSE_SUPERSEDED); - handler.configChanged(device); - assertThat(fresh.sent).hasSize(1); - } - - /** A legacy board reconnecting replaces its own earlier unsigned socket, as before. */ - @Test - void unsignedReconnectStillSupersedesAnUnsignedSession() throws Exception { - UUID device = enrolled(); - Session first = connect(device); - Session second = connect(device); - - assertThat(first.closedWith).isEqualTo(BoardStreamHandler.CLOSE_SUPERSEDED); - assertThat(second.closedWith).isNull(); - } - - @Test - void unsignedConnectionMayRegisterOnceTheSignedSessionHasGone() throws Exception { - UUID device = enrolled(); - Session board = connectSigned(device, null); - board.open = false; // dropped, close callback not yet delivered - Session legacy = connect(device); - - assertThat(legacy.closedWith).isNull(); - handler.configChanged(device); - assertThat(legacy.sent).hasSize(1); - } - - @Test - void signedConnectionForARevokedDeviceIsStillRefused() throws Exception { - UUID id = UUID.randomUUID(); - Device revoked = Device.builder().id(id).displayName("d").build(); - revoked.setRevokedAt(Instant.now()); - when(deviceRepository.findById(id)).thenReturn(Optional.of(revoked)); - - Session s = connectSigned(id, null); - - assertThat(s.closedWith.getCode()).isEqualTo(4003); - } - - // ── revoke ──────────────────────────────────────────────────────────── - - @Test - void disconnectClosesTheDevicesSessionAsRevokedAndStopsDelivery() throws Exception { - UUID device = enrolled(); - Session mine = connectSigned(device, null); - Session other = connect(enrolled()); - - handler.disconnect(device); - - assertThat(mine.closedWith).isEqualTo(BoardStreamHandler.CLOSE_REVOKED); - assertThat(other.closedWith).isNull(); - mine.open = true; // a leftover registration would write to it - handler.contentChanged("posters"); - assertThat(mine.sent).isEmpty(); - assertThat(other.sent).hasSize(1); - } - - @Test - void disconnectOfABoardWithNoSessionIsANoOp() { - handler.disconnect(UUID.randomUUID()); - } - // ── helpers ─────────────────────────────────────────────────────────── /** Registers a device the repository will vouch for, and returns its id. */ @@ -358,19 +246,10 @@ private Session connectWithQuery(String query) throws Exception { return session; } - /** A connection whose upgrade signature {@link BoardStreamHandshakeInterceptor} verified. */ - private Session connectSigned(UUID deviceId, String query) throws Exception { - Session session = new Session(query); - session.attributes.put(BoardStreamHandshakeInterceptor.SIGNED_DEVICE_ATTR, deviceId); - 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<>(); - final Map attributes = new HashMap<>(); boolean open = true; CloseStatus closedWith; @@ -379,7 +258,7 @@ private static class Session { 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(attributes); + when(ws.getAttributes()).thenReturn(new HashMap<>()); doAnswer(inv -> { sent.add(((TextMessage) inv.getArgument(0)).getPayload()); return null; diff --git a/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptorTest.java b/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptorTest.java deleted file mode 100644 index 1283eab..0000000 --- a/src/test/java/com/ibrasoft/lensbridge/handler/BoardStreamHandshakeInterceptorTest.java +++ /dev/null @@ -1,258 +0,0 @@ -package com.ibrasoft.lensbridge.handler; - -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.agent.Ed25519TestUtil; -import com.ibrasoft.lensbridge.service.agent.handshake.Ed25519Verifier; -import com.ibrasoft.lensbridge.service.agent.http.DeviceRequestAuthenticator; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.http.server.ServletServerHttpRequest; -import org.springframework.http.server.ServletServerHttpResponse; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.web.socket.WebSocketHandler; - -import java.security.KeyPair; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.Base64; -import java.util.HashMap; -import java.util.Map; -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.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * The upgrade of {@code /api/refresh-musallahboard}: device signatures are verified with the - * real {@link DeviceRequestAuthenticator}, and unsigned upgrades are let through only while - * {@code musallahboard.board-stream.require-signature} is off. - */ -class BoardStreamHandshakeInterceptorTest { - - private static final String PATH = "/api/refresh-musallahboard"; - private static final UUID DEVICE_ID = UUID.fromString("3f2a1b4c-5d6e-4f70-8a9b-0c1d2e3f4a5b"); - - private final DeviceRepository deviceRepository = mock(DeviceRepository.class); - private final DeviceRequestAuthenticator authenticator = - new DeviceRequestAuthenticator(deviceRepository, new Ed25519Verifier()); - private KeyPair keys; - private Device device; - - @BeforeEach - void setUp() { - keys = Ed25519TestUtil.generate(); - device = Device.builder().id(DEVICE_ID).displayName("Lobby board").audience(Audience.BOTH) - .publicKey(Ed25519TestUtil.rawPublicKey(keys.getPublic())).build(); - when(deviceRepository.findById(any())).thenReturn(Optional.empty()); - when(deviceRepository.findById(DEVICE_ID)).thenReturn(Optional.of(device)); - } - - // ── signed upgrades ─────────────────────────────────────────────────── - - @Test - void validSignatureIsAcceptedAndRecordsTheDevice() { - Result r = handshake(interceptor(false), signed("deviceId=" + DEVICE_ID, now())); - - assertThat(r.accepted).isTrue(); - assertThat(r.attributes).containsEntry(BoardStreamHandshakeInterceptor.SIGNED_DEVICE_ATTR, DEVICE_ID); - } - - @Test - void signedUpgradeNeedsNoQuery() { - Result r = handshake(interceptor(true), signed(null, now())); - - assertThat(r.accepted).isTrue(); - assertThat(r.attributes).containsEntry(BoardStreamHandshakeInterceptor.SIGNED_DEVICE_ATTR, DEVICE_ID); - } - - /** A present signature is checked whatever the flag says: being lenient is for its absence only. */ - @Test - void badSignatureIsRefusedEvenWhileUnsignedUpgradesAreAllowed() { - MockHttpServletRequest request = signed("deviceId=" + DEVICE_ID, now()); - byte[] other = Ed25519TestUtil.sign(Ed25519TestUtil.generate().getPrivate(), new byte[]{1}); - request.removeHeader(DeviceRequestAuthenticator.SIGNATURE_HEADER); - request.addHeader(DeviceRequestAuthenticator.SIGNATURE_HEADER, Base64.getEncoder().encodeToString(other)); - - Result r = handshake(interceptor(false), request); - - assertThat(r.accepted).isFalse(); - assertThat(r.status).isEqualTo(401); - assertThat(r.attributes).isEmpty(); - } - - @Test - void partialSignatureHeadersCountAsASignatureAndAreRefused() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); - request.setQueryString("deviceId=" + DEVICE_ID); - request.addHeader(DeviceRequestAuthenticator.DEVICE_ID_HEADER, DEVICE_ID.toString()); - - Result r = handshake(interceptor(false), request); - - assertThat(r.accepted).isFalse(); - assertThat(r.status).isEqualTo(401); - } - - @Test - void signatureForAnotherPathIsRefused() { - long ts = now(); - MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); - sign(request, "/api/agent/weather", ts); - - assertThat(handshake(interceptor(false), request).status).isEqualTo(401); - } - - @Test - void staleTimestampIsRefused() { - Result r = handshake(interceptor(false), signed(null, now() - 6 * 60_000)); - - assertThat(r.accepted).isFalse(); - assertThat(r.status).isEqualTo(401); - } - - @Test - void revokedDeviceIsRefused() { - device.setRevokedAt(Instant.now()); - - assertThat(handshake(interceptor(false), signed(null, now())).status).isEqualTo(401); - } - - /** The query is not signed, so it may not name a different device than the signature. */ - @Test - void queryNamingAnotherDeviceIsRefused() { - Result r = handshake(interceptor(false), signed("deviceId=" + UUID.randomUUID(), now())); - - assertThat(r.accepted).isFalse(); - assertThat(r.status).isEqualTo(400); - } - - /** Replaying a captured upgrade inside the five-minute window would evict the board. */ - @Test - void replayedUpgradeIsRefused() { - BoardStreamHandshakeInterceptor interceptor = interceptor(false); - long ts = now(); - - assertThat(handshake(interceptor, signed(null, ts)).accepted).isTrue(); - Result replay = handshake(interceptor, signed(null, ts)); - assertThat(replay.accepted).isFalse(); - assertThat(replay.status).isEqualTo(401); - assertThat(handshake(interceptor, signed(null, ts - 1)).accepted).isFalse(); - - assertThat(handshake(interceptor, signed(null, ts + 1)).accepted).isTrue(); - } - - @Test - void refusedSignatureDoesNotAdvanceTheReplayGuard() { - BoardStreamHandshakeInterceptor interceptor = interceptor(false); - long ts = now(); - MockHttpServletRequest forged = signed(null, ts); - forged.removeHeader(DeviceRequestAuthenticator.SIGNATURE_HEADER); - forged.addHeader(DeviceRequestAuthenticator.SIGNATURE_HEADER, - Base64.getEncoder().encodeToString(new byte[64])); - - assertThat(handshake(interceptor, forged).accepted).isFalse(); - assertThat(handshake(interceptor, signed(null, ts)).accepted).isTrue(); - } - - // ── unsigned upgrades ───────────────────────────────────────────────── - - @Test - void unsignedUpgradeIsAcceptedWhileSignaturesAreNotRequired() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); - request.setQueryString("deviceId=" + DEVICE_ID); - - Result r = handshake(interceptor(false), request); - - assertThat(r.accepted).isTrue(); - // No proven device: the handler treats it as an unsigned claim. - assertThat(r.attributes).doesNotContainKey(BoardStreamHandshakeInterceptor.SIGNED_DEVICE_ATTR); - } - - @Test - void unsignedUpgradeIsRefusedOnceSignaturesAreRequired() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); - request.setQueryString("deviceId=" + DEVICE_ID); - - Result r = handshake(interceptor(true), request); - - assertThat(r.accepted).isFalse(); - assertThat(r.status).isEqualTo(401); - } - - // ── agreement with the agent ────────────────────────────────────────── - - /** - * The same vector as the agent's {@code TestRefreshHeaderSignedGolden} - * (internal/boardsync/boardsync_test.go): its device key is the Ed25519 seed of 32 bytes - * of 7, and the signature below is exactly what the agent sends on the refresh upgrade at - * that time. If either side changes the signed message, one of the two tests fails. - */ - @Test - void agentGoldenVectorVerifies() { - long ts = 1790258531123L; - Device agentDevice = Device.builder().id(DEVICE_ID).displayName("golden").audience(Audience.BOTH) - .publicKey(Base64.getDecoder().decode("6kpsY+KcUgq+9VB7Ey7F+ZVHdq6+vnuSQh7qaRRG0iw=")) - .build(); - DeviceRepository repository = mock(DeviceRepository.class); - when(repository.findById(DEVICE_ID)).thenReturn(Optional.of(agentDevice)); - DeviceRequestAuthenticator fixedClock = new DeviceRequestAuthenticator(repository, new Ed25519Verifier(), - Clock.fixed(Instant.ofEpochMilli(ts), ZoneOffset.UTC)); - BoardStreamHandshakeInterceptor interceptor = new BoardStreamHandshakeInterceptor(fixedClock, true); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); - request.setQueryString("deviceId=" + DEVICE_ID); - request.addHeader("User-Agent", "musallahboard-agent/0.3.0"); - request.addHeader(DeviceRequestAuthenticator.DEVICE_ID_HEADER, DEVICE_ID.toString()); - request.addHeader(DeviceRequestAuthenticator.TIMESTAMP_HEADER, Long.toString(ts)); - request.addHeader(DeviceRequestAuthenticator.SIGNATURE_HEADER, - "TGTiOMTSt8N/7ad06yMvmWo9a68Yz01LNGYnDOPGfedeiPTPjC9hqtKa/yLAOa7rXlDa5UfKTpmI28tdSME4Dg=="); - - Result r = handshake(interceptor, request); - - assertThat(r.accepted).isTrue(); - assertThat(r.attributes).containsEntry(BoardStreamHandshakeInterceptor.SIGNED_DEVICE_ATTR, DEVICE_ID); - } - - // ── helpers ─────────────────────────────────────────────────────────── - - private BoardStreamHandshakeInterceptor interceptor(boolean requireSignature) { - return new BoardStreamHandshakeInterceptor(authenticator, requireSignature); - } - - private static long now() { - return System.currentTimeMillis(); - } - - /** An upgrade signed exactly as the agent signs it: GET, the path, an empty body. */ - private MockHttpServletRequest signed(String query, long timestamp) { - MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); - request.setQueryString(query); - sign(request, PATH, timestamp); - return request; - } - - private void sign(MockHttpServletRequest request, String signedPath, long timestamp) { - byte[] message = DeviceRequestAuthenticator.message("GET", signedPath, DEVICE_ID, timestamp, new byte[0]); - request.addHeader(DeviceRequestAuthenticator.DEVICE_ID_HEADER, DEVICE_ID.toString()); - request.addHeader(DeviceRequestAuthenticator.TIMESTAMP_HEADER, Long.toString(timestamp)); - request.addHeader(DeviceRequestAuthenticator.SIGNATURE_HEADER, - Base64.getEncoder().encodeToString(Ed25519TestUtil.sign(keys.getPrivate(), message))); - } - - private static Result handshake(BoardStreamHandshakeInterceptor interceptor, MockHttpServletRequest request) { - MockHttpServletResponse response = new MockHttpServletResponse(); - Map attributes = new HashMap<>(); - boolean accepted = interceptor.beforeHandshake(new ServletServerHttpRequest(request), - new ServletServerHttpResponse(response), mock(WebSocketHandler.class), attributes); - return new Result(accepted, response.getStatus(), attributes); - } - - private record Result(boolean accepted, int status, Map attributes) { - } -}