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; 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 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/controller/DeviceAdminController.java b/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java index 38f8c4e..40aabe0 100644 --- a/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java +++ b/src/main/java/com/ibrasoft/lensbridge/controller/DeviceAdminController.java @@ -164,9 +164,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/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/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/main/resources/application.properties.example b/src/main/resources/application.properties.example index e420971..967ac2c 100644 --- a/src/main/resources/application.properties.example +++ b/src/main/resources/application.properties.example @@ -135,14 +135,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/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/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; + } + } +} 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() {