Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 5 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
19 changes: 16 additions & 3 deletions docker/nginx/nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down Expand Up @@ -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;

Expand Down
20 changes: 17 additions & 3 deletions openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -3906,6 +3918,7 @@ components:
deadlineMs:
type: integer
format: int32
maximum: 900000
minimum: 0
kind:
type: string
Expand All @@ -3916,6 +3929,7 @@ components:
ttlSeconds:
type: integer
format: int32
maximum: 3600
minimum: 0
required:
- kind
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ public class AgentEnrollmentController {
@PostMapping("/enroll")
public ResponseEntity<AgentEnrollResponse> 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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,16 @@ public ResponseEntity<DeviceSummary> 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)))
})
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -10,19 +11,33 @@
* <p>
* {@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.
* <p>
* {@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;
}
Original file line number Diff line number Diff line change
@@ -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}).
* <p>
* 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.
* <p>
* 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}. */
Expand All @@ -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<CommandKind> from(String wireName) {
if (wireName == null) return Optional.empty();
return Arrays.stream(values())
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
* <p>
* 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<String> 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;
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
Loading
Loading