100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Harden Manager image uploads and global admin endpoints
Wouter Born092dd234bbf5
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex c153ca457..8953bda16 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -72,6 +72,7 @@ suncalc = "3.11"swagger = "2.2.53"swaggerUi = "5.32.11"testLogger = "4.0.0"+twelveMonkeys = "3.15.2"typescriptGenerator = "4.1.1"undertow = "2.3.26.Final"uuidGenerator = "5.2.0"@@ -190,6 +191,7 @@ swaggerAnnotations = { module = "io.swagger.core.v3:swagger-annotations", versioswaggerJaxrs2Jakarta = { module = "io.swagger.core.v3:swagger-jaxrs2-jakarta", version.ref = "swagger" }swaggerUi = { module = "org.webjars:swagger-ui", version.ref = "swaggerUi" }sshdNetty = { module = "org.apache.sshd:sshd-netty", version.ref = "apacheSshd" }+twelveMonkeysImageIoBmp = { module = "com.twelvemonkeys.imageio:imageio-bmp", version.ref = "twelveMonkeys" }typescriptGeneratorCore = { module = "cz.habarta.typescript-generator:typescript-generator-core", version.ref = "typescriptGenerator" }undertowCore = { module = "io.undertow:undertow-core", version.ref = "undertow" }undertowWebsocketsJsr = { module = "io.undertow:undertow-websockets-jsr", version.ref = "undertow" }diff --git a/manager/build.gradle b/manager/build.gradleindex c980838d5..4c3d6d3d2 100644--- a/manager/build.gradle+++ b/manager/build.gradle@@ -37,6 +37,7 @@ dependencies {implementation libs.angusMailimplementation libs.swaggerJaxrs2Jakartaimplementation libs.camelUndertow+ implementation libs.twelveMonkeysImageIoBmp// Indirect dep from org.apache.activemq:artemis-mqtt-protocolapi(libs.nettyCodecMqtt) {diff --git a/manager/src/main/java/org/openremote/manager/app/ConfigurationResourceImpl.java b/manager/src/main/java/org/openremote/manager/app/ConfigurationResourceImpl.javaindex 8bd014881..1ef267522 100644--- a/manager/src/main/java/org/openremote/manager/app/ConfigurationResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/app/ConfigurationResourceImpl.java@@ -18,12 +18,13 @@*/package org.openremote.manager.app;+import static org.openremote.manager.app.ConfigurationService.MANAGER_CONFIG_IMAGE_URL_PREFIX;++import jakarta.ws.rs.BadRequestException;+import jakarta.ws.rs.ForbiddenException;import jakarta.ws.rs.InternalServerErrorException;+import jakarta.ws.rs.core.MediaType;import jakarta.ws.rs.core.Response;-import java.io.*;-import java.nio.file.Files;-import java.nio.file.Path;-import java.util.NoSuchElementException;import java.util.logging.Logger;import org.openremote.container.timer.TimerService;import org.openremote.container.web.WebService;@@ -50,6 +51,10 @@ public class ConfigurationResourceImpl extends ManagerWebResource implements Con@Overridepublic ManagerAppConfig update(RequestParams requestParams, ManagerAppConfig managerConfiguration) {+ if (!isSuperUser()) {+ throw new ForbiddenException("Only super admin can update the manager configuration");+ }+try {this.configurationService.saveManagerConfig(managerConfiguration);} catch (Exception e) {@@ -60,22 +65,25 @@ public class ConfigurationResourceImpl extends ManagerWebResource implements Con}@Override- public String fileUpload(RequestParams requestParams, String path, FileInfo fileInfo) {+ public String imageUpload(RequestParams requestParams, String path, FileInfo fileInfo) {+ if (!isSuperUser()) {+ throw new ForbiddenException("Only super admin can upload images");+ }+try {- this.configurationService.saveManagerConfigImage(path, fileInfo);+ String storedPath = configurationService.saveManagerConfigImage(path, fileInfo);+ return MANAGER_CONFIG_IMAGE_URL_PREFIX + storedPath;+ } catch (IllegalArgumentException e) {+ LOG.warning(() -> "Image upload rejected for path '" + path + "': " + e.getMessage());+ throw new BadRequestException(+ Response.status(Response.Status.BAD_REQUEST)+ .type(MediaType.TEXT_PLAIN_TYPE)+ .entity(e.getMessage())+ .build());} catch (Exception e) {LOG.warning("Save image failed '" + path + "': " + e.getMessage());throw new InternalServerErrorException("Error storing image");}- Path managerConfigPath =- Path.of("/api")- .resolve("master")- .resolve("configuration")- .resolve("manager")- .resolve("image")- .resolve(path);-- return managerConfigPath.toString();}@Override@@ -86,20 +94,19 @@ public class ConfigurationResourceImpl extends ManagerWebResource implements Con@Overridepublic Object getManagerConfigImage(String fileName) {try {- File imageFile = configurationService.getManagerConfigImage(fileName).orElseThrow();- if (!imageFile.exists()) {- return Response.status(Response.Status.NOT_FOUND).build();- }-- String mimeType = Files.probeContentType(imageFile.toPath());- if (mimeType == null) {- mimeType = "application/octet-stream";+ var imageFile = configurationService.getManagerConfigImage(fileName);+ if (imageFile.isEmpty()) {+ return Response.status(Response.Status.NOT_FOUND).entity("Image not Found").build();}-- Response.ResponseBuilder response = Response.ok(imageFile, mimeType);- return response.build();- } catch (NoSuchElementException e) {- return Response.status(Response.Status.NOT_FOUND).entity("Image not Found").build();+ String mimeType = ImageUploadValidator.getMediaType(imageFile.get().getName());+ return Response.ok(imageFile.get(), mimeType)+ .header("X-Content-Type-Options", "nosniff")+ // Preserve embedded SVG styling while isolating documents and blocking active content.+ .header(+ "Content-Security-Policy",+ "sandbox; default-src 'none'; img-src data:; style-src 'unsafe-inline'; base-uri 'none'; form-action"+ + " 'none'")+ .build();} catch (Exception e) {return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error retrieving image")diff --git a/manager/src/main/java/org/openremote/manager/app/ConfigurationService.java b/manager/src/main/java/org/openremote/manager/app/ConfigurationService.javaindex 0a9b9fd2b..b1ed3d42d 100644--- a/manager/src/main/java/org/openremote/manager/app/ConfigurationService.java+++ b/manager/src/main/java/org/openremote/manager/app/ConfigurationService.java@@ -26,9 +26,14 @@ import com.fasterxml.jackson.databind.node.ObjectNode;import java.io.File;import java.io.IOException;import java.nio.charset.StandardCharsets;+import java.nio.file.AtomicMoveNotSupportedException;+import java.nio.file.FileAlreadyExistsException;import java.nio.file.Files;+import java.nio.file.LinkOption;import java.nio.file.Path;import java.nio.file.Paths;+import java.nio.file.StandardCopyOption;+import java.nio.file.StandardOpenOption;import java.util.Arrays;import java.util.Objects;import java.util.Optional;@@ -38,7 +43,6 @@ import java.util.logging.Logger;import java.util.stream.Stream;import org.openremote.container.persistence.PersistenceService;import org.openremote.container.timer.TimerService;-import org.openremote.container.util.CodecUtil;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.manager.web.ManagerWebService;import org.openremote.model.Container;@@ -56,6 +60,9 @@ public class ConfigurationService implements ContainerService {public static final String OR_MAP_TILES_PATH = "OR_MAP_TILES_PATH";public static final String OR_MAP_TILES_PATH_DEFAULT = "manager/src/map/mapdata.mbtiles";+ public static final String MANAGER_CONFIG_IMAGE_URL_PREFIX =+ "/api/master/configuration/manager/image/";+protected ManagerIdentityService identityService;protected PersistenceService persistenceService;protected Path pathPublicRoot;@@ -170,9 +177,7 @@ public class ConfigurationService implements ContainerService {LOG.log(Level.INFO, "Saving map_settings.json to: " + getPersistedMapConfigPath());try {Path p = getPersistedMapConfigPath();- File file = p.toAbsolutePath().toFile();- if (!file.getParentFile().exists()) file.getParentFile().mkdirs();-+ Files.createDirectories(p.getParent());Files.writeString(p, ValueUtil.JSON.writeValueAsString(mapConfiguration), StandardCharsets.UTF_8);// Ensure mapSettingsPath is now pointing to persistence path@@ -180,7 +185,7 @@ public class ConfigurationService implements ContainerService {} catch (Exception exception) {String msg = "Error saving map_settings.json: msg=" + exception.getMessage();LOG.log(Level.WARNING, msg);- throw new IllegalStateException(msg);+ throw new IllegalStateException(msg, exception);}}@@ -243,14 +248,11 @@ public class ConfigurationService implements ContainerService {public void saveManagerConfig(ManagerAppConfig managerAppConfig) throws Exception {LOG.log(Level.INFO, "Saving manager_config.json to: " + getPersistedManagerConfigPath());-try {// Check references to imagesmanagerAppConfig = checkAndFixImageReferences(managerAppConfig);Path p = getPersistedManagerConfigPath();- File file = p.toAbsolutePath().toFile();- if (!file.getParentFile().exists()) file.getParentFile().mkdirs();-+ Files.createDirectories(p.getParent());Files.writeString(p, ValueUtil.JSON.writeValueAsString(managerAppConfig), StandardCharsets.UTF_8);// Ensure managerConfigPath is now pointing to persistence path@@ -263,71 +265,157 @@ public class ConfigurationService implements ContainerService {} catch (Exception exception) {String msg = "Error saving manager_config.json: msg=" + exception.getMessage();LOG.log(Level.WARNING, msg);- throw new Exception(msg);+ throw new Exception(msg, exception);}}- public void saveManagerConfigImage(String path, FileInfo fileInfo) throws Exception {- LOG.log(Level.INFO, "Saving image in manager_config.json: " + fileInfo);- path = path.replace("/images/", "");- path = path.charAt(0) == '/' ? path.substring(1) : path;- Path resolvedPath = Path.of(path);- resolvedPath = getPersistedManagerConfigImagePath().resolve(resolvedPath);- Path filePath = getPersistedManagerConfigImagePath().resolve(path);- File file = filePath.toAbsolutePath().toFile();-+ /**+ * Stores a validated image at the requested relative path, replacing an existing image. Returns+ * the stored relative path. Callers are responsible for enforcing realm authorization.+ */+ public String saveManagerConfigImage(String path, FileInfo fileInfo) throws IOException {+ String filename = normalizeImagePath(path);+ if (fileInfo == null) {+ throw new IllegalArgumentException(+ "Image content is missing; provide the image file contents");+ }+ byte[] data = ImageUploadValidator.decodeAndValidate(filename, fileInfo.getContents());+ Path stored = resolveImagePath(getPersistedManagerConfigImagePath(), filename, true);+ if (Files.isDirectory(stored, LinkOption.NOFOLLOW_LINKS)) {+ throw new IllegalArgumentException(+ "Image upload path is a directory; provide an image filename");+ }+ // Manager serves these images through its API; other containers do not read this storage.+ // Retain the temporary file's restrictive default permissions after the rename.+ Path temporary = Files.createTempFile(stored.getParent(), ".image-upload-", ".tmp");try {- boolean isValid =- resolvedPath- .toFile()- .getCanonicalPath()- .contains(- getPersistedManagerConfigImagePath().toFile().getCanonicalPath()- + File.separator);-- if (!isValid) {- String msg =- "Failed to save manager config image path outside permitted directory: " + resolvedPath;- LOG.warning(msg);- throw new Exception(- "Failed to save manager config image path outside permitted directory: "- + resolvedPath);- }+ // Finish writing before replacing the image, so readers do not see a partial upload.+ Files.write(temporary, data, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS);+ replaceManagerConfigImage(temporary, stored);+ } finally {+ Files.deleteIfExists(temporary);+ }+ return getPersistedManagerConfigImagePath()+ .toRealPath()+ .relativize(stored)+ .toString()+ .replace(File.separatorChar, '/');+ }- if (!file.getParentFile().exists()) file.getParentFile().mkdirs();- Files.write(filePath, CodecUtil.decodeBase64(fileInfo.getContents()));- } catch (Exception exception) {- String msg =- "Error saving image in manager_config.json '"- + filePath- + "': msg="- + exception.getMessage();- LOG.log(Level.WARNING, msg);- throw new Exception(msg);+ /** Replaces a complete image atomically where supported. */+ protected void replaceManagerConfigImage(Path temporary, Path stored) throws IOException {+ try {+ Files.move(+ temporary, stored, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);+ } catch (AtomicMoveNotSupportedException e) {+ Files.move(temporary, stored, StandardCopyOption.REPLACE_EXISTING);}}public Optional<File> getManagerConfigImage(String filename) {- File file = getPersistedManagerConfigImagePath().resolve(filename).toFile();- String checkPath;-try {- if (file.isFile()) {- checkPath = getPersistedManagerConfigImagePath().toFile().getCanonicalPath();- } else {- // fallback to OR_CUSTOM_APP_DOCROOT- file = pathPublicRoot.resolve("images").resolve(filename).toFile();- checkPath = pathPublicRoot.toFile().getCanonicalPath();+ ImageUploadValidator.getMediaType(filename);+ } catch (IllegalArgumentException e) {+ return Optional.empty();+ }+ for (Path root :+ new Path[] {getPersistedManagerConfigImagePath(), pathPublicRoot.resolve("images")}) {+ try {+ if (!Files.isDirectory(root)) {+ continue;+ }+ Path path = resolveImagePath(root, filename, false);+ if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) {+ continue;+ }+ return Optional.of(path.toFile());+ } catch (IllegalArgumentException | IOException e) {+ LOG.log(+ Level.FINE,+ "Configuration image rejected for path '" + filename + "': " + e.getMessage());+ return Optional.empty();}+ }+ return Optional.empty();+ }- // Check if the file retrieved is somewhere within the allowed directory.- boolean isValid = file.getCanonicalPath().contains(checkPath + File.separator);- if (!isValid) return Optional.empty();- } catch (IOException e) {- return Optional.empty();+ private static String normalizeImagePath(String path) {+ if (path == null || path.isBlank()) {+ throw new IllegalArgumentException("Image upload path is missing");}+ if (path.startsWith("/images/")) {+ return path.substring(8);+ }+ return path.startsWith("images/") ? path.substring(7) : path;+ }- return file.isFile() ? Optional.of(file) : Optional.empty();+ // The configured root is trusted and may itself be a symlink. No symlinks below it are allowed.+ // Compare canonical Paths, not strings, and check each descendant before creating or reading it.+ private static Path resolveImagePath(Path root, String filename, boolean createParents)+ throws IOException {+ if (filename == null || filename.isBlank()) {+ throw new IllegalArgumentException(+ "Image path is missing; provide a relative filename including an image extension");+ }+ if (filename.indexOf('\\') >= 0) {+ throw new IllegalArgumentException(+ "Image path contains a backslash; use '/' to separate relative directories");+ }+ Path relative = Path.of(filename);+ Path base = root.toAbsolutePath().normalize();+ if (relative.isAbsolute()) {+ throw new IllegalArgumentException(+ "Image path must be relative to the configuration image directory; absolute paths are not"+ + " allowed");+ }+ if (relative.normalize().toString().isEmpty()) {+ throw new IllegalArgumentException(+ "Image path must include a filename; it cannot refer to the configuration image directory"+ + " itself");+ }+ for (Path part : relative) {+ if ("..".equals(part.toString())) {+ throw new IllegalArgumentException(+ "Image path contains '..'; parent directory traversal is not allowed");+ }+ }+ if (createParents) {+ Files.createDirectories(base);+ }+ Path realRoot = base.toRealPath();+ Path current = realRoot;+ for (int i = 0; i < relative.getNameCount(); i++) {+ current = current.resolve(relative.getName(i)).normalize();+ if (current.equals(realRoot)) {+ throw new IllegalArgumentException(+ "Image path starts with './'; remove it and use a relative filename or subdirectory");+ }+ if (Files.isSymbolicLink(current)) {+ throw new IllegalArgumentException(+ "Image path uses a symbolic link at '%s'; symbolic links are not allowed in the configuration image directory"+ .formatted(relative.subpath(0, i + 1)));+ }+ if (createParents && i < relative.getNameCount() - 1) {+ try {+ Files.createDirectory(current);+ } catch (FileAlreadyExistsException e) {+ if (!Files.isDirectory(current, LinkOption.NOFOLLOW_LINKS)) {+ throw new IllegalArgumentException(+ "Image path parent '%s' is not a directory; each component before the filename must be a directory"+ .formatted(relative.subpath(0, i + 1)));+ }+ }+ }+ if (Files.exists(current, LinkOption.NOFOLLOW_LINKS)) {+ current = current.toRealPath();+ }+ if (!current.startsWith(realRoot)) {+ throw new IllegalArgumentException(+ "Image path resolves outside the configuration image directory; images must remain"+ + " inside that directory");+ }+ }+ return current;}protected Path getPersistedManagerConfigPath() {@@ -346,10 +434,9 @@ public class ConfigurationService implements ContainerService {return this.persistenceService.resolvePath("manager").resolve("images");}- protected ManagerAppConfig checkAndFixImageReferences(ManagerAppConfig managerAppConfig) {-- if (!getPersistedManagerConfigImagePath().toFile().exists())- getPersistedManagerConfigImagePath().toFile().mkdirs();+ protected ManagerAppConfig checkAndFixImageReferences(ManagerAppConfig managerAppConfig)+ throws IOException {+ Files.createDirectories(getPersistedManagerConfigImagePath());if (managerAppConfig.getRealms() != null && !managerAppConfig.getRealms().isEmpty()) {managerAppConfig.getRealms()@@ -372,35 +459,40 @@ public class ConfigurationService implements ContainerService {}protected String fixImageRef(String image) {- String originalString = image;- if (!image.isBlank()) {- image = image.replace("/api/master/configuration/manager/image/", "");- image = image.replace("images/", "");- image = image.charAt(0) == '/' ? image.substring(1) : image;- Path imagePath = Path.of(image);- Path persistedImagePath =- getPersistedManagerConfigImagePath().resolve(imagePath).toAbsolutePath();- Path path = pathPublicRoot.resolve("images").resolve(imagePath).toAbsolutePath();-- if (!Files.isRegularFile(persistedImagePath)) {- if (Files.isRegularFile(path)) {- try {- // Image doesn't exist in persisted path but does exist in doc root so copy it- Files.copy(path, persistedImagePath);- // Change the reference in the config to the typical API-like reference:- image = "/api/master/configuration/manager/image/" + imagePath;- } catch (Exception e) {- LOG.warning(- "Error occurred whilst copying manager config image to persisted path: "- + persistedImagePath);- }- } else {- LOG.warning("manager_config.json image reference doesn't exist: " + imagePath);- }- } else {- return originalString;+ if (image.isBlank()) {+ return image;+ }+ String filename =+ normalizeImagePath(+ image.startsWith(MANAGER_CONFIG_IMAGE_URL_PREFIX)+ ? image.substring(MANAGER_CONFIG_IMAGE_URL_PREFIX.length())+ : image);+ try {+ Path persisted = resolveImagePath(getPersistedManagerConfigImagePath(), filename, false);+ if (Files.isRegularFile(persisted, LinkOption.NOFOLLOW_LINKS)) {+ return image;+ }+ Optional<File> source = getManagerConfigImage(filename);+ if (source.isEmpty()) {+ LOG.warning("manager_config.json image reference is missing or invalid: " + filename);+ return image;+ }+ // Validate a fallback image once when importing it into persisted configuration assets.+ byte[] data;+ try (var input = Files.newInputStream(source.get().toPath(), LinkOption.NOFOLLOW_LINKS)) {+ data = input.readNBytes(ImageUploadValidator.MAX_FILE_SIZE + 1);}+ ImageUploadValidator.validate(filename, data);+ persisted = resolveImagePath(getPersistedManagerConfigImagePath(), filename, true);+ Files.write(persisted, data, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);+ return MANAGER_CONFIG_IMAGE_URL_PREFIX + filename;+ } catch (IllegalArgumentException | IOException e) {+ LOG.warning(+ "Could not resolve manager_config.json image reference '"+ + filename+ + "': "+ + e.getMessage());+ return image;}- return image;}}diff --git a/manager/src/main/java/org/openremote/manager/app/ImageUploadValidator.java b/manager/src/main/java/org/openremote/manager/app/ImageUploadValidator.javanew file mode 100644index 000000000..18521241b--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/app/ImageUploadValidator.java@@ -0,0 +1,135 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * SPDX-License-Identifier: AGPL-3.0-or-later+ */+package org.openremote.manager.app;++import java.util.Locale;+import java.util.Map;+import org.openremote.container.util.CodecUtil;++/**+ * Validates images uploaded for use by the Manager UI.+ *+ * <p>Only PNG, JPEG, ICO, and SVG images are accepted. Raster images are decoded to verify their+ * actual format and are subject to file size and dimension limits. SVG images are parsed with+ * external XML entities disabled and checked against restricted element, metadata, CSS, and+ * reference rules before the original bytes are stored.+ *+ * <p>SVG metadata may contain RDF, Dublin Core, Creative Commons, and Adobe XMP XML, including XMP+ * packet markers. Inkscape, Sodipodi, Serif, Sketch, Illustrator, and Visio editor elements and+ * attributes are also supported. Other foreign XML namespaces, including XHTML, are rejected. SVG+ * image elements may contain Base64 static PNG or JPEG data, validated against raster limits and a+ * combined pixel budget; external image references and nested SVG data are rejected.+ *+ * <p>The filename extension must correspond with the actual image format. Both plain Base64 content+ * and Base64 data URLs are supported.+ */+public final class ImageUploadValidator {++ public static final int MAX_FILE_SIZE = 2 * 1024 * 1024;++ private static final Map<String, String> MEDIA_TYPES =+ Map.of(+ "png", "image/png",+ "jpg", "image/jpeg",+ "jpeg", "image/jpeg",+ "ico", "image/vnd.microsoft.icon",+ "svg", "image/svg+xml");++ // Base64 requires approximately four characters for every three decoded bytes. Leave some room+ // for a data URL prefix such as "data:image/png;base64,".+ private static final int MAX_ENCODED_SIZE = ((MAX_FILE_SIZE + 2) / 3) * 4 + 256;++ private ImageUploadValidator() {}++ /**+ * Decodes and validates an uploaded image.+ *+ * @param filename filename or relative path including the extension+ * @param contents Base64 encoded image contents, optionally as a data URL+ * @return decoded image bytes+ * @throws IllegalArgumentException if the image is invalid or violates the upload restrictions+ */+ public static byte[] decodeAndValidate(String filename, String contents) {+ if (contents == null || contents.isBlank()) {+ throw new IllegalArgumentException("Image content is empty");+ }++ if (contents.length() > MAX_ENCODED_SIZE) {+ throw new IllegalArgumentException(+ "Encoded image exceeds the " + MAX_FILE_SIZE + " byte upload limit");+ }++ byte[] data = CodecUtil.decodeBase64(contents);++ validate(filename, data);++ return data;+ }++ /**+ * Validates decoded image data.+ *+ * @param filename filename or relative path including the extension+ * @param data decoded image bytes+ * @throws IllegalArgumentException if the image is invalid or violates the upload restrictions+ */+ public static void validate(String filename, byte[] data) {+ if (data == null || data.length == 0) {+ throw new IllegalArgumentException("Image is empty");+ }++ if (data.length > MAX_FILE_SIZE) {+ throw new IllegalArgumentException(+ "Image is " + data.length + " bytes; maximum is " + MAX_FILE_SIZE + " bytes");+ }++ switch (getMediaType(filename)) {+ case "image/vnd.microsoft.icon" -> RasterImageValidator.validate(data, "ico");+ case "image/jpeg" -> RasterImageValidator.validate(data, "jpeg");+ case "image/png" -> RasterImageValidator.validate(data, "png");+ case "image/svg+xml" -> SvgImageValidator.validate(data);+ default -> throw new IllegalStateException("No validator for image media type");+ }+ }++ /** Returns the fixed media type for an allowed image extension, including legacy reads. */+ static String getMediaType(String filename) {+ String mediaType = MEDIA_TYPES.get(getExtension(filename));+ if (mediaType == null) {+ throw new IllegalArgumentException(+ "Unsupported image extension; allowed extensions are png, jpg, jpeg, ico, and svg");+ }+ return mediaType;+ }++ private static String getExtension(String filename) {+ if (filename == null || filename.isBlank()) {+ throw new IllegalArgumentException("Image filename is missing");+ }++ int slashIndex = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));+ int dotIndex = filename.lastIndexOf('.');++ if (dotIndex <= slashIndex || dotIndex == filename.length() - 1) {+ throw new IllegalArgumentException("Image file extension is missing");+ }++ return filename.substring(dotIndex + 1).toLowerCase(Locale.ROOT);+ }+}diff --git a/manager/src/main/java/org/openremote/manager/app/RasterImageValidator.java b/manager/src/main/java/org/openremote/manager/app/RasterImageValidator.javanew file mode 100644index 000000000..ec8133710--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/app/RasterImageValidator.java@@ -0,0 +1,310 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * SPDX-License-Identifier: AGPL-3.0-or-later+ */+package org.openremote.manager.app;++import java.awt.image.BufferedImage;+import java.io.ByteArrayInputStream;+import java.io.IOException;+import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.Iterator;+import java.util.Locale;+import java.util.Set;+import javax.imageio.ImageIO;+import javax.imageio.ImageReader;+import javax.imageio.stream.ImageInputStream;+import javax.imageio.stream.MemoryCacheImageInputStream;++/**+ * Validates decoded PNG, JPEG, and ICO uploads, including their format, dimensions, and image data.+ * Animated PNGs are rejected because the PNG decoder does not validate their additional frames.+ */+final class RasterImageValidator {++ static final int MAX_WIDTH = 4096;+ static final int MAX_HEIGHT = 4096;+ static final long MAX_PIXELS = 16_000_000;+ private static final int MAX_IMAGES = 32;+ private static final Set<Integer> DIB_HEADER_SIZES = Set.of(12, 16, 40, 52, 56, 64, 108, 124);+ private static final Set<Integer> DIB_BIT_DEPTHS = Set.of(1, 4, 8, 16, 24, 32);++ private RasterImageValidator() {}++ static void validate(byte[] data, String expectedFormat) {+ validate(data, expectedFormat, MAX_PIXELS);+ }++ /** Validates image data within a remaining pixel budget and returns its decoded pixel count. */+ static long validate(byte[] data, String expectedFormat, long remainingPixels) {+ // Upload bytes are already bounded and in memory; avoid a disk cache and shared settings.+ try (ImageInputStream input = new MemoryCacheImageInputStream(new ByteArrayInputStream(data))) {++ Iterator<ImageReader> readers = ImageIO.getImageReaders(input);++ if (!readers.hasNext()) {+ throw new IllegalArgumentException("No image decoder recognizes the uploaded data");+ }++ ImageReader reader = readers.next();++ try {+ String actualFormat = normalizeFormat(reader.getFormatName());++ if (!expectedFormat.equals(actualFormat)) {+ throw new IllegalArgumentException(+ "Image contains "+ + actualFormat.toUpperCase(Locale.ROOT)+ + " data, but its extension requires "+ + expectedFormat.toUpperCase(Locale.ROOT));+ }++ if ("ico".equals(actualFormat)) {+ validateIcoHeaders(data);+ }+ if ("png".equals(actualFormat)) {+ rejectAnimatedPng(data, 0, data.length);+ }++ reader.setInput(input, false, true);++ int imageCount = "ico".equals(expectedFormat) ? reader.getNumImages(true) : 1;++ if (imageCount <= 0 || imageCount > MAX_IMAGES) {+ throw new IllegalArgumentException(+ "Image contains " + imageCount + " frames; allowed range is 1 to " + MAX_IMAGES);+ }++ long totalPixels = 0;++ for (int i = 0; i < imageCount; i++) {+ int width = reader.getWidth(i);+ int height = reader.getHeight(i);++ if (width <= 0 || height <= 0 || width > MAX_WIDTH || height > MAX_HEIGHT) {+ throw new IllegalArgumentException(+ "Image frame "+ + (i + 1)+ + " is "+ + width+ + "x"+ + height+ + " pixels; dimensions must be between 1x1 and "+ + MAX_WIDTH+ + "x"+ + MAX_HEIGHT);+ }++ totalPixels += (long) width * height;++ if (totalPixels > MAX_PIXELS) {+ throw new IllegalArgumentException(+ "Image contains "+ + totalPixels+ + " pixels across its frames; maximum is "+ + MAX_PIXELS);+ }+ if (totalPixels > remainingPixels) {+ throw new IllegalArgumentException(+ "Image contains %d pixels across its frames, but the remaining pixel budget is %d; maximum across images is %d pixels"+ .formatted(totalPixels, remainingPixels, MAX_PIXELS));+ }++ // Force the actual image data to be decoded rather than only trusting its header.+ BufferedImage image = reader.read(i);++ if (image == null) {+ throw new IllegalArgumentException("Image frame " + (i + 1) + " could not be decoded");+ }+ if (image.getWidth() != width || image.getHeight() != height) {+ throw new IllegalArgumentException(+ "Image frame %d decoded to %dx%d pixels, but its header reports %dx%d pixels; dimensions must match"+ .formatted(i + 1, image.getWidth(), image.getHeight(), width, height));+ }+ }+ return totalPixels;+ } finally {+ reader.dispose();+ }+ } catch (IllegalArgumentException e) {+ throw e;+ } catch (IOException | RuntimeException e) {+ throw new IllegalArgumentException(+ "Could not decode "+ + expectedFormat.toUpperCase(Locale.ROOT)+ + " image data: "+ + e.getMessage(),+ e);+ }+ }++ private static void rejectAnimatedPng(byte[] data, int start, int size) {+ ByteBuffer png = ByteBuffer.wrap(data, start, size).slice().order(ByteOrder.BIG_ENDIAN);+ for (int offset = 8; offset <= size - 12; ) {+ long length = Integer.toUnsignedLong(png.getInt(offset));+ if (length > size - offset - 12) {+ // The decoder reports malformed or truncated PNG data.+ return;+ }+ if (png.getInt(offset + 4) == 0x6163544c) { // acTL+ throw new IllegalArgumentException(+ "Animated PNG images are not supported; export a static PNG so all image data can be validated");+ }+ offset += (int) length + 12;+ }+ }++ // ICO readers report directory dimensions, but allocate from the embedded PNG/DIB header.+ // Check every payload before decoding any frame, using unsigned bounds to avoid overflow.+ private static void validateIcoHeaders(byte[] data) {+ ByteBuffer buffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);+ if (data.length < 6) {+ throw new IllegalArgumentException(+ "ICO directory header is truncated: image contains %d bytes; at least 6 are required"+ .formatted(data.length));+ }+ if (buffer.getShort(0) != 0 || buffer.getShort(2) != 1) {+ throw new IllegalArgumentException(+ "ICO directory header has reserved value %d and image type %d; expected reserved value 0 and image type 1 (icon)"+ .formatted(+ Short.toUnsignedInt(buffer.getShort(0)),+ Short.toUnsignedInt(buffer.getShort(2))));+ }+ int count = Short.toUnsignedInt(buffer.getShort(4));+ int directoryEnd = 6 + count * 16;+ if (count == 0 || count > MAX_IMAGES) {+ throw new IllegalArgumentException(+ "ICO contains %d frames; allowed range is 1 to %d".formatted(count, MAX_IMAGES));+ }+ if (directoryEnd > data.length) {+ throw new IllegalArgumentException(+ "ICO directory for %d frames requires %d bytes, but the image contains only %d bytes"+ .formatted(count, directoryEnd, data.length));+ }++ for (int i = 0; i < count; i++) {+ int entry = 6 + i * 16;+ int width = Byte.toUnsignedInt(data[entry]);+ int height = Byte.toUnsignedInt(data[entry + 1]);+ width = width == 0 ? 256 : width;+ height = height == 0 ? 256 : height;+ long size = Integer.toUnsignedLong(buffer.getInt(entry + 8));+ long offset = Integer.toUnsignedLong(buffer.getInt(entry + 12));+ if (offset < directoryEnd || size < 12 || offset + size > data.length) {+ throw new IllegalArgumentException(+ "ICO frame %d has an invalid payload range: offset %d, size %d bytes; the payload must start at or after byte %d, contain at least 12 bytes, and fit within the %d-byte image"+ .formatted(i + 1, offset, size, directoryEnd, data.length));+ }++ int start = (int) offset;+ long embeddedWidth;+ long embeddedHeight;+ if (buffer.getLong(start) == 0x0a1a0a0d474e5089L) {+ ByteBuffer png = buffer.duplicate().order(ByteOrder.BIG_ENDIAN);+ if (size < 33) {+ throw new IllegalArgumentException(+ "ICO frame %d embedded PNG header is truncated: payload contains %d bytes; at least 33 are required"+ .formatted(i + 1, size));+ }+ if (png.getInt(start + 8) != 13 || png.getInt(start + 12) != 0x49484452) {+ throw new IllegalArgumentException(+ "ICO frame %d embedded PNG starts with chunk type 0x%08x and chunk length %d bytes; expected an IHDR chunk with 13 bytes of image header data"+ .formatted(+ i + 1,+ png.getInt(start + 12),+ Integer.toUnsignedLong(png.getInt(start + 8))));+ }+ rejectAnimatedPng(data, start, (int) size);+ embeddedWidth = Integer.toUnsignedLong(png.getInt(start + 16));+ embeddedHeight = Integer.toUnsignedLong(png.getInt(start + 20));+ } else {+ int headerSize = buffer.getInt(start);+ if (!DIB_HEADER_SIZES.contains(headerSize)) {+ throw new IllegalArgumentException(+ "ICO frame %d DIB header size is %d bytes; supported sizes are 12, 16, 40, 52, 56, 64, 108, and 124 bytes"+ .formatted(i + 1, Integer.toUnsignedLong(headerSize)));+ }+ if (headerSize > size) {+ throw new IllegalArgumentException(+ "ICO frame %d DIB header declares %d bytes, but its payload contains only %d bytes"+ .formatted(i + 1, headerSize, size));+ }+ embeddedWidth =+ headerSize == 12+ ? Short.toUnsignedInt(buffer.getShort(start + 4))+ : buffer.getInt(start + 4);+ int planes = Short.toUnsignedInt(buffer.getShort(start + (headerSize == 12 ? 8 : 12)));+ int bits = Short.toUnsignedInt(buffer.getShort(start + (headerSize == 12 ? 10 : 14)));+ int directoryBits = Short.toUnsignedInt(buffer.getShort(entry + 6));+ // The decoder also uses the directory bit depth for palette allocation.+ if (planes != 1) {+ throw new IllegalArgumentException(+ "ICO frame %d DIB header declares %d color planes; exactly 1 is required"+ .formatted(i + 1, planes));+ }+ if (!DIB_BIT_DEPTHS.contains(bits)) {+ throw new IllegalArgumentException(+ "ICO frame %d DIB bit depth is %d bits per pixel; supported depths are 1, 4, 8, 16, 24, and 32"+ .formatted(i + 1, bits));+ }+ if (directoryBits != 0 && directoryBits != bits) {+ throw new IllegalArgumentException(+ "ICO frame %d directory bit depth is %d, but the DIB bit depth is %d; the directory bit depth must be 0 or match the DIB header"+ .formatted(i + 1, directoryBits, bits));+ }+ long dibHeight = headerSize == 12 ? buffer.getShort(start + 6) : buffer.getInt(start + 8);+ // DIB icons contain the image followed by an equally sized transparency mask.+ if (dibHeight <= 0 || dibHeight % 2 != 0) {+ throw new IllegalArgumentException(+ "ICO frame %d DIB height is %d pixels; it must be positive and even because it includes both the image and its transparency mask"+ .formatted(i + 1, dibHeight));+ }+ embeddedHeight = dibHeight / 2;+ }++ if (embeddedWidth <= 0+ || embeddedHeight <= 0+ || embeddedWidth > MAX_WIDTH+ || embeddedHeight > MAX_HEIGHT) {+ throw new IllegalArgumentException(+ "ICO frame %d embedded image is %dx%d pixels; dimensions must be between 1x1 and %dx%d"+ .formatted(i + 1, embeddedWidth, embeddedHeight, MAX_WIDTH, MAX_HEIGHT));+ }+ long pixels = embeddedWidth * embeddedHeight;+ if (pixels > MAX_PIXELS) {+ throw new IllegalArgumentException(+ "ICO frame %d embedded image is %dx%d pixels and contains %d pixels; maximum is %d pixels"+ .formatted(i + 1, embeddedWidth, embeddedHeight, pixels, MAX_PIXELS));+ }+ if (embeddedWidth != width || embeddedHeight != height) {+ throw new IllegalArgumentException(+ "ICO frame %d directory reports %dx%d pixels, but the embedded image is %dx%d pixels; dimensions must match"+ .formatted(i + 1, width, height, embeddedWidth, embeddedHeight));+ }+ }+ }++ private static String normalizeFormat(String format) {+ String normalized = format.toLowerCase(Locale.ROOT);++ return switch (normalized) {+ case "jpg" -> "jpeg";+ default -> normalized;+ };+ }+}diff --git a/manager/src/main/java/org/openremote/manager/app/SvgImageValidator.java b/manager/src/main/java/org/openremote/manager/app/SvgImageValidator.javanew file mode 100644index 000000000..5f4bfee18--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/app/SvgImageValidator.java@@ -0,0 +1,691 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * SPDX-License-Identifier: AGPL-3.0-or-later+ */+package org.openremote.manager.app;++import java.io.ByteArrayInputStream;+import java.util.Base64;+import java.util.Locale;+import java.util.Set;+import javax.xml.XMLConstants;+import javax.xml.parsers.DocumentBuilderFactory;+import org.w3c.dom.Attr;+import org.w3c.dom.Document;+import org.w3c.dom.Element;+import org.w3c.dom.NamedNodeMap;+import org.w3c.dom.Node;+import org.xml.sax.SAXParseException;++/**+ * Validates decoded SVG uploads as XML 1.0 in UTF-8 or UTF-16 and restricts elements, attributes,+ * CSS, and references. Descriptive metadata, including XMP, and Inkscape, Sodipodi, Serif, Sketch,+ * Illustrator, and Visio editor metadata are allowed, with their full subtrees checked to reject+ * active or unsupported foreign content. XMP packet processing instructions are allowed within+ * metadata only. Embedded images must be Base64 data URLs containing validated static PNG or JPEG+ * data and share a limit on their count and total decoded pixels.+ */+final class SvgImageValidator {++ private static final int MAX_SVG_ELEMENTS = 10_000;+ private static final int MAX_SVG_DEPTH = 64;+ private static final int MAX_EMBEDDED_IMAGES = 32;++ private static final Set<String> XML_ENCODINGS =+ Set.of("UTF-8", "UTF-16", "UTF-16BE", "UTF-16LE");++ private static final String SVG_NAMESPACE = "http://www.w3.org/2000/svg";+ private static final String XLINK_NAMESPACE = "http://www.w3.org/1999/xlink";++ // Editors store authoring metadata in both elements and attributes using these namespaces.+ private static final Set<String> EDITOR_NAMESPACES =+ Set.of(+ "http://www.inkscape.org/namespaces/inkscape",+ "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd",+ "http://www.serif.com/",+ "http://www.bohemiancoding.com/sketch/ns",+ "http://ns.adobe.com/AdobeIllustrator/10.0/",+ "http://ns.adobe.com/Graphs/1.0/",+ "http://schemas.microsoft.com/visio/2003/SVGExtensions/");++ // Foreign markup in metadata is only safe when the browser will treat it as data. In+ // particular, XHTML script elements execute even when nested inside SVG metadata.+ // Creative Commons metadata uses both the current ns# and older web.resource.org namespaces.+ private static final Set<String> METADATA_NAMESPACES =+ Set.of(+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#",+ "http://www.w3.org/2000/01/rdf-schema#",+ "http://purl.org/dc/elements/1.1/",+ "http://purl.org/dc/terms/",+ "http://creativecommons.org/ns#",+ "http://web.resource.org/cc/",+ "adobe:ns:meta/",+ "http://ns.adobe.com/xap/1.0/",+ "http://ns.adobe.com/xap/1.0/mm/",+ "http://ns.adobe.com/xap/1.0/rights/",+ "http://ns.adobe.com/xap/1.0/sType/Dimensions#",+ "http://ns.adobe.com/xap/1.0/sType/ResourceEvent#",+ "http://ns.adobe.com/xap/1.0/sType/ResourceRef#",+ "http://ns.adobe.com/photoshop/1.0/",+ "http://ns.adobe.com/illustrator/1.0/",+ "http://ns.adobe.com/Variables/1.0/",+ "http://ns.adobe.com/SaveForWeb/1.0/");++ private static final Set<String> SVG_ELEMENTS =+ Set.of(+ "svg",+ "g",+ "defs",+ "symbol",+ "use",+ "image",+ "path",+ "rect",+ "circle",+ "ellipse",+ "line",+ "polyline",+ "polygon",+ "linearGradient",+ "radialGradient",+ "stop",+ "clipPath",+ "mask",+ "pattern",+ "marker",+ "style",+ "text",+ "tspan",+ "title",+ "desc",+ "metadata");++ // Presentation attributes use CSS value parsing, just like declarations in a style attribute.+ private static final Set<String> PRESENTATION_ATTRIBUTES =+ Set.of(+ "alignment-baseline",+ "baseline-shift",+ "clip",+ "clip-path",+ "clip-rule",+ "color",+ "color-interpolation",+ "color-interpolation-filters",+ "color-profile",+ "color-rendering",+ "cursor",+ "direction",+ "display",+ "dominant-baseline",+ "enable-background",+ "fill",+ "fill-opacity",+ "fill-rule",+ "filter",+ "flood-color",+ "flood-opacity",+ "font-family",+ "font-size",+ "font-size-adjust",+ "font-stretch",+ "font-style",+ "font-variant",+ "font-weight",+ "glyph-orientation-horizontal",+ "glyph-orientation-vertical",+ "image-rendering",+ "kerning",+ "letter-spacing",+ "lighting-color",+ "marker",+ "marker-end",+ "marker-mid",+ "marker-start",+ "mask",+ "mask-type",+ "opacity",+ "overflow",+ "paint-order",+ "pointer-events",+ "shape-rendering",+ "stop-color",+ "stop-opacity",+ "stroke",+ "stroke-dasharray",+ "stroke-dashoffset",+ "stroke-linecap",+ "stroke-linejoin",+ "stroke-miterlimit",+ "stroke-opacity",+ "stroke-width",+ "text-anchor",+ "text-decoration",+ "text-overflow",+ "text-rendering",+ "transform",+ "transform-origin",+ "unicode-bidi",+ "vector-effect",+ "visibility",+ "white-space",+ "word-spacing",+ "writing-mode",+ "d",+ "x",+ "y",+ "cx",+ "cy",+ "r",+ "rx",+ "ry",+ "width",+ "height");++ private static final String[] FORBIDDEN_CSS_CONSTRUCTS = {+ "@import",+ "@font-face",+ "image-set(",+ "image(",+ "src(",+ "expression(",+ "-moz-binding",+ "behavior:",+ "javascript:",+ "data:"+ };++ private static final String[] EXTERNAL_SCHEMES = {+ "javascript:", "data:", "file:", "http:", "https:"+ };++ private SvgImageValidator() {}++ static void validate(byte[] data) {+ try {+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();++ factory.setNamespaceAware(true);+ factory.setXIncludeAware(false);+ factory.setExpandEntityReferences(false);++ factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);+ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);+ factory.setFeature("http://xml.org/sax/features/external-general-entities", false);+ factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);+ factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);++ factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");+ factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");++ Document document;++ try (ByteArrayInputStream input = new ByteArrayInputStream(data)) {+ document = factory.newDocumentBuilder().parse(input);+ }++ // Stored bytes are served unchanged, so limit differences in XML interpretation.+ if (!"1.0".equals(document.getXmlVersion())) {+ throw new IllegalArgumentException("SVG XML version must be 1.0");+ }++ // Xerces can report UTF-8 input even when the declaration selects ISO-2022-JP.+ String inputEncoding = document.getInputEncoding();+ String declaredEncoding = document.getXmlEncoding();+ if (inputEncoding == null+ || !XML_ENCODINGS.contains(inputEncoding.toUpperCase(Locale.ROOT))+ || (declaredEncoding != null+ && !XML_ENCODINGS.contains(declaredEncoding.toUpperCase(Locale.ROOT)))) {+ throw new IllegalArgumentException("SVG XML encoding must be UTF-8 or UTF-16");+ }++ validateDocumentNodes(document);++ Element root = document.getDocumentElement();++ if (root == null+ || !"svg".equals(root.getLocalName())+ || !SVG_NAMESPACE.equals(root.getNamespaceURI())) {+ throw new IllegalArgumentException("SVG root must be <svg> in the SVG namespace");+ }++ validateSvgElement(root, 0, new ValidationState());+ } catch (IllegalArgumentException e) {+ throw e;+ } catch (SAXParseException e) {+ throw new IllegalArgumentException(+ "Malformed SVG XML at line "+ + e.getLineNumber()+ + ", column "+ + e.getColumnNumber()+ + ": "+ + e.getMessage(),+ e);+ } catch (Exception e) {+ throw new IllegalArgumentException("Could not parse SVG XML: " + e.getMessage(), e);+ }+ }++ private static void validateDocumentNodes(Document document) {+ for (Node child = document.getFirstChild(); child != null; child = child.getNextSibling()) {+ switch (child.getNodeType()) {+ case Node.ELEMENT_NODE, Node.COMMENT_NODE -> {+ // Allowed.+ }++ case Node.PROCESSING_INSTRUCTION_NODE,+ Node.DOCUMENT_TYPE_NODE,+ Node.ENTITY_NODE,+ Node.ENTITY_REFERENCE_NODE ->+ throw new IllegalArgumentException(+ "SVG document contains unsupported "+ + nodeType(child)+ + " before or after its root");++ default -> {+ // Ignore whitespace and other harmless document nodes.+ }+ }+ }+ }++ private static void validateSvgElement(Element element, int depth, ValidationState state) {++ if (depth > MAX_SVG_DEPTH) {+ throw new IllegalArgumentException("SVG nesting exceeds " + MAX_SVG_DEPTH + " levels");+ }++ if (++state.elementCount > MAX_SVG_ELEMENTS) {+ throw new IllegalArgumentException(+ "SVG contains more than " + MAX_SVG_ELEMENTS + " elements");+ }++ if (EDITOR_NAMESPACES.contains(element.getNamespaceURI())) {+ validateSvgAttributes(element, state);+ validateMetadata(element, depth, state);+ return;+ }++ if (!SVG_NAMESPACE.equals(element.getNamespaceURI())) {+ throw new IllegalArgumentException(+ "SVG element <" + element.getTagName() + "> is outside the SVG namespace");+ }++ String name = element.getLocalName();++ if (!SVG_ELEMENTS.contains(name)) {+ throw new IllegalArgumentException("Unsupported SVG element: " + name);+ }++ validateSvgAttributes(element, state);++ if ("metadata".equals(name)) {+ validateMetadata(element, depth, state);+ return;+ }++ for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {+ switch (child.getNodeType()) {+ case Node.ELEMENT_NODE -> validateSvgElement((Element) child, depth + 1, state);++ case Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.COMMENT_NODE -> {+ // Allowed.+ }++ case Node.PROCESSING_INSTRUCTION_NODE,+ Node.ENTITY_NODE,+ Node.ENTITY_REFERENCE_NODE,+ Node.DOCUMENT_TYPE_NODE ->+ throw new IllegalArgumentException(+ "SVG <" + name + "> contains unsupported " + nodeType(child));++ default -> {+ // Ignore other harmless DOM node types.+ }+ }+ }++ // getTextContent() recursively walks descendants, so enforce subtree limits first.+ if ("style".equals(name)) {+ try {+ validateCss(element.getTextContent());+ } catch (IllegalArgumentException e) {+ throw new IllegalArgumentException("SVG <style>: " + e.getMessage(), e);+ }+ }+ }++ private static void validateMetadata(Element metadata, int depth, ValidationState state) {++ for (Node child = metadata.getFirstChild(); child != null; child = child.getNextSibling()) {+ validateMetadataNode(child, depth + 1, state);+ }+ }++ private static void validateMetadataNode(Node node, int depth, ValidationState state) {++ if (depth > MAX_SVG_DEPTH) {+ throw new IllegalArgumentException(+ "SVG metadata nesting exceeds " + MAX_SVG_DEPTH + " levels");+ }++ switch (node.getNodeType()) {+ case Node.ELEMENT_NODE -> {+ if (++state.elementCount > MAX_SVG_ELEMENTS) {+ throw new IllegalArgumentException(+ "SVG contains more than " + MAX_SVG_ELEMENTS + " elements");+ }++ Element element = (Element) node;+ boolean editorMetadata = EDITOR_NAMESPACES.contains(element.getNamespaceURI());++ if (!editorMetadata && !METADATA_NAMESPACES.contains(element.getNamespaceURI())) {+ throw new IllegalArgumentException(+ "SVG metadata element <" + element.getTagName() + "> uses an unsupported namespace");+ }++ if (editorMetadata) {+ validateSvgAttributes(element, state);+ } else {+ validateMetadataAttributes(element);+ }++ for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {+ validateMetadataNode(child, depth + 1, state);+ }+ }++ case Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.COMMENT_NODE -> {+ // Allowed.+ }++ case Node.PROCESSING_INSTRUCTION_NODE -> {+ // XMP packet markers are editor data, not stylesheet or script instructions.+ if (!"xpacket".equals(node.getNodeName())) {+ throw new IllegalArgumentException("SVG metadata contains unsupported " + nodeType(node));+ }+ }++ case Node.ENTITY_NODE, Node.ENTITY_REFERENCE_NODE, Node.DOCUMENT_TYPE_NODE ->+ throw new IllegalArgumentException("SVG metadata contains unsupported " + nodeType(node));++ default -> {+ // Ignore other harmless DOM node types.+ }+ }+ }++ private static void validateMetadataAttributes(Element element) {+ NamedNodeMap attributes = element.getAttributes();++ for (int i = 0; i < attributes.getLength(); i++) {+ Attr attribute = (Attr) attributes.item(i);++ if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attribute.getNamespaceURI())) {+ continue;+ }++ String name =+ attribute.getLocalName() != null ? attribute.getLocalName() : attribute.getName();++ if (name.toLowerCase(Locale.ROOT).startsWith("on")) {+ throw new IllegalArgumentException(+ "SVG metadata element <"+ + element.getTagName()+ + "> has disallowed event handler attribute '"+ + attribute.getName()+ + "'");+ }+ }+ }++ private static void validateSvgAttributes(Element element, ValidationState state) {+ NamedNodeMap attributes = element.getAttributes();++ for (int i = 0; i < attributes.getLength(); i++) {+ Attr attribute = (Attr) attributes.item(i);++ String namespace = attribute.getNamespaceURI();++ if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespace)) {+ continue;+ }++ String name =+ attribute.getLocalName() != null ? attribute.getLocalName() : attribute.getName();++ String lowerName = name.toLowerCase(Locale.ROOT);+ String value = attribute.getValue().trim();++ try {+ if (lowerName.startsWith("on")) {+ throw new IllegalArgumentException("event handlers are not allowed");+ }++ // xml:base can turn otherwise relative references into external references.+ if ("base".equals(lowerName) && XMLConstants.XML_NS_URI.equals(namespace)) {+ throw new IllegalArgumentException("base URIs are not allowed");+ }++ if (namespace != null+ && !XMLConstants.XML_NS_URI.equals(namespace)+ && !XLINK_NAMESPACE.equals(namespace)+ && !EDITOR_NAMESPACES.contains(namespace)) {+ throw new IllegalArgumentException("attribute namespace is not supported");+ }++ if (XLINK_NAMESPACE.equals(namespace) && !"href".equals(lowerName)) {+ throw new IllegalArgumentException("only xlink:href is supported");+ }++ if ("href".equals(lowerName)) {+ if (SVG_NAMESPACE.equals(element.getNamespaceURI())+ && "image".equals(element.getLocalName())+ && (namespace == null || XLINK_NAMESPACE.equals(namespace))) {+ validateEmbeddedImage(value, state);+ } else {+ validateLocalReference(value);+ }+ continue;+ }++ if ("style".equals(lowerName) || PRESENTATION_ATTRIBUTES.contains(lowerName)) {+ validateCss(value);+ } else {+ validateUrlReferences(value);+ }++ String externalScheme = findExternalScheme(value);+ if (externalScheme != null) {+ throw new IllegalArgumentException("URI scheme '" + externalScheme + "' is not allowed");+ }+ } catch (IllegalArgumentException e) {+ throw new IllegalArgumentException(+ "SVG <"+ + element.getLocalName()+ + "> attribute '"+ + attribute.getName()+ + "': "+ + e.getMessage(),+ e);+ }+ }+ }++ private static void validateEmbeddedImage(String value, ValidationState state) {+ String format;+ int prefixLength;+ if (value.regionMatches(true, 0, "data:image/png;base64,", 0, 22)) {+ format = "png";+ prefixLength = 22;+ } else if (value.regionMatches(true, 0, "data:image/jpeg;base64,", 0, 23)) {+ format = "jpeg";+ prefixLength = 23;+ } else {+ throw new IllegalArgumentException(+ "embedded images must use data:image/png;base64, or data:image/jpeg;base64,; external URLs and other embedded formats are not allowed");+ }++ if (++state.embeddedImageCount > MAX_EMBEDDED_IMAGES) {+ throw new IllegalArgumentException(+ "SVG contains more than " + MAX_EMBEDDED_IMAGES + " embedded image references");+ }++ // Editors wrap Base64 data over lines; allow ASCII whitespace, but reject other invalid+ // characters.+ String encoded = value.substring(prefixLength).replaceAll("[\\t\\n\\r ]", "");+ if (encoded.isEmpty()) {+ throw new IllegalArgumentException(+ "embedded " + format.toUpperCase(Locale.ROOT) + " image data is empty");+ }+ byte[] data;+ try {+ data = Base64.getDecoder().decode(encoded);+ } catch (IllegalArgumentException e) {+ throw new IllegalArgumentException(+ "embedded " + format.toUpperCase(Locale.ROOT) + " image data is not valid Base64", e);+ }+ try {+ state.embeddedPixels +=+ RasterImageValidator.validate(+ data, format, RasterImageValidator.MAX_PIXELS - state.embeddedPixels);+ } catch (IllegalArgumentException e) {+ throw new IllegalArgumentException(+ "embedded " + format.toUpperCase(Locale.ROOT) + " image: " + e.getMessage(), e);+ }+ }++ /** Limits shared by SVG graphics, metadata, and embedded raster images throughout one upload. */+ private static final class ValidationState {+ int elementCount;+ int embeddedImageCount;+ long embeddedPixels;+ }++ private static void validateLocalReference(String value) {+ if (value.length() < 2 || value.charAt(0) != '#') {+ throw new IllegalArgumentException("reference must be a local fragment starting with '#'");+ }+ }++ private static void validateUrlReferences(String value) {+ for (int i = 0; i < value.length(); i++) {+ if (!value.regionMatches(true, i, "url(", 0, 4)) {+ continue;+ }+ int cursor = skipCssWhitespace(value, i + 4);+ char quote = cursor < value.length() ? value.charAt(cursor) : 0;+ boolean quoted = quote == '\'' || quote == '"';+ if (quoted) {+ cursor++;+ }+ if (cursor >= value.length() || value.charAt(cursor++) != '#') {+ throw new IllegalArgumentException(+ "CSS url() at character %d must reference a local fragment starting with '#', for example url(#paint); external and empty references are not allowed"+ .formatted(i + 1));+ }+ int fragmentStart = cursor;+ while (cursor < value.length()) {+ char ch = value.charAt(cursor);+ if (quoted ? ch == quote : ch == ')' || isCssWhitespace(ch)) {+ break;+ }+ if (ch == '(' || !quoted && (ch == '\'' || ch == '"')) {+ throw new IllegalArgumentException(+ "Malformed CSS url() reference at character %d: %s at character %d; use url(#paint) or url('#paint')"+ .formatted(+ i + 1,+ ch == '('+ ? "nested opening parenthesis '('"+ : "quote inside an unquoted reference",+ cursor + 1));+ }+ cursor++;+ }+ if (cursor == fragmentStart) {+ throw new IllegalArgumentException(+ "CSS url() at character %d has an empty fragment identifier; add an SVG element ID after '#', for example url(#paint)"+ .formatted(i + 1));+ }+ if (quoted) {+ if (cursor >= value.length() || value.charAt(cursor++) != quote) {+ throw new IllegalArgumentException(+ "Unterminated CSS url() reference at character %d: missing closing %s quote; use url('#paint') or url(\"#paint\")"+ .formatted(i + 1, quote == '\'' ? "single" : "double"));+ }+ }+ cursor = skipCssWhitespace(value, cursor);+ if (cursor >= value.length() || value.charAt(cursor) != ')') {+ throw new IllegalArgumentException(+ "Malformed or unterminated CSS url() reference at character %d: expected ')' at character %d after the local fragment; use url(#paint) or url('#paint')"+ .formatted(i + 1, cursor + 1));+ }+ // Each URL is consumed once; a malformed URL fails instead of retrying at later offsets.+ i = cursor;+ }+ }++ private static int skipCssWhitespace(String value, int cursor) {+ while (cursor < value.length() && isCssWhitespace(value.charAt(cursor))) {+ cursor++;+ }+ return cursor;+ }++ private static boolean isCssWhitespace(char ch) {+ return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '\f';+ }++ private static void validateCss(String css) {+ // CSS escapes can hide function and at-rule names from the checks below. For example,+ // u\72l(...) is parsed by browsers as url(...).+ if (css.indexOf('\\') >= 0) {+ throw new IllegalArgumentException("CSS escapes (backslashes) are not allowed");+ }++ String lower = css.toLowerCase(Locale.ROOT);++ // Image functions can load string paths without using url(...).+ for (String forbidden : FORBIDDEN_CSS_CONSTRUCTS) {+ if (lower.contains(forbidden)) {+ throw new IllegalArgumentException("CSS construct '" + forbidden + "' is not allowed");+ }+ }++ validateUrlReferences(css);+ }++ private static String findExternalScheme(String value) {+ String lower = value.toLowerCase(Locale.ROOT);++ for (String scheme : EXTERNAL_SCHEMES) {+ if (lower.contains(scheme)) {+ return scheme;+ }+ }++ return null;+ }++ private static String nodeType(Node node) {+ return switch (node.getNodeType()) {+ case Node.PROCESSING_INSTRUCTION_NODE -> "processing instruction";+ case Node.DOCUMENT_TYPE_NODE -> "document type declaration";+ case Node.ENTITY_NODE, Node.ENTITY_REFERENCE_NODE -> "entity reference";+ default -> "XML node type " + node.getNodeType();+ };+ }+}diff --git a/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.java b/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.javaindex c111038ce..c57a38f0d 100644--- a/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.java@@ -19,6 +19,7 @@package org.openremote.manager.map;import com.fasterxml.jackson.databind.node.ObjectNode;+import jakarta.ws.rs.ForbiddenException;import jakarta.ws.rs.ServerErrorException;import jakarta.ws.rs.WebApplicationException;import jakarta.ws.rs.core.HttpHeaders;@@ -46,6 +47,9 @@ public class MapResourceImpl extends WebResource implements MapResource {@Overridepublic ObjectNode saveSettings(RequestParams requestParams, MapConfig mapConfig) {+ if (!isSuperUser()) {+ throw new ForbiddenException("Only super admin can save map settings");+ }return mapService.saveMapConfig(mapConfig);}@@ -70,6 +74,10 @@ public class MapResourceImpl extends WebResource implements MapResource {@Overridepublic ObjectNode uploadMap(RequestParams requestParams, String filename) {+ if (!isSuperUser()) {+ throw new ForbiddenException("Only super admin can upload images");+ }+// Starting with Resteasy 6.2.15.Final, request.getContentLength() returns -1 if Content-Length// header is not setif (request.getContentLength() > mapService.customMapLimit) {@@ -100,6 +108,10 @@ public class MapResourceImpl extends WebResource implements MapResource {@Overridepublic ObjectNode deleteMap(RequestParams requestParams) {+ if (!isSuperUser()) {+ throw new ForbiddenException("Only super admin can delete maps");+ }+try {mapService.deleteUploadedFile();return mapService.getMapSettings(diff --git a/manager/src/main/java/org/openremote/manager/syslog/SyslogResourceImpl.java b/manager/src/main/java/org/openremote/manager/syslog/SyslogResourceImpl.javaindex f9e7d4a39..bb192644f 100644--- a/manager/src/main/java/org/openremote/manager/syslog/SyslogResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/syslog/SyslogResourceImpl.java@@ -21,6 +21,7 @@ package org.openremote.manager.syslog;import static org.openremote.model.syslog.SyslogConfig.DEFAULT_LIMIT;import jakarta.ws.rs.BeanParam;+import jakarta.ws.rs.ForbiddenException;import jakarta.ws.rs.core.Response;import jakarta.ws.rs.core.UriBuilder;import java.time.Instant;@@ -82,16 +83,25 @@ public class SyslogResourceImpl extends WebResource implements SyslogResource {@Overridepublic void clearEvents(@BeanParam RequestParams requestParams) {+ if (!isSuperUser()) {+ throw new ForbiddenException("Only super admin can clear stored events");+ }syslogService.clearStoredEvents();}@Overridepublic SyslogConfig getConfig(@BeanParam RequestParams requestParams) {+ if (!isSuperUser()) {+ throw new ForbiddenException("Only super admin can read the logging configuration");+ }return syslogService.getConfig();}@Overridepublic void updateConfig(@BeanParam RequestParams requestParams, SyslogConfig config) {+ if (!isSuperUser()) {+ throw new ForbiddenException("Only super admin can update the logging configuration");+ }syslogService.setConfig(config);}}diff --git a/manager/test/src/groovy/org/openremote/manager/app/ConfigurationImageStorageTest.groovy b/manager/test/src/groovy/org/openremote/manager/app/ConfigurationImageStorageTest.groovynew file mode 100644index 000000000..425640231--- /dev/null+++ b/manager/test/src/groovy/org/openremote/manager/app/ConfigurationImageStorageTest.groovy@@ -0,0 +1,329 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * SPDX-License-Identifier: AGPL-3.0-or-later+ */+package org.openremote.manager.app++import org.openremote.model.file.FileInfo+import spock.lang.Specification+import spock.lang.TempDir++import javax.imageio.ImageIO+import java.awt.image.BufferedImage+import java.nio.file.Files+import java.nio.file.Path++import static org.openremote.manager.app.ConfigurationService.MANAGER_CONFIG_IMAGE_URL_PREFIX++class ConfigurationImageStorageTest extends Specification {++ @TempDir+ Path directory++ ConfigurationService service+ Path images+ Path publicImages+ byte[] png++ def setup() {+ images = Files.createDirectories(directory.resolve("stored/images"))+ publicImages = Files.createDirectories(directory.resolve("public/images"))+ service = new TestConfigurationService(imageRoot: images, pathPublicRoot: directory.resolve("public"))+ def output = new ByteArrayOutputStream()+ ImageIO.write(new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB), "png", output)+ png = output.toByteArray()+ }++ def "repeated uploads replace the image at the requested filename without accumulating files"() {+ given:+ Files.createDirectories(images.resolve("default"))+ Files.write(images.resolve("default/logo.png"), png)+ def file = new FileInfo("logo.png", Base64.encoder.encodeToString(png), true)+ def image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB)+ image.setRGB(0, 0, 0xff0000)+ def output = new ByteArrayOutputStream()+ ImageIO.write(image, "png", output)+ def replacement = output.toByteArray()++ when:+ def first = service.saveManagerConfigImage("default/logo.png", file)+ def second = service.saveManagerConfigImage("/images/default/logo.png",+ new FileInfo("logo.png", Base64.encoder.encodeToString(replacement), true))++ then:+ first == "default/logo.png"+ second == first+ Files.readAllBytes(images.resolve("default/logo.png")) == replacement+ Files.readAllBytes(service.getManagerConfigImage(first).orElseThrow().toPath()) == replacement+ Files.list(images.resolve("default")).withCloseable { it.count() } == 1+ }++ def "a rejected replacement leaves the existing image intact"() {+ given:+ Files.write(images.resolve("logo.png"), png)++ when:+ service.saveManagerConfigImage("logo.png",+ new FileInfo("logo.png", Base64.encoder.encodeToString("not an image".bytes), true))++ then:+ thrown(IllegalArgumentException)+ Files.readAllBytes(images.resolve("logo.png")) == png+ Files.list(images).withCloseable { it.count() } == 1+ }++ def "a failed replacement removes the temporary file and preserves the stored image"() {+ given:+ def stored = images.toRealPath().resolve("logo.png") // toRealPath() is used for macOS compatibility+ def original = "existing image".bytes+ Files.write(stored, original)+ service = Spy(service)+ def moveFailure = new IOException("image replacement failed")+ Path temporary++ when:+ service.saveManagerConfigImage("logo.png",+ new FileInfo("logo.png", Base64.encoder.encodeToString(png), true))++ then:+ 1 * service.replaceManagerConfigImage(_ as Path, stored) >> { Path source, Path target ->+ temporary = source+ assert Files.readAllBytes(source) == png+ assert Files.readAllBytes(target) == original+ throw moveFailure+ }+ def failure = thrown(IOException)+ failure.is(moveFailure)+ temporary != null+ !Files.exists(temporary)+ Files.readAllBytes(stored) == original+ Files.list(images).withCloseable { it.count() } == 1+ }++ def "rejects uploads targeting an existing directory"() {+ given:+ def target = Files.createDirectories(images.resolve("default/logo.png"))+ def existingFile = target.resolve("keep.txt")+ if (populated) {+ Files.writeString(existingFile, "existing content")+ }++ when:+ service.saveManagerConfigImage("default/logo.png",+ new FileInfo("logo.png", Base64.encoder.encodeToString(png), true))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message == "Image upload path is a directory; provide an image filename"+ Files.isDirectory(target)+ Files.list(target).withCloseable { it.count() } == (populated ? 1 : 0)+ !populated || Files.readString(existingFile) == "existing content"+ Files.list(target.parent).withCloseable { it.count() } == 1++ where:+ populated << [false, true]+ }++ def "upload path errors explain which path rule was violated"() {+ when:+ service.saveManagerConfigImage(filename, new FileInfo("logo.png", Base64.encoder.encodeToString(png), true))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains(reason)+ !failure.message.contains(images.toString())+ Files.list(images).withCloseable { it.count() } == 0++ where:+ filename | reason+ "/logo.png" | "absolute paths are not allowed"+ "default\\logo.png" | "contains a backslash; use '/'"+ "../logo.png" | "contains '..'; parent directory traversal is not allowed"+ "./logo.png" | "starts with './'; remove it"+ }++ def "upload errors identify a parent path that is a file without exposing the storage root"() {+ given:+ Files.write(images.resolve("parent"), png)++ when:+ service.saveManagerConfigImage("parent/logo.png", new FileInfo("logo.png", Base64.encoder.encodeToString(png), true))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("parent 'parent' is not a directory")+ !failure.message.contains(images.toString())+ Files.readAllBytes(images.resolve("parent")) == png+ }++ def "legacy files with supported image extensions are returned without decoding their contents"() {+ given:+ Files.write(images.resolve(filename), contents.bytes)++ expect:+ Files.readAllBytes(service.getManagerConfigImage(filename).orElseThrow().toPath()) == contents.bytes++ where:+ filename | contents+ "old.svg" | "<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>"+ "old.SvG" | "<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>"+ "old.png" | "<html/>"+ "old.PNG" | "<html/>"+ "old.jpg" | "legacy JPEG"+ "old.JPEG" | "legacy JPEG"+ "old.ICO" | "legacy ICO"+ }++ def "unsupported image extensions are rejected in persisted and public image directories"() {+ given:+ [images, publicImages].each { imageRoot ->+ def file = imageRoot.resolve(filename)+ Files.createDirectories(file.parent)+ Files.write(file, "<html><a href='https://example.invalid/'>Continue</a></html>".bytes)+ }++ expect:+ service.getManagerConfigImage(filename).isEmpty()++ where:+ filename << [+ "old.html",+ "old.HTML",+ "payload.js",+ "logo.gif",+ "logo.webp",+ "logo.svg.html",+ "logo",+ "logo.",+ "nested.svg/page.html"+ ]+ }++ def "legacy images larger than the upload limit are returned without truncation"() {+ given:+ Files.write(images.resolve("large.png"), new byte[ImageUploadValidator.MAX_FILE_SIZE + 1])++ expect:+ service.getManagerConfigImage("large.png").orElseThrow().length() == ImageUploadValidator.MAX_FILE_SIZE + 1+ }++ def "public fallback images are limited to the images directory without decoding"() {+ given:+ Files.write(publicImages.resolve("logo.png"), png)+ Files.write(publicImages.resolve("unsafe.svg"), "<svg xmlns='http://www.w3.org/2000/svg' onload='alert(1)'/>".bytes)+ Files.write(directory.resolve("public/secret.png"), png)++ expect:+ Files.readAllBytes(service.getManagerConfigImage("logo.png").orElseThrow().toPath()) == png+ service.getManagerConfigImage("unsafe.svg").orElseThrow().toPath() == publicImages.resolve("unsafe.svg").toRealPath()+ service.getManagerConfigImage("../secret.png").isEmpty()+ }++ def "paths containing the root as a later substring are still outside the image directory"() {+ given:+ def outside = directory.resolve("outside").resolve(images.toString().substring(1))+ Files.createDirectories(outside)+ Files.write(outside.resolve("logo.png"), png)+ def relative = images.relativize(outside.resolve("logo.png")).toString()++ expect:+ // A string contains() check accepted an outside path containing the full allowed path later on.+ service.getManagerConfigImage(relative).isEmpty()++ when:+ service.saveManagerConfigImage(relative, new FileInfo("logo.png", Base64.encoder.encodeToString(png), true))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("parent directory traversal is not allowed")+ Files.readAllBytes(outside.resolve("logo.png")) == png+ }++ def "symbolic links below image roots cannot be read or used for uploads"() {+ given:+ def outside = Files.createDirectories(directory.resolve("outside"))+ Files.write(outside.resolve("logo.png"), png)+ Files.createSymbolicLink(images.resolve("linked"), outside)+ Files.write(images.resolve("original.png"), png)+ Files.createSymbolicLink(images.resolve("alias.png"), images.resolve("original.png"))++ expect:+ service.getManagerConfigImage("linked/logo.png").isEmpty()+ service.getManagerConfigImage("alias.png").isEmpty()++ when:+ service.saveManagerConfigImage("linked/logo.png", new FileInfo("logo.png", Base64.encoder.encodeToString(png), true))++ then:+ def directoryFailure = thrown(IllegalArgumentException)+ directoryFailure.message.contains("symbolic link at 'linked'")+ directoryFailure.message.contains("symbolic links are not allowed")+ !directoryFailure.message.contains(images.toString())+ Files.list(outside).withCloseable { it.count() } == 1++ when:+ service.saveManagerConfigImage("alias.png", new FileInfo("logo.png", Base64.encoder.encodeToString(png), true))++ then:+ def fileFailure = thrown(IllegalArgumentException)+ fileFailure.message.contains("symbolic link at 'alias.png'")+ !fileFailure.message.contains(images.toString())+ Files.isSymbolicLink(images.resolve("alias.png"))+ Files.readAllBytes(images.resolve("original.png")) == png+ }++ def "copying a fallback branding image validates it and preserves the filename"() {+ given:+ Files.write(publicImages.resolve("logo.png"), png)++ when:+ def reference = service.fixImageRef("images/logo.png")+ def filename = reference.replace(MANAGER_CONFIG_IMAGE_URL_PREFIX, "")++ then:+ filename == "logo.png"+ Files.readAllBytes(service.getManagerConfigImage(filename).orElseThrow().toPath()) == png+ Files.exists(images.resolve("logo.png"))++ and:+ service.fixImageRef("../secret.png") == "../secret.png"+ }++ def "invalid fallback branding images are not imported into persisted storage"() {+ given:+ Files.write(publicImages.resolve(filename), contents.bytes)++ expect:+ service.fixImageRef("images/${filename}") == "images/${filename}"+ !Files.exists(images.resolve(filename))++ where:+ filename | contents+ "old.html" | "<html><script>alert(1)</script></html>"+ "old.svg" | "<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>"+ "old.png" | "<html/>"+ }++ private static class TestConfigurationService extends ConfigurationService {+ Path imageRoot++ @Override+ protected Path getPersistedManagerConfigImagePath() {+ imageRoot+ }+ }+}diff --git a/manager/test/src/groovy/org/openremote/manager/app/ImageUploadValidatorTest.groovy b/manager/test/src/groovy/org/openremote/manager/app/ImageUploadValidatorTest.groovynew file mode 100644index 000000000..9f95621ea--- /dev/null+++ b/manager/test/src/groovy/org/openremote/manager/app/ImageUploadValidatorTest.groovy@@ -0,0 +1,1319 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * SPDX-License-Identifier: AGPL-3.0-or-later+ */+package org.openremote.manager.app++import spock.lang.Specification+import spock.lang.Timeout++import java.awt.image.BufferedImage+import java.nio.charset.Charset+import java.nio.charset.StandardCharsets+import java.nio.ByteBuffer+import java.nio.ByteOrder+import javax.imageio.ImageIO++import static org.openremote.manager.app.ConfigurationService.MANAGER_CONFIG_IMAGE_URL_PREFIX++class ImageUploadValidatorTest extends Specification {++ def "decodes and validates a PNG upload"() {+ given:+ def image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB)+ def output = new ByteArrayOutputStream()+ ImageIO.write(image, "png", output)+ def png = output.toByteArray()+ def contents = "data:image/png;base64," + Base64.encoder.encodeToString(png)++ expect:+ ImageUploadValidator.decodeAndValidate("logo.png", contents) == png+ }++ def "rejects unsupported extensions even when the bytes are a valid image"() {+ given:+ def image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB)+ def output = new ByteArrayOutputStream()+ ImageIO.write(image, "png", output)+ def contents = Base64.encoder.encodeToString(output.toByteArray())++ when:+ ImageUploadValidator.decodeAndValidate("logo.$extension", contents)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("Unsupported image extension")++ where:+ extension << ["html", "js", "gif", "svgz"]+ }++ def "rejects non-raster content disguised with a raster extension"() {+ when:+ ImageUploadValidator.validate(filename, content.getBytes(StandardCharsets.UTF_8))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("No image decoder recognizes")++ where:+ filename | content+ "logo.png" | "<!doctype html><script>alert(1)</script>"+ "logo.jpg" | "alert('not an image')"+ "logo.ico" | "<svg xmlns='http://www.w3.org/2000/svg'/>"+ }++ def "rejects non-SVG content disguised with an SVG extension"() {+ when:+ ImageUploadValidator.validate("logo.svg", content.getBytes(StandardCharsets.UTF_8))++ then:+ thrown(IllegalArgumentException)++ where:+ content << [+ "<html xmlns='http://www.w3.org/1999/xhtml'><script>alert(1)</script></html>",+ "alert('not an SVG')"+ ]+ }++ def "accepts SVG XML 1.0 uploads in supported encodings"() {+ given:+ def declaration = declaredEncoding == null ? "" : "<?xml version='1.0' encoding='${declaredEncoding}'?>"+ def svg = (bom ? "\uFEFF" : "") + declaration + "<svg xmlns='http://www.w3.org/2000/svg'><text>Café 日本</text></svg>"+ def data = svg.getBytes(Charset.forName(encoding))++ expect:+ ImageUploadValidator.decodeAndValidate("logo.svg", Base64.encoder.encodeToString(data)) == data++ where:+ encoding | declaredEncoding | bom+ "UTF-8" | null | false+ "UTF-8" | "UTF-8" | false+ "UTF-8" | "utf-8" | true+ "UTF-8" | null | true+ "UTF-16BE" | null | true+ "UTF-16LE" | null | true+ "UTF-16BE" | "UTF-16" | true+ "UTF-16LE" | "utf-16" | true+ "UTF-16BE" | "UTF-16BE" | false+ "UTF-16LE" | "UTF-16LE" | false+ "UTF-16LE" | "utf-16le" | true+ }++ def "rejects SVG XML 1.1 uploads"() {+ given:+ def svg = "<?xml version='1.1' encoding='${encoding}'?><svg xmlns='http://www.w3.org/2000/svg'/>"++ when:+ ImageUploadValidator.validate("logo.svg", svg.getBytes(Charset.forName(encoding)))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message == "SVG XML version must be 1.0"++ where:+ encoding << ["UTF-8", "UTF-16"]+ }++ def "rejects SVG XML encodings outside UTF-8 and UTF-16"() {+ given:+ def text = encoding == "ISO-2022-JP" ? "日本" : "Test"+ def declaration = declaredEncoding == null ? "<?xml version='1.0'?>" : "<?xml version='1.0' encoding='${declaredEncoding}'?>"+ def svg = (bom ? "\uFEFF" : "") + declaration + "<svg xmlns='http://www.w3.org/2000/svg'><text>${text}</text></svg>"++ when:+ ImageUploadValidator.validate("logo.svg", svg.getBytes(Charset.forName(encoding)))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message == "SVG XML encoding must be UTF-8 or UTF-16"++ where:+ encoding | declaredEncoding | bom+ "UTF-32BE" | "UTF-32" | false+ "UTF-32LE" | "UTF-32LE" | false+ "UTF-32BE" | null | false+ "UTF-32LE" | null | false+ "IBM037" | "IBM037" | false+ "ISO-2022-JP" | "ISO-2022-JP" | false+ "ISO-8859-1" | "ISO-8859-1" | false+ "UTF-8" | "ISO-2022-JP" | true+ }++ def "rejects raster images whose extension does not match their content"() {+ given:+ def image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB)+ def output = new ByteArrayOutputStream()+ ImageIO.write(image, "png", output)++ when:+ ImageUploadValidator.validate("logo.jpg", output.toByteArray())++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message == "Image contains PNG data, but its extension requires JPEG"+ }++ def "reports dimensions and limits for an oversized raster image"() {+ given:+ def image = new BufferedImage(4097, 1, BufferedImage.TYPE_INT_RGB)+ def output = new ByteArrayOutputStream()+ ImageIO.write(image, "png", output)++ when:+ ImageUploadValidator.validate("logo.png", output.toByteArray())++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("4097x1 pixels")+ failure.message.contains("4096x4096")+ }++ def "rejects CSS escapes that hide external URLs"() {+ when:+ ImageUploadValidator.validate("logo.svg", svg.getBytes(StandardCharsets.UTF_8))++ then:+ // The escaped function name used to bypass the literal url(...) check.+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("CSS escapes (backslashes) are not allowed")++ where:+ svg << [+ "<svg xmlns='http://www.w3.org/2000/svg'><style>rect{fill:u\\72l(https://example.com/image.png)}</style><rect width='1' height='1'/></svg>",+ "<svg xmlns='http://www.w3.org/2000/svg'><rect width='1' height='1' style='fill:u\\72l(https://example.com/image.png)'/></svg>"+ ]+ }++ def "accepts local CSS fragment references"() {+ given:+ def svg = "<svg xmlns='http://www.w3.org/2000/svg'><style>rect{fill:url(#paint)}</style><defs><linearGradient id='paint'><stop offset='0%' stop-color='red'/></linearGradient></defs><rect width='1' height='1' style='stroke:url(#paint)'/></svg>"++ expect:+ ImageUploadValidator.validate("logo.svg", svg.getBytes(StandardCharsets.UTF_8)) == null+ }++ def "accepts SVG images containing validated embedded PNG and JPEG data"() {+ given:+ def encoded = Base64.encoder.encodeToString(raster(format))+ def wrapped = encoded.toList().collate(40).collect { it.join() }.join("\n ")+ def svg = """<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">+ <image width="1" height="1" ${attribute}="data:image/${format};base64,${wrapped}"/>+ </svg>"""++ expect:+ ImageUploadValidator.validate("logo.svg", svg.bytes) == null++ where:+ format << ["png", "jpeg"]+ combined:+ attribute << ["href", "xlink:href"]+ }++ def "rejects external and unsupported image references inside SVGs"() {+ given:+ def svg = """<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">+ <image width="1" height="1" ${attribute}="${reference}"/>+ </svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("SVG <image> attribute '${attribute}'")+ failure.message.contains("embedded images must use data:image/png;base64, or data:image/jpeg;base64,")++ where:+ attribute << ["href", "xlink:href"]+ combined:+ reference << [+ "https://example.invalid/logo.png",+ "//example.invalid/logo.png",+ MANAGER_CONFIG_IMAGE_URL_PREFIX + "logo.png",+ "images/logo.png",+ "#another-image",+ "javascript:alert(1)",+ "file:///tmp/logo.png",+ "data:image/svg+xml;base64,PHN2Zy8+",+ "data:text/html;base64,PHNjcmlwdD4=",+ "data:image/gif;base64,R0lGODlh",+ "data:image/png,%89PNG",+ "data:image/png;charset=utf-8;base64,aW52YWxpZA=="+ ]+ }++ def "embedded SVG images must match the advertised raster format and decode successfully"() {+ given:+ def payload = switch (content) {+ case "jpeg" -> raster("jpeg")+ case "png" -> raster("png")+ case "html" -> "<html><script>alert(1)</script></html>".bytes+ default -> Arrays.copyOf(raster("png"), 33)+ }+ def encoded = Base64.encoder.encodeToString(payload)+ def svg = """<svg xmlns="http://www.w3.org/2000/svg">+ <image href="data:image/${format};base64,${encoded}"/>+ </svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("SVG <image> attribute 'href': embedded")+ failure.message.contains(reason)++ where:+ format | content | reason+ "png" | "jpeg" | "Image contains JPEG data"+ "jpeg" | "png" | "Image contains PNG data"+ "png" | "html" | "No image decoder recognizes"+ "png" | "truncated" | "Could not decode PNG image data"+ }++ def "embedded SVG image errors describe invalid Base64 data"() {+ when:+ ImageUploadValidator.validate("logo.svg",+ "<svg xmlns='http://www.w3.org/2000/svg'><image href='data:image/png;base64,${encoded}'/></svg>".bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("SVG <image> attribute 'href': embedded PNG image data")+ failure.message.contains(reason)++ where:+ encoded | reason+ "" | "is empty"+ "%%%" | "is not valid Base64"+ "aW52YWxpZA==!" | "is not valid Base64"+ }++ def "both SVG image references are checked even when one shadows the other"() {+ given:+ def reference = "data:image/png;base64," + Base64.encoder.encodeToString(raster("png"))+ def svg = """<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">+ <image href="${externalHref ? 'https://example.invalid/logo.png' : reference}"+ xlink:href="${externalHref ? reference : 'https://example.invalid/logo.png'}"/>+ </svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("external URLs and other embedded formats are not allowed")++ where:+ externalHref << [true, false]+ }++ def "embedded SVG images retain event handler and CSS restrictions"() {+ given:+ def encoded = Base64.encoder.encodeToString(raster("png"))+ def svg = """<svg xmlns="http://www.w3.org/2000/svg">+ <image href="data:image/png;base64,${encoded}" ${attributes}/>${content}+ </svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains(reason)++ where:+ attributes | content | reason+ "onload='alert(1)'" | "" | "event handlers are not allowed"+ "style='fill:u\\72l(//example.invalid/paint.svg#paint)'" | "" | "CSS escapes"+ "xml:base='https://example.invalid/'" | "" | "base URIs are not allowed"+ "" | "<script>alert(1)</script>" | "Unsupported SVG element: script"+ "" | "<use href='data:image/png;base64,aW52YWxpZA=='/>" | "local fragment starting with '#'"+ }++ def "embedded SVG images obey raster dimensions before decoding"() {+ given:+ def header = Arrays.copyOf(raster("png"), 33)+ ByteBuffer.wrap(header).order(ByteOrder.BIG_ENDIAN).putInt(16, 4097)+ def encoded = Base64.encoder.encodeToString(header)++ when:+ ImageUploadValidator.validate("logo.svg",+ "<svg xmlns='http://www.w3.org/2000/svg'><image width='1' height='1' href='data:image/png;base64,${encoded}'/></svg>".bytes)++ then:+ // Display dimensions must not hide the dimensions used for raster allocation.+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("embedded PNG image: Image frame 1 is 4097x1 pixels")+ failure.message.contains("4096x4096")+ }++ def "embedded SVG images share one pixel budget checked before decoding"() {+ given:+ def first = Base64.encoder.encodeToString(raster("png", 4000, 2000))+ def header = Arrays.copyOf(raster("png"), 33)+ ByteBuffer.wrap(header).order(ByteOrder.BIG_ENDIAN).putInt(16, 4000).putInt(20, 2001)+ def second = Base64.encoder.encodeToString(header)+ def svg = """<svg xmlns="http://www.w3.org/2000/svg">+ <image href="data:image/png;base64,${first}"/>+ <g><image href="data:image/png;base64,${second}"/></g>+ </svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ // The second header has no image data: budget rejection must happen before decoding it.+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("remaining pixel budget is 8000000")+ failure.message.contains("maximum across images is 16000000 pixels")+ }++ def "accepts SVGs with up to 32 embedded image references"() {+ given:+ def reference = "data:image/png;base64," + Base64.encoder.encodeToString(raster("png"))+ def svg = "<svg xmlns='http://www.w3.org/2000/svg'>" ++ "<image href='${reference}'/>".repeat(32) + "</svg>"++ expect:+ ImageUploadValidator.validate("logo.svg", svg.bytes) == null+ }++ def "rejects SVGs with more than 32 embedded image references"() {+ given:+ def reference = "data:image/png;base64," + Base64.encoder.encodeToString(raster("png"))+ def svg = "<svg xmlns='http://www.w3.org/2000/svg'>" ++ "<image href='${reference}'/>".repeat(32) ++ "<g><image href='${reference}'/></g></svg>"++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("more than 32 embedded image references")+ }++ def "rejects PNG animation frames in #location"() {+ given:+ def png = raster("png")+ def animation = ByteBuffer.allocate(20).order(ByteOrder.BIG_ENDIAN)+ .putInt(8).putInt(0x6163544c).putInt(2).putInt(0).putInt(0).array()+ def crc = new java.util.zip.CRC32()+ crc.update(animation, 4, 12)+ ByteBuffer.wrap(animation).order(ByteOrder.BIG_ENDIAN).putInt(16, (int) crc.value)+ def output = new ByteArrayOutputStream()+ output.write(png, 0, 33)+ output.write(animation)+ output.write(png, 33, png.length - 33)+ def animated = output.toByteArray()++ when:+ ImageUploadValidator.validate(filename, wrap(animated))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("Animated PNG images are not supported")++ where:+ location | filename | wrap+ "a PNG upload" | "logo.png" | { byte[] payload -> payload }+ "an SVG image" | "logo.svg" | { byte[] payload ->+ def encoded = Base64.encoder.encodeToString(payload)+ "<svg xmlns='http://www.w3.org/2000/svg'><image href='data:image/png;base64,${encoded}'/></svg>".bytes+ }+ "the first ICO entry" | "logo.ico" | { byte[] payload -> ico(payload, 1, 1) }+ "an ICO entry after a static PNG" | "logo.ico" | { byte[] payload ->+ ico([raster("png"), payload], 1, 1)+ }+ "an ICO entry after a DIB" | "logo.ico" | { byte[] payload -> ico([dib(1, 2), payload], 1, 1) }+ }++ def "rejects CSS image functions that accept string URLs"() {+ given:+ def svg = "<svg xmlns='http://www.w3.org/2000/svg'><rect width='1' height='1' style=\"mask-image:image-set('https://example.com/image.png')\"/></svg>"++ when:+ ImageUploadValidator.validate("logo.svg", svg.getBytes(StandardCharsets.UTF_8))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("SVG <rect> attribute 'style'")+ failure.message.contains("image-set(")+ }++ def "rejects CSS src() references"() {+ given:+ def svg = "<svg xmlns='http://www.w3.org/2000/svg'>${body}</svg>"++ when:+ ImageUploadValidator.validate("logo.svg", svg.getBytes(StandardCharsets.UTF_8))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.startsWith(context)+ failure.message.contains("CSS construct 'src(' is not allowed")++ where:+ body | context+ "<style>rect{fill:src('paint.svg#paint')}</style>" | "SVG <style>:"+ "<style>rect{fill:SRC(var(--paint))}</style>" | "SVG <style>:"+ "<rect style=\"fill:src('paint.svg#paint')\"/>" | "SVG <rect> attribute 'style':"+ "<rect style=\"fill:SRC(var(--paint))\"/>" | "SVG <rect> attribute 'style':"+ "<rect fill=\"src('paint.svg#paint')\"/>" | "SVG <rect> attribute 'fill':"+ "<rect fill=\"SRC(var(--paint))\"/>" | "SVG <rect> attribute 'fill':"+ }++ def "reports the attribute and rule for an external SVG reference"() {+ given:+ def svg = "<svg xmlns='http://www.w3.org/2000/svg'><use href='https://example.com/icon.svg#shape'/></svg>"++ when:+ ImageUploadValidator.validate("logo.svg", svg.getBytes(StandardCharsets.UTF_8))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("SVG <use> attribute 'href'")+ failure.message.contains("local fragment starting with '#'")+ !failure.message.contains("example.com")+ }++ def "rejects active foreign XML inside SVG metadata"() {+ when:+ ImageUploadValidator.validate("logo.svg", svg.getBytes(StandardCharsets.UTF_8))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("SVG metadata element <script> uses an unsupported namespace")++ where:+ svg << [+ '''<svg xmlns="http://www.w3.org/2000/svg"><metadata>+ <script xmlns="http://www.w3.org/1999/xhtml">document.documentElement.setAttribute('data-executed', 'yes')</script>+ </metadata></svg>''',+ '''<svg xmlns="http://www.w3.org/2000/svg"><metadata>+ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">+ <script xmlns="http://www.w3.org/1999/xhtml">document.documentElement.setAttribute('data-executed', 'yes')</script>+ </rdf:RDF>+ </metadata></svg>'''+ ]+ }++ def "accepts standard descriptive SVG metadata"() {+ given:+ def svg = '''<svg xmlns="http://www.w3.org/2000/svg">+ <metadata>+ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"+ xmlns:dc="http://purl.org/dc/elements/1.1/">+ <rdf:Description rdf:about=""><dc:title>Logo</dc:title></rdf:Description>+ </rdf:RDF>+ </metadata>+ </svg>'''++ expect:+ ImageUploadValidator.validate("logo.svg", svg.getBytes(StandardCharsets.UTF_8)) == null+ }++ def "accepts Creative Commons work metadata"() {+ given:+ def svg = """<svg xmlns="http://www.w3.org/2000/svg">+ <metadata>+ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"+ xmlns:dc="http://purl.org/dc/elements/1.1/"+ xmlns:cc="${ccNamespace}">+ <cc:Work rdf:about="">+ <dc:format>image/svg+xml</dc:format>+ </cc:Work>+ </rdf:RDF>+ </metadata>+ </svg>"""++ expect:+ ImageUploadValidator.validate("logo.svg", svg.getBytes(StandardCharsets.UTF_8)) == null++ where:+ ccNamespace << ["http://creativecommons.org/ns#", "http://web.resource.org/cc/"]+ }++ def "reports the position of malformed SVG XML"() {+ when:+ ImageUploadValidator.validate("logo.svg", "<svg xmlns='http://www.w3.org/2000/svg'><rect></svg>".getBytes(StandardCharsets.UTF_8))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.startsWith("Malformed SVG XML at line 1, column ")+ }++ def "accepts supported editor attributes on SVG elements"() {+ given:+ def svg = """<svg xmlns="http://www.w3.org/2000/svg"+ xmlns:editor="${namespace}" editor:version="1.4">+ <g editor:label="Logo" editor:groupmode="layer">+ <path editor:nodetypes="cccc" d="M0 0H1V1H0Z"/>+ </g>+ </svg>"""++ expect:+ // Namespace URIs identify editor metadata, regardless of the chosen XML prefix.+ ImageUploadValidator.validate("logo.svg", svg.bytes) == null++ where:+ namespace << [+ "http://www.inkscape.org/namespaces/inkscape",+ "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd",+ "http://www.serif.com/",+ "http://www.bohemiancoding.com/sketch/ns",+ "http://ns.adobe.com/AdobeIllustrator/10.0/",+ "http://ns.adobe.com/Graphs/1.0/",+ "http://schemas.microsoft.com/visio/2003/SVGExtensions/"+ ]+ }++ def "accepts Illustrator layers, graph attributes and export metadata"() {+ given:+ def svg = '''<svg xmlns="http://www.w3.org/2000/svg"+ xmlns:i="http://ns.adobe.com/AdobeIllustrator/10.0/"+ xmlns:graph="http://ns.adobe.com/Graphs/1.0/"+ xmlns:v="http://ns.adobe.com/Variables/1.0/"+ xmlns:sfw="http://ns.adobe.com/SaveForWeb/1.0/"+ viewBox="0 0 20 20" i:viewOrigin="0 20" i:pageBounds="0 20 20 0">+ <metadata>+ <v:variableSets><v:variableSet varSetName="Logo"><v:variables/></v:variableSet></v:variableSets>+ <sfw:sfw><sfw:slices><sfw:sliceSourceBounds x="0" y="0" width="20" height="20"/></sfw:slices></sfw:sfw>+ </metadata>+ <g i:layer="yes" i:dimmedPercent="50" i:rgbTrio="#4F008000FFFF">+ <rect width="20" height="20" i:knockout="Off" graph:whichSeries="0"/>+ </g>+ </svg>'''++ expect:+ ImageUploadValidator.validate("logo.svg", svg.bytes) == null+ }++ def "accepts Visio document, page, layer and text metadata"() {+ given:+ def svg = '''<svg xmlns="http://www.w3.org/2000/svg"+ xmlns:v="http://schemas.microsoft.com/visio/2003/SVGExtensions/"+ viewBox="0 0 20 20" xml:space="preserve">+ <v:documentProperties v:langID="1033" v:viewMarkup="false">+ <v:userDefs><v:ud v:nameU="msvNoAutoConnect" v:val="VT0(1):26"/></v:userDefs>+ </v:documentProperties>+ <g v:groupContext="foregroundPage">+ <v:pageProperties v:drawingScale="1" v:pageScale="1"/>+ <v:layer v:name="Logo" v:index="0"/>+ <g v:mID="1" v:groupContext="shape" v:layerMember="0">+ <v:textBlock v:margins="rect(4,4,4,4)"/>+ <v:textRect cx="10" cy="10" width="20" height="20"/>+ <rect width="20" height="20" fill="red"/>+ <text x="0" y="10" v:langID="1033"><v:paragraph v:horizAlign="1"/><v:tabList/>Logo</text>+ </g>+ </g>+ </svg>'''++ expect:+ ImageUploadValidator.validate("logo.svg", svg.bytes) == null+ }++ def "accepts XMP packet metadata with document history and descriptive URLs"() {+ given:+ def svg = '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">+ <metadata>+ <?xpacket begin="\uFEFF" id="W5M0MpCehiHzreSzNTczkc9d"?>+ <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core">+ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"+ xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"+ xmlns:dc="http://purl.org/dc/elements/1.1/"+ xmlns:xmp="http://ns.adobe.com/xap/1.0/"+ xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/"+ xmlns:xmpRights="http://ns.adobe.com/xap/1.0/rights/"+ xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/"+ xmlns:illustrator="http://ns.adobe.com/illustrator/1.0/"+ xmlns:stRef="http://ns.adobe.com/xap/1.0/sType/ResourceRef#"+ xmlns:stEvt="http://ns.adobe.com/xap/1.0/sType/ResourceEvent#"+ xmlns:stDim="http://ns.adobe.com/xap/1.0/sType/Dimensions#">+ <rdf:Description rdf:about="" xmp:CreatorTool="Adobe Illustrator"+ xmpMM:DocumentID="xmp.did:logo">+ <dc:title><rdf:Alt><rdf:li xml:lang="x-default">Logo</rdf:li></rdf:Alt></dc:title>+ <rdfs:label>Company logo</rdfs:label>+ <xmp:CreateDate>2026-10-07T12:00:00Z</xmp:CreateDate>+ <xmpMM:DerivedFrom rdf:parseType="Resource">+ <stRef:documentID>xmp.did:original</stRef:documentID>+ </xmpMM:DerivedFrom>+ <xmpMM:History><rdf:Seq><rdf:li rdf:parseType="Resource">+ <stEvt:action>saved</stEvt:action>+ <stEvt:softwareAgent>Adobe Illustrator</stEvt:softwareAgent>+ </rdf:li></rdf:Seq></xmpMM:History>+ <illustrator:StartupProfile>Web</illustrator:StartupProfile>+ <illustrator:ArtboardSize rdf:parseType="Resource">+ <stDim:w>20</stDim:w><stDim:h>20</stDim:h><stDim:unit>pixel</stDim:unit>+ </illustrator:ArtboardSize>+ <photoshop:AuthorsPosition>Designer</photoshop:AuthorsPosition>+ <xmpRights:WebStatement rdf:resource="https://example.invalid/license"/>+ </rdf:Description>+ </rdf:RDF>+ </x:xmpmeta>+ <?xpacket end="w"?>+ </metadata>+ <rect width="20" height="20" fill="red"/>+ </svg>'''++ expect:+ // Descriptive URLs are metadata values; they do not load resources in the browser.+ ImageUploadValidator.validate("logo.svg", svg.getBytes(StandardCharsets.UTF_8)) == null+ }++ def "new editor namespaces do not bypass SVG content restrictions"() {+ given:+ def svg = """<svg xmlns="http://www.w3.org/2000/svg" xmlns:editor="${namespace}">+ <editor:metadata ${attributes}>${content}</editor:metadata>+ </svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains(reason)++ where:+ namespace << [+ "http://ns.adobe.com/AdobeIllustrator/10.0/",+ "http://ns.adobe.com/Graphs/1.0/",+ "http://schemas.microsoft.com/visio/2003/SVGExtensions/"+ ]+ combined:+ attributes | content | reason+ "editor:onload='alert(1)'" | "" | "event handlers are not allowed"+ "editor:href='https://example.invalid/image.svg#shape'" | "" | "local fragment starting with '#'"+ "xml:base='https://example.invalid/'" | "" | "base URIs are not allowed"+ "editor:fill='u\\72l(//example.invalid/paint.svg#paint)'" | "" | "CSS escapes"+ "" | "<script>alert(1)</script>" | "SVG metadata element <script> uses an unsupported namespace"+ "" | "<script xmlns='http://www.w3.org/1999/xhtml'>alert(1)</script>" | "SVG metadata element <script> uses an unsupported namespace"+ "" | "<editor:metadata xmlns:editor='http://www.w3.org/1999/xhtml'/>" | "uses an unsupported namespace"+ }++ def "rejects unsafe content nested inside XMP metadata"() {+ given:+ def svg = """<svg xmlns="http://www.w3.org/2000/svg"><metadata>+ <x:xmpmeta xmlns:x="adobe:ns:meta/" xmlns:xmp="http://ns.adobe.com/xap/1.0/">+ <xmp:CreatorTool ${attributes}>${content}</xmp:CreatorTool>+ </x:xmpmeta>+ </metadata></svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains(reason)++ where:+ attributes | content | reason+ "onload='alert(1)'" | "" | "disallowed event handler attribute 'onload'"+ "xmp:onload='alert(1)'" | "" | "disallowed event handler attribute 'xmp:onload'"+ "" | "<script>alert(1)</script>" | "SVG metadata element <script> uses an unsupported namespace"+ "" | "<script xmlns='http://www.w3.org/1999/xhtml'>alert(1)</script>" | "SVG metadata element <script> uses an unsupported namespace"+ "" | "<link xmlns='http://www.w3.org/1999/xhtml' rel='stylesheet' href='https://example.invalid/style.css'/>" | "SVG metadata element <link> uses an unsupported namespace"+ "" | "<xmp:CreatorTool xmlns:xmp='https://example.invalid/metadata'/>" | "uses an unsupported namespace"+ "" | "<?xml-stylesheet href='https://example.invalid/style.css'?>" | "unsupported processing instruction"+ "" | "<?xml-model href='https://example.invalid/schema.xml'?>" | "unsupported processing instruction"+ "" | "<?xpacket-stylesheet href='https://example.invalid/style.css'?>" | "unsupported processing instruction"+ }++ def "descriptive XMP elements and packet markers are confined to metadata"() {+ when:+ ImageUploadValidator.validate("logo.svg", svg.getBytes(StandardCharsets.UTF_8))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains(reason)++ where:+ svg | reason+ "<svg xmlns='http://www.w3.org/2000/svg'><x:xmpmeta xmlns:x='adobe:ns:meta/'/></svg>" | "outside the SVG namespace"+ "<svg xmlns='http://www.w3.org/2000/svg' xmlns:xmp='http://ns.adobe.com/xap/1.0/' xmp:CreatorTool='Illustrator'/>" | "attribute namespace is not supported"+ "<?xpacket begin=''?><svg xmlns='http://www.w3.org/2000/svg'/>" | "unsupported processing instruction before or after its root"+ "<svg xmlns='http://www.w3.org/2000/svg'/><?xpacket end='w'?>" | "unsupported processing instruction before or after its root"+ "<svg xmlns='http://www.w3.org/2000/svg'><?xpacket begin=''?></svg>" | "SVG <svg> contains unsupported processing instruction"+ }++ def "XMP metadata obeys SVG nesting and element count limits"() {+ given:+ def content = nested+ ? "<xmp:History>".repeat(65) + "</xmp:History>".repeat(65)+ : "<xmp:CreatorTool/>".repeat(10_000)+ def svg = """<svg xmlns="http://www.w3.org/2000/svg"><metadata>+ <x:xmpmeta xmlns:x="adobe:ns:meta/" xmlns:xmp="http://ns.adobe.com/xap/1.0/">+ ${content}+ </x:xmpmeta>+ </metadata></svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains(reason)++ where:+ nested | reason+ true | "SVG metadata nesting exceeds 64 levels"+ false | "SVG contains more than 10000 elements"+ }++ def "accepts Sketch layer metadata with local XLink references"() {+ given:+ def svg = '''<svg xmlns="http://www.w3.org/2000/svg"+ xmlns:sketch="http://www.bohemiancoding.com/sketch/ns"+ xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 20 20">+ <defs><path id="shape" sketch:type="MSShapeGroup" d="M0 0H20V20H0Z"/></defs>+ <g sketch:type="MSPage"><use sketch:type="MSShapeGroup" xlink:href="#shape"/></g>+ </svg>'''++ expect:+ // Sketch exports include editor type attributes alongside standard SVG and XLink references.+ ImageUploadValidator.validate("logo.svg", svg.bytes) == null+ }++ def "rejects unsafe SVG content alongside Sketch editor metadata"() {+ given:+ def svg = """<svg xmlns="http://www.w3.org/2000/svg"+ xmlns:sketch="http://www.bohemiancoding.com/sketch/ns"+ xmlns:xlink="http://www.w3.org/1999/xlink">+ <g sketch:type="MSPage">${content}</g>+ </svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains(reason)++ where:+ content | reason+ "<use xlink:href='https://example.invalid/image.svg#shape'/>" | "local fragment starting with '#'"+ "<use xlink:href='images/icon.svg#shape'/>" | "local fragment starting with '#'"+ "<use xlink:href='data:image/svg+xml;base64,PHN2Zy8+'/>" | "local fragment starting with '#'"+ "<use xlink:href='#shape' sketch:onload='alert(1)'/>" | "event handlers are not allowed"+ "<rect sketch:fill='u\\72l(//example.invalid/paint.svg#paint)'/>" | "CSS escapes"+ "<rect style='fill:url(//example.invalid/paint.svg#paint)'/>" | "must reference a local fragment"+ "<script>alert(1)</script>" | "Unsupported SVG element: script"+ "<sketch:metadata><script xmlns='http://www.w3.org/1999/xhtml'>alert(1)</script></sketch:metadata>" | "SVG metadata element <script> uses an unsupported namespace"+ }++ def "rejects unknown namespaces on Sketch-looking SVG attributes"() {+ given:+ def svg = """<svg xmlns="http://www.w3.org/2000/svg" xmlns:sketch="${namespace}">+ <g sketch:type="MSPage"/>+ </svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("attribute 'sketch:type'")+ failure.message.contains("attribute namespace is not supported")++ where:+ namespace << ["http://www.w3.org/1999/xhtml", "https://example.invalid/editor"]+ }++ def "accepts Serif layer names in SVG logos"() {+ given:+ def svg = '''<svg xmlns="http://www.w3.org/2000/svg" xmlns:serif="http://www.serif.com/"+ width="100%" height="100%" viewBox="0 0 20 20" xml:space="preserve"+ style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;">+ <g id="Logo" serif:id="Company logo">+ <rect id="Background" serif:id="Logo background" x="0" y="0" width="20" height="20"+ style="fill:rgb(255,0,0);"/>+ </g>+ </svg>'''++ expect:+ // Affinity exports use serif:id for editor layer names, including names containing spaces.+ ImageUploadValidator.validate("logo.svg", svg.bytes) == null+ }++ def "rejects unsafe SVG content alongside Serif editor attributes"() {+ given:+ def svg = """<svg xmlns="http://www.w3.org/2000/svg" xmlns:serif="http://www.serif.com/">+ <rect serif:id="Logo background" ${attributes}/>${content}+ </svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains(reason)++ where:+ attributes | content | reason+ "onload='alert(1)'" | "" | "event handlers are not allowed"+ "serif:onload='alert(1)'" | "" | "event handlers are not allowed"+ "serif:href='//example.invalid/image.svg#shape'" | "" | "local fragment starting with '#'"+ "fill='u\\72l(//example.invalid/paint.svg#paint)'" | "" | "CSS escapes"+ "serif:fill='u\\72l(//example.invalid/paint.svg#paint)'" | "" | "CSS escapes"+ "" | "<script>alert(1)</script>" | "Unsupported SVG element: script"+ "" | "<serif:metadata><script>alert(1)</script></serif:metadata>" | "SVG metadata element <script> uses an unsupported namespace"+ }++ def "rejects unknown namespaces on Serif-looking SVG attributes"() {+ given:+ def svg = """<svg xmlns="http://www.w3.org/2000/svg" xmlns:serif="${namespace}">+ <rect serif:id="Logo background"/>+ </svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("attribute 'serif:id'")+ failure.message.contains("attribute namespace is not supported")++ where:+ namespace << ["http://www.w3.org/1999/xhtml", "https://example.invalid/editor"]+ }++ def "rejects unknown namespaces on editor-looking SVG attributes"() {+ given:+ def svg = """<svg xmlns="http://www.w3.org/2000/svg"+ xmlns:inkscape="${namespace}" inkscape:version="1.4"/>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("attribute 'inkscape:version'")+ failure.message.contains("attribute namespace is not supported")++ where:+ namespace << ["http://www.w3.org/1999/xhtml", "https://example.invalid/editor"]+ }++ def "accepts SVGs containing Inkscape views, guides, grids, pages and path effects"() {+ given:+ def svg = '''<svg xmlns="http://www.w3.org/2000/svg"+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"+ width="20" height="20" inkscape:version="1.4" sodipodi:docname="logo.svg">+ <sodipodi:namedview id="namedview1" pagecolor="#ffffff" inkscape:zoom="2"+ inkscape:current-layer="layer1">+ <sodipodi:guide position="0,20" orientation="0,1"/>+ <inkscape:grid type="xygrid" spacingx="1" spacingy="1"/>+ <inkscape:page x="0" y="0" width="20" height="20"/>+ </sodipodi:namedview>+ <defs><inkscape:path-effect id="effect1" effect="spiro" is_visible="true"/></defs>+ <g id="layer1" inkscape:groupmode="layer" inkscape:label="Logo">+ <path d="M0 0H20V20H0Z" inkscape:path-effect="#effect1"/>+ </g>+ </svg>'''++ expect:+ // Editor elements used to be rejected even after their attributes were allowed.+ ImageUploadValidator.validate("logo.svg", svg.bytes) == null+ }++ def "accepts editor elements in descriptive SVG metadata with alternate namespace prefixes"() {+ given:+ def svg = '''<svg xmlns="http://www.w3.org/2000/svg"+ xmlns:view="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"+ xmlns:editor="http://www.inkscape.org/namespaces/inkscape">+ <metadata><view:namedview><editor:grid type="xygrid"/></view:namedview></metadata>+ </svg>'''++ expect:+ ImageUploadValidator.validate("logo.svg", svg.bytes) == null+ }++ def "rejects active content and unsupported namespaces inside editor metadata"() {+ given:+ def svg = """<svg xmlns="http://www.w3.org/2000/svg"+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape">+ <sodipodi:namedview ${attributes}>${content}</sodipodi:namedview>+ </svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ // Accepting a metadata container must not skip validation of its attributes or descendants.+ def failure = thrown(IllegalArgumentException)+ failure.message.contains(reason)++ where:+ attributes | content | reason+ "" | "<script>alert(1)</script>" | "SVG metadata element <script> uses an unsupported namespace"+ "" | "<script xmlns='http://www.w3.org/1999/xhtml'>alert(1)</script>" | "SVG metadata element <script> uses an unsupported namespace"+ "" | "<foreignObject/>" | "SVG metadata element <foreignObject> uses an unsupported namespace"+ "" | "<inkscape:grid><script>alert(1)</script></inkscape:grid>" | "SVG metadata element <script> uses an unsupported namespace"+ "" | "<sodipodi:guide xmlns:sodipodi='https://example.invalid/editor'/>" | "SVG metadata element <sodipodi:guide> uses an unsupported namespace"+ "" | "<?xml-stylesheet type='text/css' href='https://example.invalid/style.css'?>" | "SVG metadata contains unsupported processing instruction"+ "onload='alert(1)'" | "" | "event handlers are not allowed"+ "" | "<inkscape:grid onload='alert(1)'/>" | "event handlers are not allowed"+ "xml:base='https://example.invalid/'" | "" | "base URIs are not allowed"+ "style='fill:url(//example.invalid/paint.svg#paint)'" | "" | "must reference a local fragment"+ "" | "<inkscape:grid style='fill:u\\72l(//example.invalid/paint.svg#paint)'/>" | "CSS escapes"+ }++ def "editor metadata obeys SVG nesting and element count limits"() {+ given:+ def contents = nested+ ? "<inkscape:page>".repeat(65) + "</inkscape:page>".repeat(65)+ : "<inkscape:page/>".repeat(10_000)+ def svg = """<svg xmlns="http://www.w3.org/2000/svg"+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape">+ <sodipodi:namedview>${contents}</sodipodi:namedview>+ </svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains(reason)++ where:+ nested | reason+ true | "SVG metadata nesting exceeds 64 levels"+ false | "SVG contains more than 10000 elements"+ }++ def "editor metadata does not bypass SVG content restrictions"() {+ given:+ def svg = """<svg xmlns="http://www.w3.org/2000/svg"+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"+ inkscape:version="1.4" ${attributes}>${content}</svg>"""++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains(reason)++ where:+ attributes | content | reason+ "onload='alert(1)'" | "" | "event handlers are not allowed"+ "inkscape:onload='alert(1)'" | "" | "event handlers are not allowed"+ "" | "<script>alert(1)</script>" | "Unsupported SVG element: script"+ "" | "<use href='//example.invalid/image.svg#shape'/>" | "local fragment starting with '#'"+ "inkscape:href='//example.invalid/image.svg#shape'" | "" | "local fragment starting with '#'"+ "inkscape:fill='u\\72l(//example.invalid/image.svg#paint)'" | "" | "CSS escapes"+ "" | "<rect fill='u\\72l(//example.invalid/image.svg#paint)'/>" | "CSS escapes"+ }++ def "rejects active SVG elements and event handlers"() {+ when:+ ImageUploadValidator.validate("logo.svg", svg.getBytes(StandardCharsets.UTF_8))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains(reason)++ where:+ svg | reason+ "<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>" | "Unsupported SVG element: script"+ "<svg xmlns='http://www.w3.org/2000/svg'><foreignObject><div/></foreignObject></svg>" | "Unsupported SVG element: foreignObject"+ "<svg xmlns='http://www.w3.org/2000/svg' onload='alert(1)'/>" | "event handlers are not allowed"+ "<svg xmlns='http://www.w3.org/2000/svg'><style>@import 'https://example.com/style.css';</style></svg>" | "CSS construct '@import' is not allowed"+ }++ def "rejects external XML entities in SVG uploads"() {+ given:+ def svg = "<!DOCTYPE svg [<!ENTITY external SYSTEM 'https://example.invalid/entity'>]><svg xmlns='http://www.w3.org/2000/svg'>&external;</svg>"++ when:+ ImageUploadValidator.validate("logo.svg", svg.getBytes(StandardCharsets.UTF_8))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("DOCTYPE")+ }++ def "rejects truncated raster data"() {+ given:+ byte[] pngSignature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] as byte[]++ when:+ ImageUploadValidator.validate("logo.png", pngSignature)++ then:+ thrown(IllegalArgumentException)+ }++ def "accepts ICO frames containing PNG and DIB data"() {+ given:+ def output = new ByteArrayOutputStream()+ ImageIO.write(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB), "png", output)++ expect:+ ImageUploadValidator.validate("logo.ico", ico(output.toByteArray(), 1, 1)) == null+ ImageUploadValidator.validate("logo.ico", ico(dib(1, 2), 1, 1)) == null+ ImageUploadValidator.validate("logo.ico", ico([output.toByteArray(), dib(1, 2), output.toByteArray()], 1, 1)) == null+ }++ def "rejects oversized embedded ICO images before decoding"() {+ given:+ // No pixel data is needed: the payload header must be checked before invoking a decoder.+ def png = ByteBuffer.allocate(33).order(ByteOrder.BIG_ENDIAN)+ .putLong(0x89504e470d0a1a0aL).putInt(13).putInt(0x49484452)+ .putInt(width).putInt(height).put((byte) 8).put((byte) 6).array()++ when:+ ImageUploadValidator.validate("logo.ico", ico(usePng ? png : dib(width, height * 2), 1, 1))++ then:+ // The ICO directory used to hide the embedded PNG dimensions from the limits.+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("ICO frame 1 embedded image is ${width}x${height} pixels")+ failure.message.contains(limit)++ where:+ usePng | width | height | limit+ true | 4100 | 4100 | "dimensions must be between 1x1 and 4096x4096"+ true | 4096 | 4096 | "contains 16777216 pixels; maximum is 16000000 pixels"+ true | Integer.MAX_VALUE | Integer.MAX_VALUE | "dimensions must be between 1x1 and 4096x4096"+ false | 4100 | 4100 | "dimensions must be between 1x1 and 4096x4096"+ false | 4096 | 4096 | "contains 16777216 pixels; maximum is 16000000 pixels"+ }++ def "rejects inconsistent ICO directory and embedded dimensions"() {+ given:+ def output = new ByteArrayOutputStream()+ ImageIO.write(new BufferedImage(2, 2, BufferedImage.TYPE_INT_ARGB), "png", output)+ def payload = png ? output.toByteArray() : dib(2, 4)++ when:+ ImageUploadValidator.validate("logo.ico", ico(payload, 1, 1))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("ICO frame 1 directory reports 1x1 pixels")+ failure.message.contains("embedded image is 2x2 pixels; dimensions must match")++ where:+ png << [true, false]+ }++ def "rejects invalid ICO payload offsets"() {+ given:+ byte[] data = ico(dib(1, 2), 1, 1)+ ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).putInt(18, offset)++ when:+ ImageUploadValidator.validate("logo.ico", data)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("invalid payload range")+ failure.message.contains("offset ${Integer.toUnsignedLong(offset)}, size 48 bytes")+ failure.message.contains("start at or after byte 22")+ failure.message.contains("fit within the 70-byte image")++ where:+ offset << [0, -1, Integer.MAX_VALUE]+ }++ def "rejects ICO directory bit depths that disagree with DIB payloads"() {+ given:+ byte[] data = ico(dib(1, 2), 1, 1)+ ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).putShort(12, (short) 30)++ when:+ ImageUploadValidator.validate("logo.ico", data)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("directory bit depth is 30, but the DIB bit depth is 32")+ failure.message.contains("must be 0 or match the DIB header")+ }++ def "reports the invalid DIB header value and requirement for ICO uploads"() {+ given:+ byte[] payload = dib(1, 2)+ def header = ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN)+ if (offset == 12 || offset == 14) {+ header.putShort(offset, (short) value)+ } else {+ header.putInt(offset, value)+ }++ when:+ ImageUploadValidator.validate("logo.ico", ico(payload, 1, 1))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.startsWith("ICO frame 1 DIB")+ failure.message.contains(reason)+ failure.message.contains(requirement)++ where:+ offset | value | reason | requirement+ 0 | 13 | "header size is 13 bytes" | "supported sizes are 12, 16, 40, 52, 56, 64, 108, and 124 bytes"+ 0 | 108 | "header declares 108 bytes" | "payload contains only 48 bytes"+ 12 | 2 | "declares 2 color planes" | "exactly 1 is required"+ 14 | 3 | "bit depth is 3 bits per pixel" | "supported depths are 1, 4, 8, 16, 24, and 32"+ 8 | 3 | "height is 3 pixels" | "must be positive and even"+ 8 | 0 | "height is 0 pixels" | "must be positive and even"+ 8 | -2 | "height is -2 pixels" | "must be positive and even"+ }++ def "reports malformed embedded PNG headers in ICO uploads"() {+ given:+ def payload = ByteBuffer.allocate(size).order(ByteOrder.BIG_ENDIAN)+ .putLong(0x89504e470d0a1a0aL).putInt(length)+ if (size >= 16) {+ payload.putInt(type)+ }++ when:+ ImageUploadValidator.validate("logo.ico", ico(payload.array(), 1, 1))++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.startsWith("ICO frame 1 embedded PNG")+ failure.message.contains(reason)+ failure.message.contains(requirement)++ where:+ size | length | type | reason | requirement+ 12 | 13 | 0x49484452 | "payload contains 12 bytes" | "at least 33 are required"+ 33 | 12 | 0x49484452 | "chunk length 12 bytes" | "expected an IHDR chunk with 13 bytes"+ 33 | 13 | 0x49444154 | "chunk type 0x49444154" | "expected an IHDR chunk with 13 bytes"+ }++ @Timeout(5)+ def "rejects deeply nested SVG elements before collecting style text"() {+ given:+ def nestedElements = "<g>".repeat(150_000) + "</g>".repeat(150_000)+ def content = withStyle ? "<style>${nestedElements}</style>" : nestedElements+ def data = "<svg xmlns='http://www.w3.org/2000/svg'>${content}</svg>".getBytes(StandardCharsets.UTF_8)+ assert data.length <ImageUploadValidator.MAX_FILE_SIZE++ when:+ ImageUploadValidator.validate("logo.svg", data)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message == "SVG nesting exceeds 64 levels"++ where:+ withStyle << [false, true]+ }++ @Timeout(5)+ def "rejects repeated unterminated CSS URLs within bounded time"() {+ given:+ def svg = "<svg xmlns='http://www.w3.org/2000/svg'><style>" + prefix.repeat(131_072) + "</style></svg>"++ when:+ ImageUploadValidator.validate("logo.svg", svg.getBytes(StandardCharsets.UTF_8))++ then:+ // Regex matching used to rescan the remaining input for every unterminated url(.+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("url()")++ where:+ prefix << ["url(", "url(#"]+ }++ def "reports the CSS context, position and reason for rejected URLs"() {+ when:+ ImageUploadValidator.validate("logo.svg", "<svg xmlns='http://www.w3.org/2000/svg'><style>rect{fill:${css}}</style></svg>".bytes)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message.startsWith("SVG <style>:")+ failure.message.contains("at character 11")+ failure.message.contains(reason)+ failure.message.contains("url(#paint)") || failure.message.contains("url('#paint')")++ where:+ css | reason+ "url(#paint" | "expected ')'"+ "url('#paint)" | "missing closing single quote"+ 'url("#paint)' | "missing closing double quote"+ "url(#)" | "empty fragment identifier"+ "url(#paint extra)" | "expected ')'"+ "url(#paint(url(#other))" | "nested opening parenthesis '('"+ "url(#paint'other)" | "quote inside an unquoted reference"+ "url()" | "external and empty references are not allowed"+ "url(https://example.invalid/paint.svg#paint)" | "must reference a local fragment starting with '#'"+ }++ def "rejects escaped URLs in SVG presentation attributes"() {+ given:+ def svg = "<svg xmlns='http://www.w3.org/2000/svg'><rect ${attribute}='u\\72l(//example.invalid/paint.svg#paint)'/></svg>"++ when:+ ImageUploadValidator.validate("logo.svg", svg.bytes)++ then:+ // Presentation attributes use CSS parsing and used to bypass the style-only escape check.+ def failure = thrown(IllegalArgumentException)+ failure.message.contains("attribute '${attribute}'")+ failure.message.contains("CSS escapes")++ where:+ attribute << ["fill", "stroke", "filter", "clip-path", "mask", "marker-start", "cursor"]+ }++ def "accepts quoted local URLs in SVG presentation attributes"() {+ expect:+ ImageUploadValidator.validate("logo.svg", '''<svg xmlns="http://www.w3.org/2000/svg">+ <rect fill="url( '#paint' )" stroke="URL(#paint)"/></svg>'''.bytes) == null+ }++ private static byte[] ico(byte[] payload, int width, int height) {+ ico([payload], width, height)+ }++ private static byte[] ico(List<byte[]> payloads, int width, int height) {+ int offset = 6 + payloads.size() * 16+ def buffer = ByteBuffer.allocate(offset + (int) payloads.sum {+ it.length+ }).order(ByteOrder.LITTLE_ENDIAN)+ .putShort((short) 0).putShort((short) 1).putShort((short) payloads.size())+ payloads.each { payload ->+ buffer.put((byte) width).put((byte) height).put((byte) 0).put((byte) 0)+ .putShort((short) 1).putShort((short) 32).putInt(payload.length).putInt(offset)+ offset += payload.length+ }+ payloads.each { buffer.put(it) }+ buffer.array()+ }++ private static byte[] raster(String format, int width = 1, int height = 1) {+ def output = new ByteArrayOutputStream()+ ImageIO.write(new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB), format, output)+ output.toByteArray()+ }++ private static byte[] dib(int width, int height) {+ ByteBuffer.allocate(48).order(ByteOrder.LITTLE_ENDIAN)+ .putInt(40).putInt(width).putInt(height).putShort((short) 1).putShort((short) 32).array()+ }+}diff --git a/manager/test/src/groovy/org/openremote/manager/app/RasterImageValidatorTest.groovy b/manager/test/src/groovy/org/openremote/manager/app/RasterImageValidatorTest.groovynew file mode 100644index 000000000..06ddf478e--- /dev/null+++ b/manager/test/src/groovy/org/openremote/manager/app/RasterImageValidatorTest.groovy@@ -0,0 +1,135 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * SPDX-License-Identifier: AGPL-3.0-or-later+ */+package org.openremote.manager.app++import spock.lang.Specification++import java.awt.image.BufferedImage+import javax.imageio.ImageIO+import javax.imageio.ImageReader+import javax.imageio.spi.IIORegistry+import javax.imageio.spi.ImageReaderSpi+import javax.imageio.stream.ImageInputStream++class RasterImageValidatorTest extends Specification {++ private static final byte[] TEST_IMAGE = [0x52, 0x41, 0x53, 0x54] as byte[]++ ImageReader reader = Mock()+ ImageReaderSpi provider+ IIORegistry registry = IIORegistry.getDefaultInstance()++ def setup() {+ reader.getFormatName() >> "png"+ reader.getHeight(0) >> 1+ provider = Stub(ImageReaderSpi) {+ canDecodeInput(_ as ImageInputStream) >> { ImageInputStream input ->+ input.mark()+ try {+ byte[] signature = new byte[TEST_IMAGE.length]+ input.readFully(signature)+ return Arrays.equals(signature, TEST_IMAGE)+ } finally {+ input.reset()+ }+ }+ createReaderInstance() >> reader+ }+ registry.registerServiceProvider(provider, ImageReaderSpi.class)+ }++ def cleanup() {+ registry.deregisterServiceProvider(provider, ImageReaderSpi.class)+ }++ def "uses a memory cache without changing the shared ImageIO cache preference"() {+ given:+ def useCache = ImageIO.getUseCache()+ reader.getWidth(0) >> 1+ reader.read(0) >> new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB)++ when:+ ImageUploadValidator.validate("logo.png", TEST_IMAGE)++ then:+ 1 * reader.setInput({ ImageInputStream input ->+ input.isCachedMemory() && !input.isCachedFile()+ }, false, true)+ 1 * reader.dispose()+ ImageIO.getUseCache() == useCache+ }++ def "reports #decoderFailure.class.simpleName during #phase as a validation failure"() {+ given:+ reader.getWidth(0) >> {+ if (phase == "header parsing") {+ throw decoderFailure+ }+ return 1+ }+ reader.read(0) >> { throw decoderFailure }++ when:+ ImageUploadValidator.validate("logo.png", TEST_IMAGE)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message == "Could not decode PNG image data: ${decoderFailure.message}"+ failure.cause.is(decoderFailure)+ 1 * reader.dispose()++ where:+ phase | decoderFailure+ "header parsing" | new IllegalStateException("invalid header state")+ "pixel decoding" | new ArrayIndexOutOfBoundsException("invalid sample index")+ "pixel decoding" | new NegativeArraySizeException("negative palette size")+ "pixel decoding" | new IllegalStateException("invalid decoder state")+ "pixel decoding" | new IOException("truncated pixel data")+ }++ def "preserves an IllegalArgumentException reported by the decoder"() {+ given:+ def decoderFailure = new IllegalArgumentException("invalid color model")+ reader.getWidth(0) >> 1+ reader.read(0) >> { throw decoderFailure }++ when:+ ImageUploadValidator.validate("logo.png", TEST_IMAGE)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.is(decoderFailure)+ 1 * reader.dispose()+ }++ def "preserves the detailed dimensions validation message"() {+ given:+ reader.getWidth(0) >> 4097++ when:+ ImageUploadValidator.validate("logo.png", TEST_IMAGE)++ then:+ def failure = thrown(IllegalArgumentException)+ failure.message == "Image frame 1 is 4097x1 pixels; dimensions must be between 1x1 and 4096x4096"+ failure.cause == null+ 0 * reader.read(_)+ 1 * reader.dispose()+ }+}diff --git a/model/src/main/java/org/openremote/model/manager/ConfigurationResource.java b/model/src/main/java/org/openremote/model/manager/ConfigurationResource.javaindex bd764f678..a7837e8d9 100644--- a/model/src/main/java/org/openremote/model/manager/ConfigurationResource.java+++ b/model/src/main/java/org/openremote/model/manager/ConfigurationResource.java@@ -50,7 +50,7 @@ public interface ConfigurationResource {operationId = "updateConfiguration",summary = "Update manager configuration",description =- "Replaces manager_config.json and returns the stored configuration. This administrative change affects Manager UI branding and behavior.")+ "Replaces manager_config.json and returns the stored configuration. This administrative change affects Manager UI branding and behavior. This operation is restricted to a super administrator.")@OpenApiResponses.Ok@OpenApiResponses.Authenticated@OpenApiResponses.BadRequest@@ -66,18 +66,20 @@ public interface ConfigurationResource {@POST@Consumes(APPLICATION_JSON)@Produces(APPLICATION_JSON)- @Path("manager/file")+ @Path("manager/image")@RolesAllowed({Constants.WRITE_ADMIN_ROLE})@Operation(- operationId = "fileUpload",+ operationId = "imageUpload",summary = "Upload a Manager configuration image",description =- "Decodes and stores the supplied FileInfo under the requested relative path, then returns its Manager API path.")+ "Validates and stores the supplied image FileInfo at the requested relative path,"+ + " replacing an existing image, then returns its Manager API path. This operation"+ + " is restricted to a super administrator.")@OpenApiResponses.Ok@OpenApiResponses.Authenticated@OpenApiResponses.BadRequest@OpenApiResponses.ServerError- String fileUpload(+ String imageUpload(@BeanParam RequestParams requestParams,@Parameter(description = "Relative storage path and filename for the image.",@@ -107,14 +109,20 @@ public interface ConfigurationResource {operationId = "getManagerConfigImage",summary = "Retrieve a Manager configuration image",description =- "Streams a previously uploaded configuration image using its detected media type.")+ "Streams a configuration image using a fixed media type determined by its filename"+ + " extension. Only png, jpg, jpeg, ico, and svg extensions are served, ignoring case;"+ + " unsupported extensions return 404.")@ApiResponse(responseCode = "200",description = "The image file",- content =- @Content(- mediaType = "application/octet-stream",- schema = @Schema(type = "string", format = "binary")))+ content = {+ @Content(mediaType = "image/png", schema = @Schema(type = "string", format = "binary")),+ @Content(mediaType = "image/jpeg", schema = @Schema(type = "string", format = "binary")),+ @Content(+ mediaType = "image/vnd.microsoft.icon",+ schema = @Schema(type = "string", format = "binary")),+ @Content(mediaType = "image/svg+xml", schema = @Schema(type = "string", format = "binary"))+ })@OpenApiResponses.NotFound@OpenApiResponses.ServerErrorObject getManagerConfigImage(diff --git a/model/src/main/java/org/openremote/model/map/MapResource.java b/model/src/main/java/org/openremote/model/map/MapResource.javaindex 759784fd6..7f3c414bb 100644--- a/model/src/main/java/org/openremote/model/map/MapResource.java+++ b/model/src/main/java/org/openremote/model/map/MapResource.java@@ -52,7 +52,7 @@ public interface MapResource {operationId = "saveSettings",summary = "Update map settings",description =- "Stores the map configuration and returns the resulting public MapLibre settings.")+ "Stores the map configuration and returns the resulting public MapLibre settings. This operation is restricted to a super administrator.")@OpenApiResponses.Ok@OpenApiResponses.Authenticated@OpenApiResponses.BadRequest@@ -121,7 +121,7 @@ public interface MapResource {operationId = "uploadMap",summary = "Upload a custom MBTiles map",description =- "Stores the raw request body as the realm's custom MBTiles database and returns the resulting public map settings.")+ "Stores the raw request body as the realm's custom MBTiles database and returns the resulting public map settings. This operation is restricted to a super administrator.")@OpenApiResponses.Ok@OpenApiResponses.Authenticated@OpenApiResponses.BadRequest@@ -167,7 +167,7 @@ public interface MapResource {operationId = "deleteMap",summary = "Remove the custom MBTiles map",description =- "Deletes the installed custom MBTiles database and returns the fallback public map settings.")+ "Deletes the installed custom MBTiles database and returns the fallback public map settings. This operation is restricted to a super administrator.")@OpenApiResponses.Ok@OpenApiResponses.Authenticated@OpenApiResponses.BadRequestdiff --git a/model/src/main/java/org/openremote/model/syslog/SyslogResource.java b/model/src/main/java/org/openremote/model/syslog/SyslogResource.javaindex 5150df816..03417fb8b 100644--- a/model/src/main/java/org/openremote/model/syslog/SyslogResource.java+++ b/model/src/main/java/org/openremote/model/syslog/SyslogResource.java@@ -112,7 +112,8 @@ public interface SyslogResource {@Operation(operationId = "clearEvents",summary = "Clear stored syslog events",- description = "Permanently removes all events from the configured syslog storage.")+ description =+ "Permanently removes all events from the configured syslog storage. This operation is restricted to a super administrator.")@OpenApiResponses.NoContentvoid clearEvents(@BeanParam RequestParams requestParams);@@ -124,7 +125,8 @@ public interface SyslogResource {@Operation(operationId = "getConfig",summary = "Retrieve the syslog configuration",- description = "Returns the current log-storage and retention configuration.")+ description =+ "Returns the current log-storage and retention configuration. This operation is restricted to a super administrator.")@OpenApiResponses.OkSyslogConfig getConfig(@BeanParam RequestParams requestParams);@@ -135,7 +137,8 @@ public interface SyslogResource {@Operation(operationId = "updateConfig",summary = "Update the syslog configuration",- description = "Validates and applies log-storage and retention settings.")+ description =+ "Validates and applies log-storage and retention settings. This operation is restricted to a super administrator.")@OpenApiResponses.NoContent@OpenApiResponses.BadRequestvoid updateConfig(diff --git a/test/src/test/groovy/org/openremote/test/app/ConfigurationResourceTest.groovy b/test/src/test/groovy/org/openremote/test/app/ConfigurationResourceTest.groovynew file mode 100644index 000000000..3567ed4f9--- /dev/null+++ b/test/src/test/groovy/org/openremote/test/app/ConfigurationResourceTest.groovy@@ -0,0 +1,425 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * SPDX-License-Identifier: AGPL-3.0-or-later+ */+package org.openremote.test.app++import jakarta.ws.rs.BadRequestException+import jakarta.ws.rs.ForbiddenException+import jakarta.ws.rs.NotFoundException+import jakarta.ws.rs.core.Response+import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget+import org.openremote.container.persistence.PersistenceService+import org.openremote.manager.security.ManagerIdentityService+import org.openremote.manager.setup.SetupService+import org.openremote.model.file.FileInfo+import org.openremote.model.manager.ConfigurationResource+import org.openremote.model.manager.ManagerAppConfig+import org.openremote.model.security.ClientRole+import org.openremote.model.util.ValueUtil+import org.openremote.setup.integration.KeycloakTestSetup+import org.openremote.test.ManagerContainerTrait+import spock.lang.Shared+import spock.lang.Specification++import javax.imageio.ImageIO+import java.awt.image.BufferedImage+import java.net.http.HttpClient+import java.net.http.HttpRequest+import java.net.http.HttpResponse+import java.nio.charset.StandardCharsets+import java.nio.file.Files+import java.time.Duration++import static org.openremote.manager.app.ConfigurationService.MANAGER_CONFIG_IMAGE_URL_PREFIX+import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD+import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT+import static org.openremote.model.Constants.*+import static org.openremote.model.util.MapAccess.getString++class ConfigurationResourceTest extends Specification implements ManagerContainerTrait {++ private static final String IMAGE_CONTENT_SECURITY_POLICY =+ "sandbox; default-src 'none'; img-src data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"++ @Shared+ ConfigurationResource adminResource++ @Shared+ ConfigurationResource publicResource++ @Shared+ ConfigurationResource nonSuperuserResource++ @Shared+ ResteasyWebTarget publicTarget++ @Shared+ String nonSuperuserId++ @Shared+ String adminToken++ @Shared+ HttpClient rawHttpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build()++ def setupSpec() {+ given: "the server container is started"+ def container = startContainer(defaultConfig(), defaultServices())+ def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)++ and: "a superuser and an admin-role user without the superuser realm role are authenticated"+ adminToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID,+ MASTER_REALM_ADMIN_USER,+ getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT))+ def username = "configuration-admin-without-superuser"+ def user = keycloakTestSetup.createUser(MASTER_REALM, username, username,+ "Configuration", "Admin", "${username}@openremote.local", true,+ [ClientRole.READ_ADMIN, ClientRole.WRITE_ADMIN] as ClientRole[])+ nonSuperuserId = user.id+ def nonSuperuserToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID,+ username, username)++ and: "the configuration resource proxies are configured"+ adminResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, adminToken)+ .proxy(ConfigurationResource.class)+ publicTarget = getClientApiTarget(serverUri(serverPort), MASTER_REALM)+ publicResource = publicTarget.proxy(ConfigurationResource.class)+ nonSuperuserResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM,+ nonSuperuserToken).proxy(ConfigurationResource.class)+ }++ def cleanupSpec() {+ rawHttpClient.close()+ if (nonSuperuserId != null) {+ container.getService(ManagerIdentityService.class).getIdentityProvider()+ .deleteUser(MASTER_REALM, nonSuperuserId)+ }+ }++ def "Public clients can read the Manager configuration"() {+ when:+ def config = publicResource.getManagerConfig()++ then:+ config != null+ config.realms.containsKey("default")+ }++ def "Superuser can update and read the Manager configuration"() {+ given:+ def original = adminResource.getManagerConfig()+ def updated = ValueUtil.JSON.readValue(ValueUtil.asJSON(original).orElseThrow(),+ ManagerAppConfig.class)+ updated.loadLocales = !original.loadLocales++ when:+ def saved = adminResource.update(null, updated)++ then:+ saved.loadLocales == updated.loadLocales+ publicResource.getManagerConfig().loadLocales == updated.loadLocales++ cleanup:+ if (original != null) {+ adminResource.update(null, original)+ }+ }++ def "Superuser can upload an image and public clients can retrieve it"() {+ given:+ def image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB)+ def output = new ByteArrayOutputStream()+ ImageIO.write(image, "png", output)+ def png = output.toByteArray()+ def filename = "configuration-resource-test-${UUID.randomUUID()}.png"+ def storedFile = container.getService(PersistenceService.class)+ .resolvePath("manager/images/${filename}")+ def fileInfo = new FileInfo(filename, Base64.encoder.encodeToString(png), true)++ when:+ def path = adminResource.imageUpload(null, filename, fileInfo)+ def response = publicTarget.path("configuration/manager/image/${filename}").request().get()++ then:+ path == MANAGER_CONFIG_IMAGE_URL_PREFIX + filename+ response.withCloseable { r ->+ assert r.status == Response.Status.OK.statusCode+ assert r.mediaType.toString() == "image/png"+ assert r.getHeaderString("X-Content-Type-Options") == "nosniff"+ assert r.getHeaderString("Content-Security-Policy") == IMAGE_CONTENT_SECURITY_POLICY+ assert r.readEntity(byte[].class) == png+ return true+ }++ cleanup:+ Files.deleteIfExists(storedFile)+ }++ def "Superuser can replace a branding image while preserving its configuration reference"() {+ given:+ def original = adminResource.getManagerConfig()+ def updated = ValueUtil.JSON.readValue(ValueUtil.asJSON(original).orElseThrow(), ManagerAppConfig.class)+ def output = new ByteArrayOutputStream()+ ImageIO.write(new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB), "png", output)+ def filename = "default/configuration-branding-${UUID.randomUUID()}.png"+ def storedFile = container.getService(PersistenceService.class).resolvePath("manager/images/${filename}")+ def file = new FileInfo("logo.png", Base64.encoder.encodeToString(output.toByteArray()), true)+ def replacementImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB)+ replacementImage.setRGB(0, 0, 0xff0000)+ def replacementOutput = new ByteArrayOutputStream()+ ImageIO.write(replacementImage, "png", replacementOutput)+ def replacement = replacementOutput.toByteArray()++ when:+ def path = adminResource.imageUpload(null, filename, file)+ updated.realms.default.logo = path+ adminResource.update(null, updated)+ def replacementPath = adminResource.imageUpload(null, filename,+ new FileInfo("logo.png", Base64.encoder.encodeToString(replacement), true))++ then:+ replacementPath == path+ publicResource.getManagerConfig().realms.default.logo == path+ publicTarget.path(path.replace("/api/master/", "")).request().get().withCloseable { response ->+ assert response.status == Response.Status.OK.statusCode+ assert response.getHeaderString("Content-Security-Policy") == IMAGE_CONTENT_SECURITY_POLICY+ assert response.readEntity(byte[].class) == replacement+ return true+ }++ cleanup:+ adminResource.update(null, original)+ Files.deleteIfExists(storedFile)+ }++ def "Public clients retrieve legacy images with fixed image types and browser content restrictions"() {+ given:+ def storedFile = container.getService(PersistenceService.class).resolvePath("manager/images/legacy-${filename}")+ Files.createDirectories(storedFile.parent)+ Files.write(storedFile, contents.bytes)++ expect:+ // Legacy content is streamed under the type for its allowed image extension.+ publicTarget.path("configuration/manager/image/legacy-${filename}").request().get().withCloseable { response ->+ assert response.status == Response.Status.OK.statusCode+ assert response.mediaType.toString() == mediaType+ assert response.getHeaderString("X-Content-Type-Options") == "nosniff"+ assert response.getHeaderString("Content-Security-Policy") == IMAGE_CONTENT_SECURITY_POLICY+ assert response.readEntity(byte[].class) == contents.bytes+ return true+ }++ cleanup:+ Files.deleteIfExists(storedFile)++ where:+ filename | contents | mediaType+ "logo.svg" | "<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>" | "image/svg+xml"+ "logo.SvG" | "<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>" | "image/svg+xml"+ "logo.png" | "<html/>" | "image/png"+ "logo.PNG" | "<html/>" | "image/png"+ "logo.jpg" | "legacy JPEG" | "image/jpeg"+ "logo.jpeg" | "legacy JPEG" | "image/jpeg"+ "logo.JpEg" | "legacy JPEG" | "image/jpeg"+ "logo.ico" | "legacy ICO" | "image/vnd.microsoft.icon"+ "logo.ICO" | "legacy ICO" | "image/vnd.microsoft.icon"+ }++ def "Public clients cannot retrieve legacy files with unsupported image extensions"() {+ given:+ def storedFile = container.getService(PersistenceService.class).resolvePath("manager/images/legacy-${filename}")+ Files.createDirectories(storedFile.parent)+ Files.write(storedFile, "<html><a href='https://example.invalid/'>Continue</a></html>".bytes)++ expect:+ publicTarget.path("configuration/manager/image/legacy-${filename}").request().get().withCloseable { response ->+ assert response.status == Response.Status.NOT_FOUND.statusCode+ return true+ }++ cleanup:+ Files.deleteIfExists(storedFile)++ where:+ filename << ["page.html", "page.HTML", "payload.js", "logo.svg.html", "logo", "logo."]+ }++ def "Encoded unsafe image paths are rejected over HTTP without changing stored files"() {+ given:+ def images = container.getService(PersistenceService.class).resolvePath("manager/images").toAbsolutePath().normalize()+ Files.createDirectories(images)+ def filename = "configuration-path-${UUID.randomUUID()}.png"+ def stored = images.resolve(filename)+ def outside = images.parent.resolve(filename)+ def original = png(0)+ def privateContents = "Private file ${filename}".bytes+ Files.write(stored, original)+ Files.write(outside, privateContents)+ def encodedPath = switch (vector) {+ case "lowercase traversal" -> "%2e%2e%2f${filename}"+ case "uppercase traversal" -> "%2E%2E%2F${filename}"+ case "encoded dots" -> "%2e%2e/${filename}"+ case "absolute path" -> URLEncoder.encode(outside.toString(), StandardCharsets.UTF_8).replace("%2F", "%2f")+ default -> "${filename}%00ignored.png"+ }+ def path = method == "GET" ? "image/${encodedPath}": "image?path=${encodedPath}"+ def upload = new FileInfo(filename, Base64.encoder.encodeToString(png(0xff0000)), true)++ when:+ def response = rawImageRequest(method, path, upload)++ then:+ response.statusCode() in (method == "GET" ? [400, 404] : [400])+ Files.readAllBytes(outside) == privateContents+ Files.readAllBytes(stored) == original+ Files.list(images).withCloseable { files ->+ files.filter { it.fileName.toString().contains(filename) }.count()+ } == 1++ cleanup:+ Files.deleteIfExists(stored)+ Files.deleteIfExists(outside)++ where:+ method << ["GET", "POST"]+ combined:+ vector << ["lowercase traversal", "uppercase traversal", "encoded dots", "absolute path", "NUL"]+ }++ def "Nested image paths support literal and encoded separators over HTTP"() {+ given:+ def folder = "configuration-encoded-${UUID.randomUUID()}"+ def path = "${folder}${separator}logo.png"+ def stored = container.getService(PersistenceService.class).resolvePath("manager/images/${folder}/logo.png")+ def contents = png(0xff0000)+ def upload = new FileInfo("logo.png", Base64.encoder.encodeToString(contents), true)++ when:+ def uploaded = rawImageRequest("POST", "image?path=${path}", upload)++ then:+ uploaded.statusCode() == 200+ new String(uploaded.body(), StandardCharsets.UTF_8) == MANAGER_CONFIG_IMAGE_URL_PREFIX + "${folder}/logo.png"+ Files.readAllBytes(stored) == contents++ when:+ def downloaded = rawImageRequest("GET", "image/${path}")++ then:+ downloaded.statusCode() == 200+ downloaded.body() == contents++ cleanup:+ Files.deleteIfExists(stored)+ Files.deleteIfExists(stored.parent)++ where:+ separator << ["/", "%2f", "%2F"]+ }++ def "The removed manager file endpoint returns not found"() {+ given:+ def filename = "configuration-old-endpoint-${UUID.randomUUID()}.png"+ def stored = container.getService(PersistenceService.class).resolvePath("manager/images/${filename}")+ def upload = new FileInfo(filename, Base64.encoder.encodeToString(png(0)), true)++ when:+ def response = rawImageRequest(method, "file?path=${filename}", upload)++ then:+ response.statusCode() == 404+ !Files.exists(stored)++ cleanup:+ Files.deleteIfExists(stored)++ where:+ method << ["GET", "POST"]+ }++ def "Missing Manager configuration images return not found"() {+ when:+ publicResource.getManagerConfigImage("missing-${UUID.randomUUID()}.png")++ then:+ thrown(NotFoundException)+ }++ def "Superuser cannot upload a file with an unsupported image extension"() {+ when:+ adminResource.imageUpload(null, "page.html",+ new FileInfo("page.html", Base64.encoder.encodeToString("<html/>".bytes), true))++ then:+ def failure = thrown(BadRequestException)+ failure.response.readEntity(String.class).contains("Unsupported image extension")+ }++ def "Image upload errors return the detailed validation reason to the client"() {+ given:+ def svg = "<svg xmlns='http://www.w3.org/2000/svg'><style>rect{fill:url(#paint}</style></svg>"++ when:+ adminResource.imageUpload(null, "logo.svg",+ new FileInfo("logo.svg", Base64.encoder.encodeToString(svg.bytes), true))++ then:+ def failure = thrown(BadRequestException)+ def reason = failure.response.readEntity(String.class)+ reason.contains("SVG <style>:")+ reason.contains("at character 11")+ reason.contains("expected ')'")+ reason.contains("use url(#paint) or url('#paint')")+ }++ def "Admin client roles alone cannot change global Manager configuration or images"() {+ when: "the user updates the Manager configuration"+ nonSuperuserResource.update(null, new ManagerAppConfig())++ then:+ thrown(ForbiddenException)++ when: "the user uploads an image"+ nonSuperuserResource.imageUpload(null, "logo.png", new FileInfo("logo.png", "", false))++ then:+ thrown(ForbiddenException)+ }++ // Construct the URI directly so encoded attack paths reach the server without double encoding.+ private HttpResponse<byte[]> rawImageRequest(String method, String path, FileInfo upload = null) {+ def request = HttpRequest.newBuilder(URI.create("${publicTarget.uri}/configuration/manager/${path}"))+ .timeout(Duration.ofSeconds(10))+ if (method == "POST") {+ request.header("Authorization", "Bearer ${adminToken}")+ .header("Content-Type", "application/json")+ .POST(HttpRequest.BodyPublishers.ofString(ValueUtil.asJSON(upload).orElseThrow()))+ } else {+ request.GET()+ }+ return rawHttpClient.send(request.build(), HttpResponse.BodyHandlers.ofByteArray())+ }++ private static byte[] png(int color) {+ def image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB)+ image.setRGB(0, 0, color)+ def output = new ByteArrayOutputStream()+ ImageIO.write(image, "png", output)+ return output.toByteArray()+ }+}diff --git a/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy b/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovyindex 681f3c7be..022586083 100644--- a/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy+++ b/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy@@ -20,13 +20,19 @@ package org.openremote.test.mapimport com.fasterxml.jackson.databind.node.ObjectNodeimport groovy.json.JsonSlurper+import jakarta.ws.rs.ForbiddenExceptionimport jakarta.ws.rs.client.Entityimport jakarta.ws.rs.core.MediaType+import jakarta.ws.rs.core.Responseimport org.jboss.resteasy.client.jaxrs.ResteasyWebTargetimport org.openremote.manager.map.MapService+import org.openremote.manager.security.ManagerIdentityService+import org.openremote.manager.setup.SetupServiceimport org.openremote.model.manager.MapConfigimport org.openremote.model.map.MapResource+import org.openremote.model.security.ClientRoleimport org.openremote.model.util.ValueUtil+import org.openremote.setup.integration.KeycloakTestSetupimport org.openremote.test.ManagerContainerTraitimport spock.lang.Sharedimport spock.lang.Specification@@ -129,7 +135,24 @@ class MapResourceTest extends Specification implements ManagerContainerTrait {json2.glyphs == "http://127.0.0.1:" + serverPort + MapService.MAP_SHARED_DATA_BASE_URI + "/fonts/" + MapService.DEFAULT_GLYPHS_PATH}+ def "Retrieve a vector tile"() {+ when: "the zoom-zero tile is requested from the bundled MBTiles file"+ def response = mapResource.getTile(0, 0, 0)++ then: "the compressed vector tile is returned"+ response.withCloseable { r ->+ assert r.status == Response.Status.OK.statusCode+ assert r.getHeaderString("Content-Encoding") == "gzip"+ assert r.readEntity(byte[].class).length> 0+ return true+ }+ }+def "Upload custom map tiles"() {+ given:+ def mapService = container.getService(MapService.class)+ def originalLimit = mapService.customMapLimit+when: "valid tiles are uploaded"def response = clientTarget.path("map/upload")@@ -150,11 +173,17 @@ class MapResourceTest extends Specification implements ManagerContainerTrait {json.options.default.bounds.size() == 4json.sources != null- when: "invalid tiles are uploaded"+ and: "the custom-map status reports the uploaded file"+ def customMapInfo = mapResource.getCustomMapInfo()+ customMapInfo.get("filename").asText() == "eindhoven.mbtiles"+ customMapInfo.get("limit").asInt() == originalLimit++ when: "the custom map is deleted"mapResource.deleteMap(null)- then: "an internal server error should occur"+ then: "the uploaded file and custom-map status are cleared"!Files.exists(Path.of("tmp/map/eindhoven.mbtiles"))+ mapResource.getCustomMapInfo().get("filename").isNull()when: "invalid tiles are uploaded"response = clientTarget@@ -195,6 +224,9 @@ class MapResourceTest extends Specification implements ManagerContainerTrait {assert r.status == 413return true}++ cleanup:+ mapService.customMapLimit = originalLimit}def "Configure custom tile server URL"() {@@ -241,4 +273,40 @@ class MapResourceTest extends Specification implements ManagerContainerTrait {savedSettings.get("glyphs").textValue() == MapService.DEFAULT_GLYPHS_PATHsavedSettings.get("layers").isArray() && savedSettings.get("layers").size() > 0}++ def "Admin client roles alone cannot change global map settings"() {+ given: "a master realm user has admin client roles but no superuser realm role"+ def identityProvider = container.getService(ManagerIdentityService.class).getIdentityProvider()+ def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)+ def username = "map-admin-without-superuser"+ def user = keycloakTestSetup.createUser(MASTER_REALM, username, username, "Map", "Admin",+ "${username}@openremote.local", true,+ [ClientRole.READ_ADMIN, ClientRole.WRITE_ADMIN] as ClientRole[])+ def token = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, username, username)+ def restrictedMapResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, token)+ .proxy(MapResource.class)++ when: "the user saves map settings"+ restrictedMapResource.saveSettings(null, new MapConfig())++ then:+ thrown(ForbiddenException)++ when: "the user uploads custom map tiles"+ restrictedMapResource.uploadMap(null, "map.mbtiles")++ then:+ thrown(ForbiddenException)++ when: "the user deletes custom map tiles"+ restrictedMapResource.deleteMap(null)++ then:+ thrown(ForbiddenException)++ cleanup:+ if (user != null) {+ identityProvider.deleteUser(MASTER_REALM, user.id)+ }+ }}diff --git a/test/src/test/groovy/org/openremote/test/syslog/SyslogResourceTest.groovy b/test/src/test/groovy/org/openremote/test/syslog/SyslogResourceTest.groovyindex d45af4c0a..92566ef8c 100644--- a/test/src/test/groovy/org/openremote/test/syslog/SyslogResourceTest.groovy+++ b/test/src/test/groovy/org/openremote/test/syslog/SyslogResourceTest.groovy@@ -18,20 +18,31 @@*/package org.openremote.test.syslog+import groovy.json.JsonSlurper+import jakarta.ws.rs.ForbiddenExceptionimport jakarta.ws.rs.core.Response-import org.openremote.container.security.IdentityProvider-import org.openremote.container.security.IdentityService+import org.openremote.container.persistence.PersistenceServiceimport org.openremote.manager.security.ManagerIdentityProviderimport org.openremote.manager.security.ManagerIdentityServiceimport org.openremote.manager.setup.SetupServiceimport org.openremote.manager.syslog.SyslogServiceimport org.openremote.model.security.ClientRole+import org.openremote.model.syslog.SyslogCategory+import org.openremote.model.syslog.SyslogConfig+import org.openremote.model.syslog.SyslogEvent+import org.openremote.model.syslog.SyslogLevel+import org.openremote.model.syslog.SyslogResourceimport org.openremote.setup.integration.KeycloakTestSetupimport org.openremote.test.ManagerContainerTraitimport spock.lang.Sharedimport spock.lang.Specification+import java.time.Instant++import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD+import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULTimport static org.openremote.model.Constants.*+import static org.openremote.model.util.MapAccess.getStringclass SyslogResourceTest extends Specification implements ManagerContainerTrait {@@ -82,7 +93,105 @@ class SyslogResourceTest extends Specification implements ManagerContainerTraitdeleteUser(identityProvider)}- private String createUserToken(container, KeycloakTestSetup keycloakTestSetup, String roleName, ClientRole role) {+ def "Superuser can read and update syslog configuration and clear stored events"() {+ given: "the server container and a superuser resource proxy"+ def container = startContainer(defaultConfig(), defaultServices(new SyslogService()))+ def token = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID,+ MASTER_REALM_ADMIN_USER,+ getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT))+ def adminResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, token)+ .proxy(SyslogResource.class)+ def persistenceService = container.getService(PersistenceService.class)+ def originalConfig = adminResource.getConfig(null)+ def updatedConfig = new SyslogConfig(SyslogLevel.WARN,+ [SyslogCategory.API] as SyslogCategory[], originalConfig.storedMaxAgeMinutes + 1)+ String marker = "syslog-resource-test-${UUID.randomUUID()}"+ def now = Instant.now()++ when: "the superuser changes the storage configuration"+ adminResource.updateConfig(null, updatedConfig)+ def storedConfig = adminResource.getConfig(null)++ then:+ storedConfig.storedLevel == SyslogLevel.WARN+ storedConfig.storedCategories.toList() == [SyslogCategory.API]+ storedConfig.storedMaxAgeMinutes == updatedConfig.storedMaxAgeMinutes++ when: "a stored event is read through the resource"+ persistenceService.doTransaction { em ->+ em.persist(new SyslogEvent(now.toEpochMilli(), SyslogLevel.WARN,+ SyslogCategory.API, marker, "test event"))+ }+ def before = adminResource.getEvents(null, SyslogLevel.WARN, 10, 1,+ now.minusSeconds(60).toEpochMilli(), now.plusSeconds(60).toEpochMilli(),+ [SyslogCategory.API], [marker])++ then:+ before.withCloseable { r ->+ assert r.status == Response.Status.OK.statusCode+ assert new JsonSlurper().parseText(r.readEntity(String.class))*.message == ["test event"]+ return true+ }++ when: "the superuser clears stored events"+ adminResource.clearEvents(null)+ def after = adminResource.getEvents(null, SyslogLevel.WARN, 10, 1,+ now.minusSeconds(60).toEpochMilli(), now.plusSeconds(60).toEpochMilli(),+ [SyslogCategory.API], [marker])++ then:+ after.withCloseable { r ->+ assert r.status == Response.Status.OK.statusCode+ assert new JsonSlurper().parseText(r.readEntity(String.class)).isEmpty()+ return true+ }++ cleanup:+ if (originalConfig != null) {+ adminResource.updateConfig(null, originalConfig)+ }+ if (persistenceService != null && marker != null) {+ persistenceService.doTransaction { em ->+ em.createQuery("delete from SyslogEvent e where e.subCategory = :marker")+ .setParameter("marker", marker).executeUpdate()+ }+ }+ }++ def "Admin client roles alone cannot manage or read global syslog configuration"() {+ given: "a master realm user has admin client roles but no superuser realm role"+ def container = startContainer(defaultConfig(), defaultServices(new SyslogService()))+ def identityProvider = container.getService(ManagerIdentityService.class).getIdentityProvider()+ def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)+ def token = createUserToken(container, keycloakTestSetup, "admin-without-superuser",+ ClientRole.READ_ADMIN, ClientRole.WRITE_ADMIN)+ def restrictedSyslogResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, token)+ .proxy(SyslogResource.class)++ when: "the user clears stored events"+ restrictedSyslogResource.clearEvents(null)++ then:+ thrown(ForbiddenException)++ when: "the user reads the global syslog configuration"+ restrictedSyslogResource.getConfig(null)++ then:+ thrown(ForbiddenException)++ when: "the user updates the global syslog configuration"+ restrictedSyslogResource.updateConfig(null, new SyslogConfig(SyslogLevel.INFO,+ [SyslogCategory.API] as SyslogCategory[], 60))++ then:+ thrown(ForbiddenException)++ cleanup:+ deleteUser(identityProvider)+ }++ private String createUserToken(container, KeycloakTestSetup keycloakTestSetup, String roleName, ClientRole... roles) {def username = "syslog-test-${roleName}"def user = keycloakTestSetup.createUser(MASTER_REALM,@@ -92,7 +201,7 @@ class SyslogResourceTest extends Specification implements ManagerContainerTraitroleName,"${username}@openremote.local",true,- [role] as ClientRole[]+ roles)userId = user.id@@ -102,6 +211,7 @@ class SyslogResourceTest extends Specification implements ManagerContainerTraitprivate static void deleteUser(ManagerIdentityProvider identityProvider) {if (userId != null) {identityProvider.deleteUser(MASTER_REALM, userId)+ userId = null}}diff --git a/ui/app/manager/src/pages/page-configuration.ts b/ui/app/manager/src/pages/page-configuration.tsindex b8c0de461..ac1d65b01 100644--- a/ui/app/manager/src/pages/page-configuration.ts+++ b/ui/app/manager/src/pages/page-configuration.ts@@ -34,6 +34,8 @@ import type { OrConfRealmCard } from "../components/configuration/or-conf-realm/import type { OrConfPanel } from "../components/configuration/or-conf-panel";import { DefaultHeaderMainMenu, DefaultHeaderSecondaryMenu, DefaultRealmConfig } from "../index";import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";+import { i18next } from "@openremote/or-translate";+import { isAxiosError } from "@openremote/rest";declare const APP_VERSION: string;@@ -161,6 +163,9 @@ export class PageConfiguration extends Page<AppStateKeyed> {@state()protected loading = false;+ @state()+ protected saving = false;+@state()protected managerConfigurationChanged = false;@@ -243,15 +248,17 @@ export class PageConfiguration extends Page<AppStateKeyed> {return html`<or-translate value="notAuthenticated"></or-translate>`;}return html`+ ${this.saving ? html`<or-loading-indicator .overlay=${true}></or-loading-indicator>` : ""}${when(this.loading,() => html` <or-loading-indicator></or-loading-indicator> `,() => {const saveDisabled =- !this.managerConfigurationChanged &&- !this.mapConfigChanged &&- !this.tilesForUpload &&- !this.tilesForDeletion;+ this.saving ||+ (!this.managerConfigurationChanged &&+ !this.mapConfigChanged &&+ !this.tilesForUpload &&+ !this.tilesForDeletion);const realmHeading = html` <div id="heading" style="justify-content: space-between;"><span style="margin: 0;"><or-translate style="text-transform: uppercase;" value="configuration.realmStyling"></or-translate@@ -417,95 +424,96 @@ export class PageConfiguration extends Page<AppStateKeyed> {return (await manager.rest.api.RealmResource.getAccessible()).data;}- protected saveAllConfigs(config: ManagerAppConfig, mapConfig: MapConfig) {- this.loading = true;- let managerPromise;+ protected async saveAllConfigs(config: ManagerAppConfig, mapConfig: MapConfig) {+ this.saving = true;// Save the images to the server that have been uploaded by the user.// TODO: Optimize code so it only saves images that have been changed.- const filePromises = [];+ const imageUploads: Promise<void>[] = [];if (this.realmConfigPanel !== undefined) {const elems = this.realmConfigPanel.getCardElements() as OrConfRealmCard[];- elems.forEach((elem, index) => {+ elems.forEach((elem) => {const files = elem?.getFiles();- Object.entries(files).forEach(async ([x, y]) => {- filePromises.push(- manager.rest.api.ConfigurationResource.fileUpload(y, { path: (y as any).path }).then((file) => {- config.realms[elem.name][x] = file.data;- })+ Object.entries(files).forEach(([field, file]) => {+ imageUploads.push(+ manager.rest.api.ConfigurationResource.imageUpload(file, { path: (file as any).path })+ .then(({ data }) => {+ config.realms[elem.name][field] = data;+ })+ .catch((error) => {+ const detail =+ isAxiosError(error) && error.response?.status === 400 && typeof error.response.data === "string"+ ? error.response.data.trim().split("\n")[0]+ : "";+ const message = i18next.t("fileUploadFailed", { file: field });+ showSnackbar(+ undefined,+ detail && !detail.startsWith("Request failed with HTTP error status:")+ ? `${message}: ${detail}`+ : message,+ i18next.t("dismiss")+ );+ console.error(error);+ throw error;+ }));});});this.managerConfiguration = config;}- // POST map config if changed...- let mapPromise;- if (this.mapConfigChanged) {- mapPromise = manager.rest.api.MapResource.saveSettings(mapConfig)- .then(() => {- this.mapConfig = mapConfig;- })- .catch((reason) => {- console.error(reason);- });- }-- if (this.tilesForUpload) {- showSnackbar(undefined, "configuration.global.uploadingMapTiles");- const filename = this.tilesForUpload.name;- filePromises.push(- manager.rest.api.MapResource.uploadMap(- { filename },- {- headers: { "Content-Type": "application/octet-stream" },- data: this.tilesForUpload,- }- )- .then(({ data }) => {- this.customMapFilename = filename;- this.mapConfig = data as MapConfig;- })- .catch((reason) => {- showSnackbar(undefined, "configuration.global.uploadingMapTilesError");- console.error(reason);- })- .finally(() => {- this.tilesForUpload = null;- })- );- }+ try {+ // Wait for every image request before deciding whether the configuration can be saved.+ if ((await Promise.allSettled(imageUploads)).some((result) => result.status === "rejected")) {+ return;+ }- // We first wait for the filePromises to finish, so that- // we can use the path returned from the backend to store to the- // manager_config.- Promise.all(filePromises).then((arr: string[]) => {- // Wait for all requests to complete, then finish loading.- const promises = [+ // Save pending settings first: the tile upload then applies its authoritative bounds/center.+ await Promise.all([this.managerConfigurationChanged ? manager.rest.api.ConfigurationResource.update(config) : null,- this.mapConfigChanged ? mapPromise : null,- ];- Promise.all(promises).finally(() => {- // The deletion must happen after the config changes since deletion will re-center to the default map.- if (this.tilesForDeletion && !this.tilesForUpload) {- manager.rest.api.MapResource.deleteMap()- .then(({ data }) => {- this.tilesForDeletion = false;- this.customMapFilename = undefined;- this.mapConfig = data as MapConfig;- })- .catch((reason) => {- console.error(reason);- });+ this.mapConfigChanged ? manager.rest.api.MapResource.saveSettings(mapConfig) : null,+ ]);+ if (this.mapConfigChanged) {+ this.mapConfig = mapConfig;+ }++ if (this.tilesForUpload) {+ showSnackbar(undefined, "configuration.global.uploadingMapTiles");+ const filename = this.tilesForUpload.name;+ try {+ const { data } = await manager.rest.api.MapResource.uploadMap(+ { filename },+ { headers: { "Content-Type": "application/octet-stream" }, data: this.tilesForUpload }+ );+ this.customMapFilename = filename;+ this.mapConfig = data as MapConfig;+ this.tilesForUpload = null;+ this.tilesForDeletion = false;+ } catch (error) {+ showSnackbar(undefined, "configuration.global.uploadingMapTilesError");+ console.error(error);+ return;}- this.requestUpdate();- this.loading = false;- this.managerConfigurationChanged = false;- this.mapConfigChanged = false;- const configURL = (manager.managerUrl ?? "") + "/api/master/configuration/manager";- fetch(configURL, { cache: "reload" });- window.location.reload();- });- });+ }++ // Delete after saving settings so the map returns to its default center.+ if (this.tilesForDeletion) {+ const { data } = await manager.rest.api.MapResource.deleteMap();+ this.tilesForDeletion = false;+ this.customMapFilename = undefined;+ this.mapConfig = data as MapConfig;+ }++ this.managerConfigurationChanged = false;+ this.mapConfigChanged = false;+ const configURL = (manager.managerUrl ?? "") + "/api/master/configuration/manager";+ fetch(configURL, { cache: "reload" });+ window.location.reload();+ } catch (error) {+ showSnackbar(undefined, i18next.t("errorOccurred"), i18next.t("dismiss"));+ console.error(error);+ } finally {+ this.saving = false;+ }}}diff --git a/ui/app/manager/test/configuration-images.test.ts b/ui/app/manager/test/configuration-images.test.tsnew file mode 100644index 000000000..d315bab67--- /dev/null+++ b/ui/app/manager/test/configuration-images.test.ts@@ -0,0 +1,188 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * SPDX-License-Identifier: AGPL-3.0-or-later+ */+import { expect } from "@openremote/test";+import { test } from "./fixtures/manager.js";++// A one-pixel yellow PNG, enlarged by the SVG to make missing embedded images visible.+const embeddedPng =+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4/5/hPwAH/QL+ppTFtAAAAABJRU5ErkJggg==";+const styledSvg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="120" height="20">+ <style>.sheet { fill: rgb(255, 0, 0) } .gradient { fill: url(#paint) }</style>+ <defs>+ <linearGradient id="paint">+ <stop offset="0%" stop-color="blue"/><stop offset="100%" stop-color="blue"/>+ </linearGradient>+ <clipPath id="clip"><rect x="40" width="20" height="20"/></clipPath>+ <rect id="shape" width="20" height="20" fill="magenta"/>+ </defs>+ <rect id="sheet" class="sheet" width="20" height="20"/>+ <rect id="inline" x="20" width="20" height="20" style="fill: rgb(0, 255, 0)"/>+ <rect class="gradient" x="40" width="20" height="20" clip-path="url(#clip)"/>+ <use href="#shape" x="60"/>+ <image href="${embeddedPng}" x="80" width="20" height="20"/>+ <image xlink:href="${embeddedPng}" x="100" width="20" height="20"/>+</svg>`;++let imageUrl: string;++test.beforeEach(async ({ manager, baseURL }) => {+ // Reuse one test filename so repeated runs do not accumulate uploaded images.+ const response = await manager.api.ConfigurationResource.imageUpload(+ { name: "configuration-csp.svg", contents: Buffer.from(styledSvg).toString("base64"), binary: true },+ { path: "test/configuration-csp.svg" },+ { ...(await manager.adminConfig()), responseType: "text" }+ );+ imageUrl = new URL(response.data, baseURL).href;+});++/**+ * @given An uploaded SVG uses styles and embedded PNG images+ * @when The image is opened directly+ * @then Its normal styling is preserved and its embedded images are permitted by CSP+ */+test("should preserve SVG styles and embedded images when opening an image directly", async ({ page }) => {+ const violations: string[] = [];+ page.on("console", (message) => {+ if (message.text().includes("Content Security Policy")) {+ violations.push(message.text());+ }+ });+ await page.goto(imageUrl);++ await expect(page.locator("#sheet")).toHaveCSS("fill", "rgb(255, 0, 0)");+ await expect(page.locator("#inline")).toHaveCSS("fill", "rgb(0, 255, 0)");+ // Without img-src data:, the endpoint CSP blocks otherwise valid embedded raster images.+ expect(violations).toEqual([]);+});++/**+ * @given An uploaded SVG uses styles, local references and embedded PNG images+ * @when It is displayed through an img element+ * @then All six regions render with their expected colors+ */+test("should render styled SVG images with local fragments and embedded rasters", async ({ page }) => {+ await page.goto(new URL("/api/master/configuration/manager", imageUrl).href);+ await page.setContent('<img id="logo">');+ await page.locator("#logo").evaluate((image, url) => image.setAttribute("src", url), imageUrl);++ await expect(page.locator("#logo")).toHaveJSProperty("naturalWidth", 120);+ const colors = await page.locator("#logo").evaluate((element) => {+ const image = element as HTMLImageElement;+ const canvas = document.createElement("canvas");+ canvas.width = image.naturalWidth;+ canvas.height = image.naturalHeight;+ const context = canvas.getContext("2d")!;+ context.drawImage(image, 0, 0);+ return [10, 30, 50, 70, 90, 110].map((x) => Array.from(context.getImageData(x, 10, 1, 1).data));+ });++ // Preserve vector styling and embedded images referenced through both href and xlink:href.+ expect(colors).toEqual([+ [255, 0, 0, 255],+ [0, 255, 0, 255],+ [0, 0, 255, 255],+ [255, 0, 255, 255],+ [255, 255, 0, 255],+ [255, 255, 0, 255],+ ]);+});++const markExecution = "document.documentElement.setAttribute('data-executed', 'yes')";+const legacyDocuments = [+ {+ name: "SVG",+ contentType: "image/svg+xml",+ body: `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" onload="${markExecution}">+ <script>${markExecution}</script>+ <script href="https://upload-attack.invalid/script.js"/>+ <style>+ @import url("https://upload-attack.invalid/style.css");+ rect { fill: url("https://upload-attack.invalid/paint.svg#paint") }+ </style>+ <image href="https://upload-attack.invalid/image.png" width="20" height="20"/>+ <rect width="20" height="20"/>+ </svg>`,+ },+ {+ name: "HTML",+ contentType: "text/html",+ body: `<!doctype html><html><head>+ <base href="https://upload-attack.invalid/">+ <link rel="stylesheet" href="https://upload-attack.invalid/style.css">+ <script src="https://upload-attack.invalid/script.js"></script>+ <script>${markExecution}</script>+ </head><body onload="${markExecution}">+ <img src="https://upload-attack.invalid/image.png">+ <iframe src="https://upload-attack.invalid/frame.html"></iframe>+ <form action="https://upload-attack.invalid/credentials"><button>Submit</button></form>+ </body></html>`,+ },+];++for (const document of legacyDocuments) {+ /**+ * @given Legacy content contains scripts and external resource references+ * @when It is opened directly with the image endpoint's response headers+ * @then Scripts, external requests, and access to application storage are blocked+ */+ test(`should isolate legacy ${document.name} image responses`, async ({ page }) => {+ const externalRequests: string[] = [];+ const violations: string[] = [];+ page.on("console", (message) => {+ if (message.text().includes("Content Security Policy")) {+ violations.push(message.text());+ }+ });+ await page.route("https://upload-attack.invalid/**", (route) => {+ externalRequests.push(route.request().url());+ return route.fulfill({ body: "Unexpected external request" });+ });+ await page.route(imageUrl, async (route) => {+ // Keep the real endpoint headers; substitute only content that predates upload validation.+ const response = await route.fetch();+ const headers = response.headers();+ delete headers["content-length"];+ delete headers["content-encoding"];+ headers["content-type"] = document.contentType;+ await route.fulfill({ response, headers, body: document.body });+ });++ await page.goto(imageUrl);+ if (document.name === "HTML") {+ await page.getByRole("button", { name: "Submit" }).click();+ expect(await page.evaluate(() => window.document.baseURI)).toBe(imageUrl);+ await expect(page).toHaveURL(imageUrl);+ }++ // These checks fail without the endpoint's CSP, even with nosniff and an img-based UI.+ await expect(page.locator(":root")).not.toHaveAttribute("data-executed", "yes");+ expect(externalRequests).toEqual([]);+ expect(violations.some((message) => message.includes("img-src"))).toBe(true);+ expect(+ await page.evaluate(() => {+ try {+ window.localStorage.getItem("configuration-csp-test");+ return false;+ } catch (error) {+ return error instanceof DOMException && error.name === "SecurityError";+ }+ })+ ).toBe(true);+ });+}diff --git a/ui/app/manager/test/configuration.test.ts b/ui/app/manager/test/configuration.test.tsnew file mode 100644index 000000000..5e03c9f1f--- /dev/null+++ b/ui/app/manager/test/configuration.test.ts@@ -0,0 +1,128 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * SPDX-License-Identifier: AGPL-3.0-or-later+ */+import { expect } from "@openremote/test";+import { adminStatePath, test } from "./fixtures/manager.js";++test.use({ storageState: adminStatePath });++/**+ * @given A superuser has selected a new realm logo+ * @when The server rejects the image upload+ * @then The validation reason is shown, configuration is not saved, and the user can retry+ */+test("should keep the configuration editable after an image upload fails", async ({ page, manager }) => {+ let uploadAttempts = 0;+ let configUpdates = 0;+ await page.route("**/api/master/configuration/manager/image?**", (route) => {+ uploadAttempts++;+ return route.fulfill({+ status: 400,+ contentType: "text/plain",+ body: "No image decoder recognizes the uploaded data",+ });+ });+ await page.route("**/api/master/configuration/manager", (route) => {+ if (route.request().method() === "PUT") {+ configUpdates++;+ return route.fulfill({ status: 200, json: {} });+ }+ return route.continue();+ });++ await manager.goToRealmStartPage("master");+ await manager.navigateToMenuItem("Appearance");++ const configuration = page.locator("page-configuration");+ const saveButton = configuration.locator("#save-btn");+ const defaultRealm = configuration.locator("or-conf-realm-card").filter({ hasText: "default" }).first();+ await defaultRealm+ .locator("or-file-uploader input[type=file]")+ .first()+ .setInputFiles({+ name: "invalid.png",+ mimeType: "image/png",+ buffer: Buffer.from("not an image"),+ });+ await expect(saveButton).toBeEnabled();++ await saveButton.click();++ // A rejected upload previously left the page loading indefinitely and hid the validation failure.+ await expect(page.locator("or-mwc-snackbar").last()).toContainText(+ "Failed to upload logo: No image decoder recognizes the uploaded data"+ );+ await expect(saveButton).toBeEnabled();+ expect(configUpdates).toBe(0);++ await saveButton.click();+ await expect.poll(() => uploadAttempts).toBe(2);+ expect(configUpdates).toBe(0);+});++/**+ * @given A superuser has changed map settings and selected new tiles+ * @when Both changes are saved together+ * @then Pending settings are kept and the uploaded tiles determine the center and bounds+ */+test("should retain tile metadata when saving map settings with an upload", async ({ page, manager }) => {+ const calls: string[] = [];+ const newCenter = [10, 20];+ const newBounds = [9, 19, 11, 21];+ const override = "https://example.invalid/style.json";+ let storedConfig = {+ version: 8,+ options: { default: { center: [0, 0], bounds: [-1, -1, 1, 1], zoom: 10 } },+ sources: { vector_tiles: { type: "vector", tiles: [] } },+ layers: [],+ override: undefined as string | undefined,+ };+ await page.route("**/api/master/map", (route) => {+ if (route.request().method() === "PUT") {+ calls.push("settings");+ storedConfig = route.request().postDataJSON();+ }+ return route.fulfill({ json: storedConfig });+ });+ await page.route("**/api/master/map/upload?**", (route) => {+ calls.push("tiles");+ storedConfig.options.default.center = newCenter;+ storedConfig.options.default.bounds = newBounds;+ return route.fulfill({ json: storedConfig });+ });++ await manager.goToRealmStartPage("master");+ await manager.navigateToMenuItem("Appearance");+ const configuration = page.locator("page-configuration");+ const map = configuration.locator("or-conf-map-global");+ await map.locator(".map-style-server-group or-vaadin-text-field input").fill(override);+ await map.locator(".map-style-server-group or-vaadin-text-field input").press("Tab");+ await map.locator("#fileupload-elem").setInputFiles({+ name: "new.mbtiles",+ mimeType: "application/octet-stream",+ buffer: Buffer.from("mock tiles"),+ });+ await configuration.locator("#save-btn").click();++ await expect.poll(() => calls.length).toBe(2);+ // Saving the original settings after the upload used to restore stale center/bounds.+ expect(calls).toEqual(["settings", "tiles"]);+ expect(storedConfig.options.default.center).toEqual(newCenter);+ expect(storedConfig.options.default.bounds).toEqual(newBounds);+ expect(storedConfig.override).toBe(override);+});diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.jsonindex b3631e6b1..e87d0da42 100644--- a/ui/app/shared/locales/en/or.json+++ b/ui/app/shared/locales/en/or.json@@ -858,6 +858,7 @@"display": "Display","screen": "Screen","uploadFile": "Upload file",+ "fileUploadFailed": "Failed to upload {{file}}","fileSelected": "File selected","fileSaved": "File saved","thresholds": "Thresholds",