#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
fix(security): bound request size and harden the mobile scanner relay (#8672)
Reece Browne025f763f0152
diff --git a/app/common/src/main/java/stirling/software/common/service/MobileScannerService.java b/app/common/src/main/java/stirling/software/common/service/MobileScannerService.javaindex 17b9ac5be9..f9158832db 100644--- a/app/common/src/main/java/stirling/software/common/service/MobileScannerService.java+++ b/app/common/src/main/java/stirling/software/common/service/MobileScannerService.java@@ -1,6 +1,7 @@package stirling.software.common.service;import java.io.IOException;+import java.nio.file.FileAlreadyExistsException;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;@@ -19,16 +20,26 @@ import lombok.extern.slf4j.Slf4j;/*** Service for handling mobile scanner file uploads and temporary storage. Files are stored* temporarily and automatically cleaned up after 10 minutes or upon retrieval.+ *+ * <p>Uploads need no login, so they only go to sessions a desktop created, sessions expire a fixed+ * time after creation, and storage is capped; a batch over a cap is rejected whole.*/@Service@Slf4jpublic class MobileScannerService {private static final long SESSION_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes+ static final long MAX_FILE_BYTES = 50L * 1024 * 1024; // 50 MB+ static final long MAX_SESSION_BYTES = 500L * 1024 * 1024; // 500 MB+ static final int MAX_FILES_PER_SESSION = 500;+ static final long MAX_TOTAL_BYTES = 2L * 1024 * 1024 * 1024; // 2 GB+ static final int MAX_ACTIVE_SESSIONS = 1000;private static final Pattern FILENAME_SANITIZE_PATTERN = Pattern.compile("[^a-zA-Z0-9._-]");private static final Pattern SESSION_ID_VALIDATION_PATTERN = Pattern.compile("[a-zA-Z0-9-]+");private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile("[.][^.]+$");private final Map<String, SessionData> activeSessions = new ConcurrentHashMap<>();+ // Guards session create/delete and every SessionData count, so cap checks are atomic.+ private final Object storageLock = new Object();private final Path tempDirectory;public MobileScannerService() throws IOException {@@ -42,21 +53,25 @@ public class MobileScannerService {/*** Register a new session (called by desktop when QR code is generated)*- * @param sessionId Unique session identifier+ * @param sessionId Unique session identifier; an existing session with this id is replaced and+ * its files deleted* @return SessionInfo with creation time and expiry+ * @throws UploadLimitException if the live-session cap is reached*/public SessionInfo createSession(String sessionId) {validateSessionId(sessionId);SessionData session = new SessionData(sessionId);- activeSessions.put(sessionId, session);+ synchronized (storageLock) {+ // Replacing only the entry would orphan the old session's files.+ deleteSession(sessionId);+ ensureSessionCapacity();+ activeSessions.put(sessionId, session);+ }log.info("Created mobile scanner session: {}", sessionId);return new SessionInfo(- sessionId,- session.createdAt,- session.createdAt + SESSION_TIMEOUT_MS,- SESSION_TIMEOUT_MS);+ sessionId, session.createdAt, session.expiresAt(), SESSION_TIMEOUT_MS);}/**@@ -71,17 +86,13 @@ public class MobileScannerService {return null;}- long now = System.currentTimeMillis();- long expiryTime = session.getLastAccessTime() + SESSION_TIMEOUT_MS;-- // Check if expired- if (now > expiryTime) {+ if (session.isExpired(System.currentTimeMillis())) {deleteSession(sessionId);return null;}- session.updateLastAccess();- return new SessionInfo(sessionId, session.createdAt, expiryTime, SESSION_TIMEOUT_MS);+ return new SessionInfo(+ sessionId, session.createdAt, session.expiresAt(), SESSION_TIMEOUT_MS);}/**@@ -90,64 +101,130 @@ public class MobileScannerService {* @param sessionId Unique session identifier* @param files Files to upload* @throws IOException If file storage fails+ * @throws IllegalArgumentException if the session does not exist or has expired+ * @throws UploadLimitException if the batch would exceed a storage cap; nothing is stored*/public void uploadFiles(String sessionId, List<MultipartFile> files) throws IOException {validateSessionId(sessionId);- SessionData session =- activeSessions.computeIfAbsent(sessionId, id -> new SessionData(sessionId));+ List<MultipartFile> nonEmpty = files.stream().filter(file -> !file.isEmpty()).toList();+ long batchBytes = 0;+ for (MultipartFile file : nonEmpty) {+ if (file.getSize() > MAX_FILE_BYTES) {+ throw new UploadLimitException("File exceeds the mobile upload size limit", false);+ }+ batchBytes += file.getSize();+ }- // Create session directory- Path sessionDir = getSafeSessionDirectory(sessionId);- Files.createDirectories(sessionDir);+ SessionData session = reserve(sessionId, nonEmpty.size(), batchBytes);+ int unstoredFiles = nonEmpty.size();+ long unstoredBytes = batchBytes;+ try {+ Path sessionDir = getSafeSessionDirectory(sessionId);+ Files.createDirectories(sessionDir);- // Save each file- for (MultipartFile file : files) {- if (file.isEmpty()) {- continue;+ for (MultipartFile file : nonEmpty) {+ storeFile(session, sessionDir, file);+ unstoredFiles--;+ unstoredBytes -= file.getSize();}+ } finally {+ if (unstoredFiles > 0) {+ synchronized (storageLock) {+ session.fileCount -= unstoredFiles;+ session.storedBytes -= unstoredBytes;+ }+ }+ }+ }- String originalFilename = file.getOriginalFilename();- if (originalFilename == null || originalFilename.isBlank()) {- originalFilename = "upload-" + System.currentTimeMillis();+ /**+ * Reserves room for a batch. Counts and bytes are added up front so concurrent uploads cannot+ * both pass the same check.+ */+ private SessionData reserve(String sessionId, int fileCount, long bytes) {+ synchronized (storageLock) {+ // Only the logged-in desktop creates sessions.+ SessionData session = liveSession(sessionId);+ if (session == null) {+ throw new IllegalArgumentException("Session not found or expired");+ }+ if (session.fileCount + fileCount > MAX_FILES_PER_SESSION+ || session.storedBytes + bytes > MAX_SESSION_BYTES) {+ throw new UploadLimitException("Session upload limit reached", false);}+ if (totalStoredBytes() + bytes > MAX_TOTAL_BYTES) {+ deleteExpiredSessions(System.currentTimeMillis());+ }+ if (totalStoredBytes() + bytes > MAX_TOTAL_BYTES) {+ throw new UploadLimitException("Mobile upload storage is full", true);+ }+ session.fileCount += fileCount;+ session.storedBytes += bytes;+ return session;+ }+ }++ private void storeFile(SessionData session, Path sessionDir, MultipartFile file)+ throws IOException {+ String originalFilename = file.getOriginalFilename();+ if (originalFilename == null || originalFilename.isBlank()) {+ originalFilename = "upload-" + System.currentTimeMillis();+ }- // Sanitize filename- String safeFilename = sanitizeFilename(originalFilename);- Path filePath = sessionDir.resolve(safeFilename).normalize().toAbsolutePath();+ String safeFilename = sanitizeFilename(originalFilename);+ Path filePath = sessionDir.resolve(safeFilename).normalize().toAbsolutePath();- // Ensure resulting path stays within the session directory+ // Ensure resulting path stays within the session directory+ if (!filePath.startsWith(sessionDir)) {+ throw new IOException("Invalid filename");+ }++ // Handle duplicate filenames. createFile claims a name atomically, so concurrent+ // same-name uploads cannot share a path.+ int counter = 1;+ while (!tryCreate(filePath)) {+ String nameWithoutExt = FILE_EXTENSION_PATTERN.matcher(safeFilename).replaceFirst("");+ String ext =+ safeFilename.contains(".")+ ? safeFilename.substring(safeFilename.lastIndexOf('.'))+ : "";+ safeFilename = nameWithoutExt + "-" + counter + ext;+ filePath = sessionDir.resolve(safeFilename).normalize().toAbsolutePath();if (!filePath.startsWith(sessionDir)) {throw new IOException("Invalid filename");}+ counter++;+ }- // Handle duplicate filenames- int counter = 1;- while (Files.exists(filePath)) {- String nameWithoutExt =- FILE_EXTENSION_PATTERN.matcher(safeFilename).replaceFirst("");- String ext =- safeFilename.contains(".")- ? safeFilename.substring(safeFilename.lastIndexOf('.'))- : "";- safeFilename = nameWithoutExt + "-" + counter + ext;- filePath = sessionDir.resolve(safeFilename).normalize().toAbsolutePath();- if (!filePath.startsWith(sessionDir)) {- throw new IOException("Invalid filename");- }- counter++;- }-+ try {file.transferTo(filePath);+ } catch (IOException | RuntimeException e) {+ Files.deleteIfExists(filePath);+ throw e;+ }+ synchronized (storageLock) {+ // Deleted or replaced mid-upload: the file would count toward no cap.+ if (activeSessions.get(session.sessionId) != session) {+ Files.deleteIfExists(filePath);+ throw new IOException("Session was removed during upload");+ }session.addFile(new FileMetadata(safeFilename, file.getSize(), file.getContentType()));- log.info(- "Uploaded file for session {}: {} ({} bytes)",- sessionId,- safeFilename,- file.getSize());}+ log.info(+ "Uploaded file for session {}: {} ({} bytes)",+ session.sessionId,+ safeFilename,+ file.getSize());+ }- session.updateLastAccess();+ private static boolean tryCreate(Path filePath) throws IOException {+ try {+ Files.createFile(filePath);+ return true;+ } catch (FileAlreadyExistsException e) {+ return false;+ }}/**@@ -157,12 +234,13 @@ public class MobileScannerService {* @return List of file metadata, or empty list if session doesn't exist*/public List<FileMetadata> getSessionFiles(String sessionId) {- SessionData session = activeSessions.get(sessionId);+ SessionData session = liveSession(sessionId);if (session == null) {return List.of();}- session.updateLastAccess();- return new ArrayList<>(session.getFiles());+ synchronized (storageLock) {+ return new ArrayList<>(session.getFiles());+ }}/**@@ -171,10 +249,11 @@ public class MobileScannerService {* @param sessionId Session identifier* @param filename Filename to retrieve* @return File path- * @throws IOException If file not found or session doesn't exist+ * @throws IOException If file not found, already claimed by an earlier download, or session+ * doesn't exist*/public Path getFile(String sessionId, String filename) throws IOException {- SessionData session = activeSessions.get(sessionId);+ SessionData session = liveSession(sessionId);if (session == null) {throw new IOException("Session not found: " + sessionId);}@@ -184,14 +263,23 @@ public class MobileScannerService {throw new IOException("File not found: " + filename);}- session.updateLastAccess();- session.markFileAsDownloaded(filename);+ // Served once, as the file stays on disk while it streams. Checking the stored name rather+ // than the disk also rejects other spellings on case-insensitive filesystems.+ synchronized (storageLock) {+ if (!session.isStored(filename)) {+ throw new IOException("File not found: " + filename);+ }+ if (session.isDownloaded(filename)) {+ throw new IOException("File already downloaded: " + filename);+ }+ session.markFileAsDownloaded(filename);+ }return filePath;}/**- * Deletes a file after it has been served to the client. Should be called after successful- * download.+ * Deletes a file after it has been served to the client. The session stays open until it+ * expires or the desktop deletes it, so the phone can send further batches to the same QR code.** @param sessionId Session identifier* @param filename Filename to delete@@ -199,57 +287,87 @@ public class MobileScannerService {public void deleteFileAfterDownload(String sessionId, String filename) {try {Path filePath = getSafeFilePath(sessionId, filename);- Files.deleteIfExists(filePath);- log.info("Deleted file after download: {}/{}", sessionId, filename);-- // Check if all files have been downloaded - if so, delete the entire sessionSessionData session = activeSessions.get(sessionId);- if (session != null && session.allFilesDownloaded()) {- deleteSession(sessionId);- log.info("All files downloaded - deleted session: {}", sessionId);+ if (session == null) {+ return;}+ synchronized (storageLock) {+ // Unclaimed means the id was re-created mid-download and the name is a new file.+ if (!session.isDownloaded(filename)) {+ return;+ }+ // Released while the file is still on disk, so no new upload can reuse the name.+ session.releaseFile(filename);+ }+ Files.deleteIfExists(filePath);+ log.info("Deleted file after download: {}/{}", sessionId, filename);} catch (IOException | IllegalArgumentException e) {log.warn("Failed to delete file after download: {}/{}", sessionId, filename, e);}}+ /**+ * Makes a claimed file downloadable again after a download that did not send all of it.+ *+ * @param sessionId Session identifier+ * @param filename Filename whose claim is dropped+ */+ public void releaseDownloadClaim(String sessionId, String filename) {+ SessionData session = activeSessions.get(sessionId);+ if (session == null) {+ return;+ }+ synchronized (storageLock) {+ if (session.isDownloaded(filename)) {+ session.unmarkDownloaded(filename);+ }+ }+ }+/*** Deletes a session and all its files** @param sessionId Session to delete*/public void deleteSession(String sessionId) {- SessionData session = activeSessions.remove(sessionId);- if (session != null) {- try {- Path sessionDir = getSafeSessionDirectory(sessionId);- if (Files.exists(sessionDir)) {- // Delete all files in session directory- try (var paths = Files.walk(sessionDir)) {- paths.sorted(- (a, b) ->- -a.compareTo(- b)) // Reverse order to delete files before- // directory- .forEach(- path -> {- try {- Files.deleteIfExists(path);- } catch (IOException e) {- log.warn("Failed to delete file: {}", path, e);- }- });- }- }+ // Locked so createSession cannot re-register the id before the walk deletes its files.+ synchronized (storageLock) {+ SessionData session = activeSessions.remove(sessionId);+ if (session != null) {+ deleteSessionDirectory(sessionId);log.info("Deleted session: {}", sessionId);- } catch (IllegalArgumentException e) {- log.warn(- "Refused to delete session with invalid sessionId '{}': {}",- sessionId,- e.getMessage());- } catch (IOException e) {- log.error("Error deleting session directory: {}", sessionId, e);+ } else if (sessionId != null+ && SESSION_ID_VALIDATION_PATTERN.matcher(sessionId).matches()) {+ // A directory can outlive its entry (e.g. an earlier delete raced an upload).+ deleteSessionDirectory(sessionId);+ }+ }+ }++ private void deleteSessionDirectory(String sessionId) {+ try {+ Path sessionDir = getSafeSessionDirectory(sessionId);+ if (Files.exists(sessionDir)) {+ try (var paths = Files.walk(sessionDir)) {+ // Deepest first, so each directory is empty when its turn comes.+ paths.sorted((a, b) -> -a.compareTo(b))+ .forEach(+ path -> {+ try {+ Files.deleteIfExists(path);+ } catch (IOException e) {+ log.warn("Failed to delete file: {}", path, e);+ }+ });+ }}+ } catch (IllegalArgumentException e) {+ log.warn(+ "Refused to delete session with invalid sessionId '{}': {}",+ sessionId,+ e.getMessage());+ } catch (IOException e) {+ log.error("Error deleting session directory: {}", sessionId, e);}}@@ -257,21 +375,101 @@ public class MobileScannerService {@Scheduled(fixedRate = 5 * 60 * 1000)public void cleanupExpiredSessions() {long now = System.currentTimeMillis();- List<String> expiredSessions = new ArrayList<>();+ synchronized (storageLock) {+ deleteExpiredSessions(now);+ }+ deleteOrphanedDirectories(now);+ }- activeSessions.forEach(- (sessionId, session) -> {- if (now - session.getLastAccessTime() > SESSION_TIMEOUT_MS) {- expiredSessions.add(sessionId);- }- });+ // Caller must hold storageLock.+ private void deleteExpiredSessions(long now) {+ List<String> expired =+ activeSessions.entrySet().stream()+ .filter(entry -> entry.getValue().isExpired(now))+ .map(Map.Entry::getKey)+ .toList();+ if (!expired.isEmpty()) {+ log.info("Cleaning up {} expired mobile scanner sessions", expired.size());+ expired.forEach(this::deleteSession);+ }+ }- if (!expiredSessions.isEmpty()) {- log.info("Cleaning up {} expired mobile scanner sessions", expiredSessions.size());- expiredSessions.forEach(this::deleteSession);+ /** Removes session directories with no live session, such as those left before a restart. */+ private void deleteOrphanedDirectories(long now) {+ if (!Files.isDirectory(tempDirectory)) {+ return;+ }+ List<Path> dirs;+ try (var paths = Files.list(tempDirectory)) {+ dirs =+ paths.filter(Files::isDirectory)+ .filter(+ dir ->+ SESSION_ID_VALIDATION_PATTERN+ .matcher(dir.getFileName().toString())+ .matches())+ .toList();+ } catch (IOException e) {+ log.warn("Failed to list mobile scanner temp directory", e);+ return;+ }+ for (Path dir : dirs) {+ String sessionId = dir.getFileName().toString();+ try {+ if (activeSessions.containsKey(sessionId)+ || now - Files.getLastModifiedTime(dir).toMillis() <= SESSION_TIMEOUT_MS) {+ continue;+ }+ } catch (IOException e) {+ continue;+ }+ synchronized (storageLock) {+ if (!activeSessions.containsKey(sessionId)) {+ log.info("Deleting orphaned mobile scanner directory: {}", sessionId);+ deleteSessionDirectory(sessionId);+ }+ }}}+ // Caller must hold storageLock. Expired sessions are purged first so they stop holding the+ // caps before the next sweep.+ private void ensureSessionCapacity() {+ if (activeSessions.size() >= MAX_ACTIVE_SESSIONS) {+ deleteExpiredSessions(System.currentTimeMillis());+ }+ if (activeSessions.size() >= MAX_ACTIVE_SESSIONS) {+ throw new UploadLimitException("Too many active mobile upload sessions", true);+ }+ }++ /**+ * @return bytes the session can still accept, or -1 if it does not exist or has expired+ */+ public long remainingSessionBytes(String sessionId) {+ if (sessionId == null) {+ return -1;+ }+ synchronized (storageLock) {+ SessionData session = liveSession(sessionId);+ return session == null ? -1 : MAX_SESSION_BYTES - session.storedBytes;+ }+ }++ private SessionData liveSession(String sessionId) {+ SessionData session = activeSessions.get(sessionId);+ return session == null || session.isExpired(System.currentTimeMillis()) ? null : session;+ }++ // Caller must hold storageLock. Bounded by MAX_ACTIVE_SESSIONS, so a scan is cheap.+ private long totalStoredBytes() {+ long total = 0;+ for (SessionData session : activeSessions.values()) {+ total += session.storedBytes;+ }+ return total;+ }+private void validateSessionId(String sessionId) {if (sessionId == null || sessionId.isBlank()) {throw new IllegalArgumentException("Session ID cannot be empty");@@ -401,44 +599,82 @@ public class MobileScannerService {}}- /** Session data tracking */+ /** Thrown when an upload or new session would exceed a mobile scanner storage cap. */+ public static class UploadLimitException extends RuntimeException {+ private final boolean serverCapacity;++ public UploadLimitException(String message, boolean serverCapacity) {+ super(message);+ this.serverCapacity = serverCapacity;+ }++ /**+ * @return true if the server-wide cap was hit rather than a per-file or per-session one+ */+ public boolean isServerCapacity() {+ return serverCapacity;+ }+ }++ /** Session data tracking. Files and counters are guarded by {@code storageLock}. */private static class SessionData {private final String sessionId;private final List<FileMetadata> files = new ArrayList<>();private final Map<String, Boolean> downloadedFiles = new HashMap<>();+ private final Map<String, Long> storedFileSizes = new HashMap<>();private final long createdAt;- private long lastAccessTime;+ // Includes bytes reserved for uploads still being written.+ private long storedBytes;+ // Every file accepted over the session's life; downloads do not give the slot back.+ private int fileCount;public SessionData(String sessionId) {this.sessionId = sessionId;this.createdAt = System.currentTimeMillis();- this.lastAccessTime = createdAt;}public void addFile(FileMetadata file) {files.add(file);downloadedFiles.put(file.getFilename(), false);+ storedFileSizes.put(file.getFilename(), file.getSize());+ }++ public void releaseFile(String filename) {+ Long size = storedFileSizes.remove(filename);+ if (size != null) {+ storedBytes -= size;+ }+ files.removeIf(file -> file.getFilename().equals(filename));+ downloadedFiles.remove(filename);}public List<FileMetadata> getFiles() {return files;}+ public boolean isStored(String filename) {+ return storedFileSizes.containsKey(filename);+ }++ public boolean isDownloaded(String filename) {+ return Boolean.TRUE.equals(downloadedFiles.get(filename));+ }+public void markFileAsDownloaded(String filename) {downloadedFiles.put(filename, true);}- public boolean allFilesDownloaded() {- return !downloadedFiles.isEmpty()- && downloadedFiles.values().stream().allMatch(downloaded -> downloaded);+ public void unmarkDownloaded(String filename) {+ downloadedFiles.put(filename, false);}- public void updateLastAccess() {- this.lastAccessTime = System.currentTimeMillis();+ // Fixed at creation, so polling cannot keep a session alive.+ public long expiresAt() {+ return createdAt + SESSION_TIMEOUT_MS;}- public long getLastAccessTime() {- return lastAccessTime;+ public boolean isExpired(long now) {+ return now > expiresAt();}}}diff --git a/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.java b/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.javaindex aca5b68fd2..c3c4757acf 100644--- a/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.java+++ b/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.java@@ -15,6 +15,9 @@ public class RequestUriUtils {private static final Pattern SHARE_LINK_API_PATTERN =Pattern.compile("^/api/v1/storage/share-links/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$");+ // The phone's two mobile-scanner calls, matched exactly so only a bare session id passes+ private static final Pattern MOBILE_SCANNER_PHONE_PATTERN =+ Pattern.compile("^/api/v1/mobile-scanner/(validate-session|upload)/[A-Za-z0-9-]+$");// Invite tokens are 36-char lowercase UUIDs (UUID.randomUUID().toString()); match exactlyprivate static final Pattern INVITE_LINK_PATTERN =Pattern.compile(@@ -209,8 +212,8 @@ public class RequestUriUtils {|| trimmedUri.startsWith("/healthz")|| trimmedUri.startsWith("/liveness")|| trimmedUri.startsWith("/readiness")- || trimmedUri.startsWith(- "/api/v1/mobile-scanner/") // Mobile scanner endpoints (no auth)+ // The phone that scans the QR code has no credentials+ || MOBILE_SCANNER_PHONE_PATTERN.matcher(trimmedUri).matches()|| trimmedUri.startsWith("/api/v1/webhooks/")|| trimmedUri.startsWith("/v1/api-docs")// Workflow participant endpoints - access controlled by share tokens, not logindiff --git a/app/common/src/test/java/stirling/software/common/service/MobileScannerServiceTest.java b/app/common/src/test/java/stirling/software/common/service/MobileScannerServiceTest.javaindex 1bfc166676..bb1fe9d008 100644--- a/app/common/src/test/java/stirling/software/common/service/MobileScannerServiceTest.java+++ b/app/common/src/test/java/stirling/software/common/service/MobileScannerServiceTest.java@@ -6,6 +6,8 @@ import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;+import java.nio.file.attribute.FileTime;+import java.util.ArrayList;import java.util.List;import org.junit.jupiter.api.BeforeEach;@@ -19,6 +21,7 @@ import org.springframework.web.multipart.MultipartFile;import stirling.software.common.service.MobileScannerService.FileMetadata;import stirling.software.common.service.MobileScannerService.SessionInfo;+import stirling.software.common.service.MobileScannerService.UploadLimitException;/*** Unit tests for {@link MobileScannerService}. The service stores uploaded files in a temp@@ -119,17 +122,55 @@ class MobileScannerServiceTest {}@Test- @DisplayName("expires and removes a session whose last access is in the past")+ @DisplayName("expires and removes a session created more than the timeout ago")void expiredSessionRemoved() {service.createSession("expired");- // Force the underlying session's last access far into the past.- forceLastAccess("expired", System.currentTimeMillis() - (20 * 60 * 1000L));+ forceCreatedAt("expired", System.currentTimeMillis() - (20 * 60 * 1000L));assertNull(service.validateSession("expired"));// After expiry the session should be gone entirely.assertNull(service.validateSession("expired"));}++ @Test+ @DisplayName("an expired session's files are not listed or served before the sweep")+ void expiredSessionHidesFiles() throws IOException {+ service.createSession("gone");+ service.uploadFiles("gone", List.of(file("a.txt", "x")));+ forceCreatedAt("gone", System.currentTimeMillis() - (20 * 60 * 1000L));++ assertTrue(service.getSessionFiles("gone").isEmpty());+ assertThrows(IOException.class, () -> service.getFile("gone", "a.txt"));+ }++ @Test+ @DisplayName("remainingSessionBytes reports a live session's room and -1 otherwise")+ void remainingSessionBytes() throws IOException {+ service.createSession("live");+ service.uploadFiles("live", List.of(file("a.txt", "xyz")));+ service.createSession("dead");+ forceCreatedAt("dead", System.currentTimeMillis() - (20 * 60 * 1000L));++ assertEquals(+ MobileScannerService.MAX_SESSION_BYTES - 3,+ service.remainingSessionBytes("live"));+ assertEquals(-1, service.remainingSessionBytes("dead"));+ assertEquals(-1, service.remainingSessionBytes("never"));+ assertEquals(-1, service.remainingSessionBytes(null));+ }++ @Test+ @DisplayName("reads do not push the expiry back")+ void readsDoNotExtendExpiry() throws IOException {+ long expiresAt = service.createSession("fixed").getExpiresAt();+ service.uploadFiles("fixed", List.of(file("a.txt", "x")));++ service.getSessionFiles("fixed");+ service.getFile("fixed", "a.txt");++ assertEquals(expiresAt, service.validateSession("fixed").getExpiresAt());+ }}@Nested@@ -156,12 +197,42 @@ class MobileScannerServiceTest {}@Test- @DisplayName("auto-creates a session when uploading to an unregistered session ID")- void autoCreatesSession() throws IOException {- service.uploadFiles("new-session", List.of(file("a.txt", "data")));+ @DisplayName("rejects uploads to a session that was never created")+ void rejectsUnknownSession() {+ assertThrows(+ IllegalArgumentException.class,+ () -> service.uploadFiles("new-session", List.of(file("a.txt", "data"))));- List<FileMetadata> metas = service.getSessionFiles("new-session");- assertEquals(1, metas.size());+ assertNull(service.validateSession("new-session"));+ assertFalse(Files.exists(tempDir.resolve("new-session")));+ }++ @Test+ @DisplayName("rejects uploads to an expired session")+ void rejectsExpiredSession() {+ service.createSession("late");+ forceCreatedAt("late", System.currentTimeMillis() - (20 * 60 * 1000L));++ assertThrows(+ IllegalArgumentException.class,+ () -> service.uploadFiles("late", List.of(file("a.txt", "data"))));+ }++ @Test+ @DisplayName("accepts another batch after the first one was collected")+ void acceptsBatchAfterCollection() throws IOException {+ service.createSession("again");+ service.uploadFiles("again", List.of(file("a.txt", "x")));+ service.getFile("again", "a.txt");+ service.deleteFileAfterDownload("again", "a.txt");++ service.uploadFiles("again", List.of(file("b.txt", "y")));++ assertEquals(+ List.of("b.txt"),+ service.getSessionFiles("again").stream()+ .map(FileMetadata::getFilename)+ .toList());}@Test@@ -317,6 +388,46 @@ class MobileScannerServiceTest {}}+ @Nested+ @DisplayName("getFile claims")+ class GetFileClaims {++ @Test+ @DisplayName("a file can be claimed for download only once")+ void claimedOnce() throws IOException {+ service.createSession("c1");+ service.uploadFiles("c1", List.of(file("a.txt", "x")));++ service.getFile("c1", "a.txt");++ assertThrows(IOException.class, () -> service.getFile("c1", "a.txt"));+ }++ @Test+ @DisplayName("a re-uploaded file with a downloaded name can be claimed again")+ void reuploadedNameClaimable() throws IOException {+ service.createSession("c2");+ service.uploadFiles("c2", List.of(file("a.txt", "x"), file("b.txt", "y")));+ service.getFile("c2", "a.txt");+ service.deleteFileAfterDownload("c2", "a.txt");++ service.uploadFiles("c2", List.of(file("a.txt", "z")));++ assertDoesNotThrow(() -> service.getFile("c2", "a.txt"));+ }++ @Test+ @DisplayName("a file on disk that the session did not store is not served")+ void unstoredFileNotServed() throws IOException {+ service.createSession("c3");+ service.uploadFiles("c3", List.of(file("a.txt", "x")));+ Files.writeString(tempDir.resolve("c3").resolve("other.txt"), "y");++ assertThrows(IOException.class, () -> service.getFile("c3", "other.txt"));+ assertDoesNotThrow(() -> service.getFile("c3", "a.txt"));+ }+ }+@Nested@DisplayName("deleteFileAfterDownload")class DeleteFileAfterDownload {@@ -327,25 +438,49 @@ class MobileScannerServiceTest {service.createSession("d1");service.uploadFiles("d1", List.of(file("a.txt", "x"), file("b.txt", "y")));+ service.getFile("d1", "a.txt");service.deleteFileAfterDownload("d1", "a.txt");assertFalse(Files.exists(tempDir.resolve("d1").resolve("a.txt")));- // Session still present because not all files have been downloaded.assertNotNull(service.validateSession("d1"));}@Test- @DisplayName("deletes the entire session once all files are marked downloaded")- void deletesSessionWhenAllDownloaded() throws IOException {+ @DisplayName("keeps the session open once every file is downloaded")+ void keepsSessionWhenAllDownloaded() throws IOException {service.createSession("d2");service.uploadFiles("d2", List.of(file("only.txt", "x")));- // Mark the file as downloaded via getFile, then delete it.service.getFile("d2", "only.txt");service.deleteFileAfterDownload("d2", "only.txt");- assertNull(service.validateSession("d2"));- assertFalse(Files.exists(tempDir.resolve("d2")));+ assertNotNull(service.validateSession("d2"));+ assertTrue(service.getSessionFiles("d2").isEmpty());+ assertFalse(Files.exists(tempDir.resolve("d2").resolve("only.txt")));+ }++ @Test+ @DisplayName("leaves an unclaimed file alone, such as a new upload to a re-created id")+ void ignoresUnclaimedFile() throws IOException {+ service.createSession("d4");+ service.uploadFiles("d4", List.of(file("a.txt", "x")));++ service.deleteFileAfterDownload("d4", "a.txt");++ assertTrue(Files.exists(tempDir.resolve("d4").resolve("a.txt")));+ assertEquals(1, service.getSessionFiles("d4").size());+ }++ @Test+ @DisplayName("a released claim makes the file downloadable again")+ void releasedClaimAllowsRetry() throws IOException {+ service.createSession("d5");+ service.uploadFiles("d5", List.of(file("a.txt", "x")));+ service.getFile("d5", "a.txt");++ service.releaseDownloadClaim("d5", "a.txt");++ assertDoesNotThrow(() -> service.getFile("d5", "a.txt"));}@Test@@ -384,6 +519,17 @@ class MobileScannerServiceTest {assertFalse(Files.exists(tempDir.resolve("x1")));}+ @Test+ @DisplayName("removes a leftover directory even when the session is unknown")+ void removesLeftoverDirectory() throws IOException {+ Path leftover = Files.createDirectories(tempDir.resolve("leftover"));+ Files.write(leftover.resolve("a.jpg"), new byte[] {1});++ service.deleteSession("leftover");++ assertFalse(Files.exists(leftover));+ }+@Test@DisplayName("is a no-op for an unknown session")void unknownSessionNoOp() {@@ -400,7 +546,7 @@ class MobileScannerServiceTest {void removesExpired() throws IOException {service.createSession("old");service.uploadFiles("old", List.of(file("a.txt", "x")));- forceLastAccess("old", System.currentTimeMillis() - (20 * 60 * 1000L));+ forceCreatedAt("old", System.currentTimeMillis() - (20 * 60 * 1000L));service.cleanupExpiredSessions();@@ -418,6 +564,27 @@ class MobileScannerServiceTest {assertNotNull(service.validateSession("fresh"));}+ @Test+ @DisplayName("removes stale directories that have no live session")+ void removesOrphanedDirectories() throws IOException {+ Path stale = Files.createDirectories(tempDir.resolve("stale"));+ Files.write(stale.resolve("a.jpg"), new byte[] {1});+ Files.setLastModifiedTime(+ stale, FileTime.fromMillis(System.currentTimeMillis() - 20 * 60 * 1000L));+ Path recent = Files.createDirectories(tempDir.resolve("recent"));+ service.createSession("live");+ service.uploadFiles("live", List.of(file("a.txt", "x")));+ Files.setLastModifiedTime(+ tempDir.resolve("live"),+ FileTime.fromMillis(System.currentTimeMillis() - 20 * 60 * 1000L));++ service.cleanupExpiredSessions();++ assertFalse(Files.exists(stale));+ assertTrue(Files.exists(recent));+ assertTrue(Files.exists(tempDir.resolve("live").resolve("a.txt")));+ }+@Test@DisplayName("does not throw when there are no sessions")void noSessionsNoThrow() {@@ -425,6 +592,271 @@ class MobileScannerServiceTest {}}+ @Nested+ @DisplayName("storage limits")+ class StorageLimits {++ private static final long MAX_FILE = MobileScannerService.MAX_FILE_BYTES;++ @Test+ @DisplayName("rejects a file over the per-file cap and stores nothing from the batch")+ void rejectsOversizedFile() {+ service.createSession("big");+ UploadLimitException e =+ assertThrows(+ UploadLimitException.class,+ () ->+ service.uploadFiles(+ "big",+ List.of(+ file("ok.txt", "x"),+ sized("huge.jpg", MAX_FILE + 1))));++ assertFalse(e.isServerCapacity());+ assertFalse(Files.exists(tempDir.resolve("big")));+ assertTrue(service.getSessionFiles("big").isEmpty());+ }++ @Test+ @DisplayName("rejects a batch that would exceed the per-session file count")+ void rejectsTooManyFiles() throws IOException {+ List<MultipartFile> files = new ArrayList<>();+ for (int i = 0; i < MobileScannerService.MAX_FILES_PER_SESSION; i++) {+ files.add(file("f" + i + ".txt", "x"));+ }+ service.createSession("many");+ service.uploadFiles("many", files);++ assertThrows(+ UploadLimitException.class,+ () -> service.uploadFiles("many", List.of(file("one-more.txt", "x"))));+ assertEquals(+ MobileScannerService.MAX_FILES_PER_SESSION,+ service.getSessionFiles("many").size());+ }++ @Test+ @DisplayName("rejects uploads past the per-session byte cap")+ void rejectsSessionBytes() throws IOException {+ fillSession("s", MobileScannerService.MAX_SESSION_BYTES);++ UploadLimitException e =+ assertThrows(+ UploadLimitException.class,+ () -> service.uploadFiles("s", List.of(file("extra.txt", "x"))));+ assertFalse(e.isServerCapacity());+ }++ @Test+ @DisplayName("rejects uploads past the server-wide byte cap")+ void rejectsTotalBytes() throws IOException {+ fillServer();+ service.createSession("other");++ UploadLimitException e =+ assertThrows(+ UploadLimitException.class,+ () -> service.uploadFiles("other", List.of(file("a.txt", "x"))));+ assertTrue(e.isServerCapacity());+ }++ @Test+ @DisplayName("a downloaded file frees its bytes")+ void downloadReleasesBytes() throws IOException {+ fillServer();+ service.getFile("fill-0", "f0.jpg");+ service.deleteFileAfterDownload("fill-0", "f0.jpg");+ service.createSession("other");++ assertDoesNotThrow(() -> service.uploadFiles("other", List.of(file("a.txt", "x"))));+ }++ @Test+ @DisplayName("deleting a session frees its bytes")+ void deleteSessionReleasesBytes() throws IOException {+ fillServer();+ service.deleteSession("fill-0");+ service.createSession("other");++ assertDoesNotThrow(() -> service.uploadFiles("other", List.of(file("a.txt", "x"))));+ }++ @Test+ @DisplayName("a reused filename releases only its own size")+ void reusedFilenameReleasesOwnSize() throws IOException {+ service.createSession("r");+ service.uploadFiles("r", List.of(sized("a.jpg", MAX_FILE), file("keep.txt", "x")));+ service.getFile("r", "a.jpg");+ service.deleteFileAfterDownload("r", "a.jpg");+ service.uploadFiles("r", List.of(sized("a.jpg", 10)));+ service.getFile("r", "a.jpg");+ service.deleteFileAfterDownload("r", "a.jpg");++ assertEquals(1L, storedBytes());+ }++ @Test+ @DisplayName("a failed write releases its reservation")+ void failedWriteReleasesReservation() {+ MultipartFile failing =+ new MockMultipartFile("file", "bad.jpg", "image/jpeg", new byte[] {1}) {+ @Override+ public long getSize() {+ return MAX_FILE;+ }++ @Override+ public void transferTo(Path dest) throws IOException {+ throw new IOException("disk full");+ }+ };++ service.createSession("f");+ assertThrows(IOException.class, () -> service.uploadFiles("f", List.of(failing)));+ assertEquals(0L, storedBytes());+ }++ @Test+ @DisplayName("caps the number of live sessions, but re-creating an existing id is allowed")+ void capsSessions() {+ for (int i = 0; i < MobileScannerService.MAX_ACTIVE_SESSIONS; i++) {+ service.createSession("s" + i);+ }++ UploadLimitException e =+ assertThrows(UploadLimitException.class, () -> service.createSession("new"));+ assertTrue(e.isServerCapacity());+ assertDoesNotThrow(() -> service.createSession("s0"));+ }++ @Test+ @DisplayName("expired sessions stop holding the caps before the sweep runs")+ void expiredSessionsFreeCaps() throws IOException {+ fillServer();+ for (int i = 0; i < 4; i++) {+ forceCreatedAt("fill-" + i, System.currentTimeMillis() - (20 * 60 * 1000L));+ }+ service.createSession("other");++ assertDoesNotThrow(() -> service.uploadFiles("other", List.of(file("a.txt", "x"))));+ assertFalse(Files.exists(tempDir.resolve("fill-0")));+ }++ @Test+ @DisplayName("re-creating a session deletes its old files and frees their bytes")+ void recreateDeletesOldFiles() throws IOException {+ service.createSession("again");+ service.uploadFiles("again", List.of(sized("a.jpg", MAX_FILE)));++ service.createSession("again");++ assertFalse(Files.exists(tempDir.resolve("again").resolve("a.jpg")));+ assertTrue(service.getSessionFiles("again").isEmpty());+ assertEquals(0L, storedBytes());+ }++ @Test+ @DisplayName("a file written after its session was removed is deleted, not left uncounted")+ void sessionRemovedMidUpload() {+ MultipartFile racing =+ new MockMultipartFile("file", "late.jpg", "image/jpeg", new byte[] {1}) {+ @Override+ public void transferTo(Path dest) throws IOException {+ service.createSession("race");+ service.uploadFiles("race", List.of(file("new.txt", "x")));+ Files.write(dest, new byte[] {1});+ }+ };++ service.createSession("race");+ assertThrows(IOException.class, () -> service.uploadFiles("race", List.of(racing)));++ assertFalse(Files.exists(tempDir.resolve("race").resolve("late.jpg")));+ assertTrue(Files.exists(tempDir.resolve("race").resolve("new.txt")));+ assertEquals(1L, storedBytes());+ }++ @Test+ @DisplayName("same-name uploads in flight together get distinct files and byte counts")+ void concurrentSameNameUploads() throws IOException {+ MultipartFile outer =+ new MockMultipartFile("file", "dup.jpg", "image/jpeg", new byte[] {1}) {+ @Override+ public void transferTo(Path dest) throws IOException {+ service.uploadFiles("same", List.of(sized("dup.jpg", 10)));+ Files.write(dest, new byte[] {1});+ }+ };++ service.createSession("same");+ service.uploadFiles("same", List.of(outer));++ assertEquals(+ List.of("dup-1.jpg", "dup.jpg"),+ service.getSessionFiles("same").stream()+ .map(FileMetadata::getFilename)+ .toList());+ assertEquals(11L, storedBytes());+ service.getFile("same", "dup.jpg");+ service.deleteFileAfterDownload("same", "dup.jpg");+ assertEquals(10L, storedBytes());+ }++ @Test+ @DisplayName("a failed write removes the file and its reservation")+ void failedWriteRemovesFile() {+ MultipartFile failing =+ new MockMultipartFile("file", "bad.jpg", "image/jpeg", new byte[] {1}) {+ @Override+ public void transferTo(Path dest) throws IOException {+ throw new IOException("disk full");+ }+ };++ service.createSession("fail");+ assertThrows(IOException.class, () -> service.uploadFiles("fail", List.of(failing)));++ assertFalse(Files.exists(tempDir.resolve("fail").resolve("bad.jpg")));+ assertEquals(0L, storedBytes());+ }++ private void fillSession(String sessionId, long bytes) throws IOException {+ List<MultipartFile> files = new ArrayList<>();+ for (int i = 0; bytes > 0; i++) {+ long size = Math.min(bytes, MAX_FILE);+ files.add(sized("f" + i + ".jpg", size));+ bytes -= size;+ }+ service.createSession(sessionId);+ service.uploadFiles(sessionId, files);+ }++ private void fillServer() throws IOException {+ long remaining = MobileScannerService.MAX_TOTAL_BYTES;+ for (int i = 0; remaining > 0; i++) {+ long bytes = Math.min(remaining, MobileScannerService.MAX_SESSION_BYTES);+ fillSession("fill-" + i, bytes);+ remaining -= bytes;+ }+ }++ private long storedBytes() {+ Long total = ReflectionTestUtils.invokeMethod(service, "totalStoredBytes");+ assertNotNull(total);+ return total;+ }+ }++ /** A one-byte file that reports {@code size}, so caps can be tested without large writes. */+ private MultipartFile sized(String name, long size) {+ return new MockMultipartFile("file", name, "image/jpeg", new byte[] {1}) {+ @Override+ public long getSize() {+ return size;+ }+ };+ }+@Nested@DisplayName("SessionInfo accessors")class SessionInfoAccessors {@@ -455,17 +887,17 @@ class MobileScannerServiceTest {}/**- * Reaches into the internal SessionData for a given session and forces its lastAccessTime, used- * to deterministically simulate expiry without sleeping.+ * Reaches into the internal SessionData for a given session and forces its createdAt, used to+ * deterministically simulate expiry without sleeping.*/@SuppressWarnings("unchecked")- private void forceLastAccess(String sessionId, long lastAccessTime) {+ private void forceCreatedAt(String sessionId, long createdAt) {java.util.Map<String, Object> sessions =(java.util.Map<String, Object>)ReflectionTestUtils.getField(service, "activeSessions");assertNotNull(sessions);Object sessionData = sessions.get(sessionId);assertNotNull(sessionData, "session not found: " + sessionId);- ReflectionTestUtils.setField(sessionData, "lastAccessTime", lastAccessTime);+ ReflectionTestUtils.setField(sessionData, "createdAt", createdAt);}}diff --git a/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.java b/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.javaindex e0efa53f30..5756ed5632 100644--- a/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.java+++ b/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.java@@ -215,6 +215,34 @@ class RequestUriUtilsTest {assertTrue(RequestUriUtils.isPublicAuthEndpoint("/app/api/v1/webhooks/whk_abc123", "/app"));}+ @Test+ void testIsPublicAuthEndpoint_mobileScannerPhoneCallsOnly() {+ // The phone has no credentials; everything the desktop calls stays behind login.+ assertTrue(+ RequestUriUtils.isPublicAuthEndpoint(+ "/api/v1/mobile-scanner/validate-session/abc", ""));+ assertTrue(RequestUriUtils.isPublicAuthEndpoint("/api/v1/mobile-scanner/upload/abc", ""));+ assertTrue(+ RequestUriUtils.isPublicAuthEndpoint(+ "/app/api/v1/mobile-scanner/upload/abc", "/app"));+ assertFalse(+ RequestUriUtils.isPublicAuthEndpoint(+ "/api/v1/mobile-scanner/create-session/abc", ""));+ assertFalse(RequestUriUtils.isPublicAuthEndpoint("/api/v1/mobile-scanner/files/abc", ""));+ assertFalse(+ RequestUriUtils.isPublicAuthEndpoint(+ "/api/v1/mobile-scanner/download/abc/a.jpg", ""));+ assertFalse(RequestUriUtils.isPublicAuthEndpoint("/api/v1/mobile-scanner/session/abc", ""));+ // Anything beyond a bare session id stays protected, whatever the firewall allows.+ assertFalse(+ RequestUriUtils.isPublicAuthEndpoint(+ "/api/v1/mobile-scanner/upload/abc/../../files/abc", ""));+ assertFalse(+ RequestUriUtils.isPublicAuthEndpoint(+ "/api/v1/mobile-scanner/upload/abc/extra", ""));+ assertFalse(RequestUriUtils.isPublicAuthEndpoint("/api/v1/mobile-scanner/upload/", ""));+ }+@Testvoid testIsPublicAuthEndpoint_withContextPath() {assertTrue(RequestUriUtils.isPublicAuthEndpoint("/app/login", "/app"));diff --git a/app/core/build.gradle b/app/core/build.gradleindex c1f4d4c6ca..8a79cdb749 100644--- a/app/core/build.gradle+++ b/app/core/build.gradle@@ -20,6 +20,7 @@ dependencies {implementation project(':common')implementation 'org.springframework.boot:spring-boot-starter-jetty'+ implementation 'org.eclipse.jetty.compression:jetty-compression-server'implementation 'org.eclipse.jetty.http2:jetty-http2-server'implementation 'org.eclipse.jetty:jetty-alpn-java-server'implementation ('org.telegram:telegrambots:6.9.7.1') {diff --git a/app/core/src/main/java/stirling/software/SPDF/config/JettyCompressionConfig.java b/app/core/src/main/java/stirling/software/SPDF/config/JettyCompressionConfig.javanew file mode 100644index 0000000000..b36ac4295f--- /dev/null+++ b/app/core/src/main/java/stirling/software/SPDF/config/JettyCompressionConfig.java@@ -0,0 +1,64 @@+package stirling.software.SPDF.config;++import java.util.List;++import org.eclipse.jetty.compression.server.CompressionConfig;+import org.eclipse.jetty.compression.server.CompressionHandler;+import org.eclipse.jetty.http.pathmap.PathMappings;+import org.eclipse.jetty.http.pathmap.PathSpec;+import org.springframework.boot.jetty.JettyServerCustomizer;+import org.springframework.context.annotation.Bean;+import org.springframework.context.annotation.Configuration;++/**+ * Keeps {@code server.compression} to response compression only.+ *+ * <p>On Jetty, Spring Boot's {@link CompressionHandler} leaves its request-decompression rules+ * empty, so every compressed request body is inflated before any size limit sees it: a few MB on+ * the wire can become gigabytes. No Stirling-PDF client compresses request bodies.+ */+@Configuration+public class JettyCompressionConfig {++ @Bean+ public JettyServerCustomizer disableRequestDecompression() {+ return server -> server.getDescendants(CompressionHandler.class).forEach(this::apply);+ }++ @SuppressWarnings("unchecked")+ private void apply(CompressionHandler handler) {+ PathMappings<CompressionConfig> mappings = handler.getBean(PathMappings.class);+ if (mappings == null) {+ // Fail closed: without the mappings the configs cannot all be found and rewritten.+ throw new IllegalStateException(+ "Cannot disable request decompression: CompressionHandler no longer exposes"+ + " its path mappings");+ }+ if (mappings.isEmpty()) {+ // An empty handler installs Jetty's defaults on start, which decompress POST bodies.+ handler.putConfiguration(+ "/",+ CompressionConfig.builder().defaults().decompressExcludePath("/*").build());+ return;+ }+ for (PathSpec pathSpec : List.copyOf(mappings.keySet())) {+ handler.putConfiguration(+ pathSpec, withoutRequestDecompression(handler.getConfiguration(pathSpec)));+ }+ }++ // CompressionConfig is immutable, so the response-side settings are copied into a new one.+ static CompressionConfig withoutRequestDecompression(CompressionConfig config) {+ CompressionConfig.Builder builder = CompressionConfig.builder();+ config.getCompressIncludeEncodings().forEach(builder::compressIncludeEncoding);+ config.getCompressExcludeEncodings().forEach(builder::compressExcludeEncoding);+ config.getCompressIncludeMethods().forEach(builder::compressIncludeMethod);+ config.getCompressExcludeMethods().forEach(builder::compressExcludeMethod);+ config.getCompressIncludeMimeTypes().forEach(builder::compressIncludeMimeType);+ config.getCompressExcludeMimeTypes().forEach(builder::compressExcludeMimeType);+ config.getCompressIncludePaths().forEach(builder::compressIncludePath);+ config.getCompressExcludePaths().forEach(builder::compressExcludePath);+ builder.compressPreferredEncodings(config.getCompressPreferredEncodings());+ return builder.decompressExcludePath("/*").build();+ }+}diff --git a/app/core/src/main/java/stirling/software/SPDF/config/MobileScannerUploadFilter.java b/app/core/src/main/java/stirling/software/SPDF/config/MobileScannerUploadFilter.javanew file mode 100644index 0000000000..29173ac9a4--- /dev/null+++ b/app/core/src/main/java/stirling/software/SPDF/config/MobileScannerUploadFilter.java@@ -0,0 +1,81 @@+package stirling.software.SPDF.config;++import java.io.IOException;++import org.springframework.core.Ordered;+import org.springframework.core.annotation.Order;+import org.springframework.http.HttpStatus;+import org.springframework.http.MediaType;+import org.springframework.stereotype.Component;+import org.springframework.web.filter.OncePerRequestFilter;++import jakarta.servlet.FilterChain;+import jakarta.servlet.ServletException;+import jakarta.servlet.http.HttpServletRequest;+import jakarta.servlet.http.HttpServletResponse;++import lombok.RequiredArgsConstructor;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.service.MobileScannerService;+import stirling.software.common.util.RequestUriUtils;++/**+ * Rejects mobile scanner uploads before their body is read. The upload endpoint needs no login, and+ * the multipart body is written to disk before the controller runs, so an upload to an unknown+ * session or one larger than a session can hold would otherwise cost up to the global multipart+ * limit in disk space first.+ */+@Component+@Order(Ordered.HIGHEST_PRECEDENCE)+@RequiredArgsConstructor+public class MobileScannerUploadFilter extends OncePerRequestFilter {++ private static final String UPLOAD_PREFIX = "/api/v1/mobile-scanner/upload/";+ // Room for the multipart boundaries and part headers on top of the file bytes.+ private static final long MULTIPART_OVERHEAD_BYTES = 1024 * 1024;++ private final MobileScannerService mobileScannerService;+ private final ApplicationProperties applicationProperties;++ @Override+ protected boolean shouldNotFilter(HttpServletRequest request) {+ ApplicationProperties.System system = applicationProperties.getSystem();+ // When the feature is off the controller answers 403 without touching the session.+ return !"POST".equals(request.getMethod())+ || !(system.isEnableMobileScanner() || system.isEnableMobileSignature())+ || !RequestUriUtils.normalizeUri(request.getContextPath(), request.getRequestURI())+ .startsWith(UPLOAD_PREFIX);+ }++ @Override+ protected void doFilterInternal(+ HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)+ throws ServletException, IOException {+ String path =+ RequestUriUtils.normalizeUri(request.getContextPath(), request.getRequestURI());+ String sessionId = path.substring(UPLOAD_PREFIX.length());+ long remaining = mobileScannerService.remainingSessionBytes(sessionId);+ if (remaining < 0) {+ reject(response, HttpStatus.BAD_REQUEST, "Session not found or expired");+ return;+ }+ long length = request.getContentLengthLong();+ if (length < 0) {+ reject(response, HttpStatus.LENGTH_REQUIRED, "Content-Length is required");+ return;+ }+ if (length > remaining + MULTIPART_OVERHEAD_BYTES) {+ reject(response, HttpStatus.CONTENT_TOO_LARGE, "Session upload limit reached");+ return;+ }+ filterChain.doFilter(request, response);+ }++ private static void reject(HttpServletResponse response, HttpStatus status, String message)+ throws IOException {+ response.setStatus(status.value());+ response.setContentType(MediaType.APPLICATION_JSON_VALUE);+ response.getWriter().write("{\"error\":\"" + message + "\"}");+ }+}diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/MobileScannerController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/MobileScannerController.javaindex 0bfa6c0337..7085838455 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/MobileScannerController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/MobileScannerController.java@@ -1,16 +1,20 @@package stirling.software.SPDF.controller.api.misc;+import java.io.FilterInputStream;import java.io.IOException;-import java.nio.file.Files;+import java.io.InputStream;+import java.io.OutputStream;import java.nio.file.Path;import java.util.HashMap;import java.util.List;import java.util.Map;+import org.springframework.core.io.FileSystemResource;import org.springframework.core.io.Resource;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;+import org.springframework.http.MediaTypeFactory;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;@@ -34,6 +38,7 @@ import lombok.extern.slf4j.Slf4j;import stirling.software.common.model.ApplicationProperties;import stirling.software.common.service.MobileScannerService;import stirling.software.common.service.MobileScannerService.FileMetadata;+import stirling.software.common.service.MobileScannerService.UploadLimitException;/*** REST controller for mobile scanner functionality. Allows mobile devices to upload scanned images@@ -99,6 +104,7 @@ public class MobileScannerController {description = "Session created successfully",content = @Content(schema = @Schema(implementation = SessionInfoResponse.class)))@ApiResponse(responseCode = "400", description = "Invalid session ID")+ @ApiResponse(responseCode = "503", description = "Too many active sessions")@ApiResponse(responseCode = "403", description = "Mobile scanner feature not enabled")public ResponseEntity<Map<String, Object>> createSession(@Parameter(description = "Session ID for QR code", required = true) @PathVariable@@ -122,6 +128,8 @@ public class MobileScannerController {return ResponseEntity.ok(response);+ } catch (UploadLimitException e) {+ return limitExceeded(e);} catch (IllegalArgumentException e) {log.warn("Invalid session creation request: {}", e.getMessage());return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));@@ -186,7 +194,11 @@ public class MobileScannerController {responseCode = "200",description = "Files uploaded successfully",content = @Content(schema = @Schema(implementation = UploadResponse.class)))- @ApiResponse(responseCode = "400", description = "Invalid session ID or files")+ @ApiResponse(+ responseCode = "400",+ description = "Unknown or expired session, invalid session ID or no files")+ @ApiResponse(responseCode = "413", description = "File or session size limit exceeded")+ @ApiResponse(responseCode = "503", description = "Server-wide upload capacity reached")@ApiResponse(responseCode = "403", description = "Mobile scanner feature not enabled")@ApiResponse(responseCode = "500", description = "Upload failed")public ResponseEntity<Map<String, Object>> uploadFiles(@@ -216,6 +228,8 @@ public class MobileScannerController {log.info("Mobile scanner upload: session={}, files={}", sessionId, files.size());return ResponseEntity.ok(response);+ } catch (UploadLimitException e) {+ return limitExceeded(e);} catch (IllegalArgumentException e) {log.warn("Invalid mobile scanner upload request: {}", e.getMessage());return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));@@ -286,24 +300,20 @@ public class MobileScannerController {}try {+ // From the name, not the file: nothing after getFile's claim may throw.+ MediaType contentType =+ MediaTypeFactory.getMediaType(filename)+ .orElse(MediaType.APPLICATION_OCTET_STREAM);Path filePath = mobileScannerService.getFile(sessionId, filename);- // Read file into memory first, so we can delete it before sending- byte[] fileBytes = Files.readAllBytes(filePath);-- String contentType = Files.probeContentType(filePath);- if (contentType == null) {- contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;- }-- // Delete file immediately after reading into memory (server-side cleanup)- mobileScannerService.deleteFileAfterDownload(sessionId, filename);-- // Serve from memory- Resource resource = new org.springframework.core.io.ByteArrayResource(fileBytes);+ Resource resource =+ new DeleteAfterReadResource(+ filePath,+ () -> mobileScannerService.deleteFileAfterDownload(sessionId, filename),+ () -> mobileScannerService.releaseDownloadClaim(sessionId, filename));return ResponseEntity.ok()- .contentType(MediaType.parseMediaType(contentType))+ .contentType(contentType).header(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=\"" + filename + "\"")@@ -342,6 +352,80 @@ public class MobileScannerController {Map.of("success", true, "sessionId", sessionId, "message", "Session deleted"));}+ private ResponseEntity<Map<String, Object>> limitExceeded(UploadLimitException e) {+ log.warn("Mobile scanner storage limit: {}", e.getMessage());+ HttpStatus status =+ e.isServerCapacity()+ ? HttpStatus.SERVICE_UNAVAILABLE+ : HttpStatus.CONTENT_TOO_LARGE;+ return ResponseEntity.status(status).body(Map.of("error", e.getMessage()));+ }++ /**+ * Streams a file from disk, so an unread download does not pin it on the heap. When the stream+ * closes it runs {@code onFullRead} if the whole file was read, otherwise {@code+ * onPartialRead}, so a failed or ranged download leaves the file to be fetched again.+ */+ private static final class DeleteAfterReadResource extends FileSystemResource {+ private final Runnable onFullRead;+ private final Runnable onPartialRead;++ DeleteAfterReadResource(Path path, Runnable onFullRead, Runnable onPartialRead) {+ super(path);+ this.onFullRead = onFullRead;+ this.onPartialRead = onPartialRead;+ }++ @Override+ public InputStream getInputStream() throws IOException {+ return new FilterInputStream(super.getInputStream()) {+ private boolean reachedEnd;+ private boolean closed;++ @Override+ public int read() throws IOException {+ int b = super.read();+ reachedEnd |= b == -1;+ return b;+ }++ @Override+ public int read(byte[] buffer, int offset, int length) throws IOException {+ int n = super.read(buffer, offset, length);+ reachedEnd |= n == -1;+ return n;+ }++ @Override+ public long transferTo(OutputStream out) throws IOException {+ // Copies through read() so reaching the end is seen; delegating would bypass+ // it.+ long total = 0;+ byte[] buffer = new byte[8192];+ int n;+ while ((n = read(buffer, 0, buffer.length)) != -1) {+ out.write(buffer, 0, n);+ total += n;+ }+ return total;+ }++ @Override+ public void close() throws IOException {+ if (closed) {+ return;+ }+ closed = true;+ try {+ super.close();+ } finally {+ (reachedEnd ? onFullRead : onPartialRead).run();+ }+ }+ };+ }+ }+// Response schemas for OpenAPI documentationprivate static class SessionInfoResponse {public boolean success;diff --git a/app/core/src/main/resources/application.properties b/app/core/src/main/resources/application.propertiesindex 348ef4a506..2b464633c7 100644--- a/app/core/src/main/resources/application.properties+++ b/app/core/src/main/resources/application.properties@@ -29,7 +29,7 @@ spring.threads.virtual.enabled=true# Spring Security re-evaluates authorization after the response is already committed.spring.security.filter.dispatcher-types=REQUEST,ERROR-# Response compression+# Response compression; JettyCompressionConfig stops it also inflating request bodiesserver.compression.enabled=trueserver.compression.min-response-size=1024server.compression.mime-types=application/json,application/xml,text/html,text/plain,text/css,application/javascript,image/svg+xml,application/x-font-ttf,font/opentype,application/vnd.ms-fontobject,font/woff,font/woff2,application/font-woff,application/font-woff2,application/wasmdiff --git a/app/core/src/test/java/stirling/software/SPDF/config/JettyCompressionConfigTest.java b/app/core/src/test/java/stirling/software/SPDF/config/JettyCompressionConfigTest.javanew file mode 100644index 0000000000..341037a989--- /dev/null+++ b/app/core/src/test/java/stirling/software/SPDF/config/JettyCompressionConfigTest.java@@ -0,0 +1,169 @@+package stirling.software.SPDF.config;++import static org.assertj.core.api.Assertions.assertThat;++import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.io.OutputStream;+import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.net.http.HttpResponse;+import java.util.List;+import java.util.Optional;+import java.util.zip.GZIPOutputStream;++import org.eclipse.jetty.compression.server.CompressionConfig;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Test;+import org.springframework.boot.jetty.servlet.JettyServletWebServerFactory;+import org.springframework.boot.web.server.Compression;+import org.springframework.boot.web.server.WebServer;++import jakarta.servlet.http.HttpServlet;+import jakarta.servlet.http.HttpServletRequest;+import jakarta.servlet.http.HttpServletResponse;++/** Boots a real Jetty with {@code server.compression} on, as the application does. */+class JettyCompressionConfigTest {++ private static final int INFLATED_SIZE = 1024 * 1024;++ private final HttpClient client = HttpClient.newHttpClient();+ private WebServer server;++ @AfterEach+ void stopServer() {+ if (server != null) {+ server.stop();+ }+ client.close();+ }++ @Test+ void gzipRequestBodyReachesServletCompressed() throws Exception {+ start(true);+ byte[] body = gzip(new byte[INFLATED_SIZE]);++ assertThat(postGzip(body)).isEqualTo(String.valueOf(body.length));+ }++ @Test+ void withoutCustomizerJettyInflatesRequestBody() throws Exception {+ // Guards the test above against passing vacuously if Jetty stops inflating by default.+ start(false);++ assertThat(postGzip(gzip(new byte[INFLATED_SIZE])))+ .isEqualTo(String.valueOf(INFLATED_SIZE));+ }++ @Test+ void responsesAreStillCompressed() throws Exception {+ start(true);++ assertThat(getEncoding("text/plain")).hasValue("gzip");+ }++ @Test+ void responsesOutsideConfiguredMimeTypesStayUncompressed() throws Exception {+ start(true);++ assertThat(getEncoding("image/jpeg")).isEmpty();+ }++ @Test+ void rewrittenConfigKeepsResponseSettingsAndExcludesAllPathsFromDecompression() {+ CompressionConfig original =+ CompressionConfig.builder()+ .compressIncludeMimeType("text/plain")+ .compressExcludeMimeType("image/jpeg")+ .compressIncludeMethod("GET")+ .compressExcludePath("/skip/*")+ .compressPreferredEncodings(List.of("gzip"))+ .build();++ CompressionConfig rewritten = JettyCompressionConfig.withoutRequestDecompression(original);++ assertThat(rewritten.getCompressIncludeMimeTypes())+ .isEqualTo(original.getCompressIncludeMimeTypes());+ assertThat(rewritten.getCompressExcludeMimeTypes())+ .isEqualTo(original.getCompressExcludeMimeTypes());+ assertThat(rewritten.getCompressIncludeMethods())+ .isEqualTo(original.getCompressIncludeMethods());+ assertThat(rewritten.getCompressExcludePaths())+ .isEqualTo(original.getCompressExcludePaths());+ assertThat(rewritten.getCompressPreferredEncodings()).containsExactly("gzip");+ assertThat(rewritten.getDecompressExcludePaths()).containsExactly("/*");+ }++ private Optional<String> getEncoding(String contentType)+ throws IOException, InterruptedException {+ HttpResponse<byte[]> response =+ client.send(+ HttpRequest.newBuilder(URI.create(uri() + "?type=" + contentType))+ .header("Accept-Encoding", "gzip")+ .GET()+ .build(),+ HttpResponse.BodyHandlers.ofByteArray());+ assertThat(response.statusCode()).isEqualTo(200);+ return response.headers().firstValue("Content-Encoding");+ }++ private void start(boolean withCustomizer) {+ JettyServletWebServerFactory factory = new JettyServletWebServerFactory(0);+ Compression compression = new Compression();+ compression.setEnabled(true);+ factory.setCompression(compression);+ if (withCustomizer) {+ factory.addServerCustomizers(+ new JettyCompressionConfig().disableRequestDecompression());+ }+ server =+ factory.getWebServer(+ context ->+ context.addServlet("echo", new BodyLengthServlet())+ .addMapping("/*"));+ server.start();+ }++ private String postGzip(byte[] body) throws IOException, InterruptedException {+ HttpResponse<String> response =+ client.send(+ HttpRequest.newBuilder(uri())+ .header("Content-Type", "application/octet-stream")+ .header("Content-Encoding", "gzip")+ .POST(HttpRequest.BodyPublishers.ofByteArray(body))+ .build(),+ HttpResponse.BodyHandlers.ofString());+ assertThat(response.statusCode()).isEqualTo(200);+ return response.body();+ }++ private URI uri() {+ return URI.create("http://localhost:" + server.getPort() + "/echo");+ }++ private static byte[] gzip(byte[] data) throws IOException {+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {+ gzip.write(data);+ }+ return out.toByteArray();+ }++ /** POST answers with the number of body bytes read; GET answers 8 KB of {@code ?type}. */+ private static class BodyLengthServlet extends HttpServlet {+ @Override+ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {+ long length = req.getInputStream().transferTo(OutputStream.nullOutputStream());+ resp.setContentType("text/plain");+ resp.getWriter().write(String.valueOf(length));+ }++ @Override+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {+ resp.setContentType(req.getParameter("type"));+ resp.getWriter().write("a".repeat(8192));+ }+ }+}diff --git a/app/core/src/test/java/stirling/software/SPDF/config/MobileScannerUploadFilterTest.java b/app/core/src/test/java/stirling/software/SPDF/config/MobileScannerUploadFilterTest.javanew file mode 100644index 0000000000..30ec04c55b--- /dev/null+++ b/app/core/src/test/java/stirling/software/SPDF/config/MobileScannerUploadFilterTest.java@@ -0,0 +1,119 @@+package stirling.software.SPDF.config;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.springframework.mock.web.MockHttpServletRequest;+import org.springframework.mock.web.MockHttpServletResponse;++import jakarta.servlet.FilterChain;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.service.MobileScannerService;++class MobileScannerUploadFilterTest {++ private static final long ROOM = 10L * 1024 * 1024;+ private static final long OVERHEAD = 1024 * 1024;++ private final MobileScannerService service = mock(MobileScannerService.class);+ private final ApplicationProperties properties = new ApplicationProperties();+ private final FilterChain chain = mock(FilterChain.class);+ private final MobileScannerUploadFilter filter =+ new MobileScannerUploadFilter(service, properties);++ @BeforeEach+ void setUp() {+ properties.getSystem().setEnableMobileScanner(true);+ when(service.remainingSessionBytes(any())).thenReturn(-1L);+ when(service.remainingSessionBytes("live")).thenReturn(ROOM);+ }++ @Test+ void passesUploadToLiveSessionWithinLimit() throws Exception {+ MockHttpServletResponse response = run(upload("live", 1024));++ assertEquals(200, response.getStatus());+ verify(chain).doFilter(any(), any());+ }++ @Test+ void rejectsUnknownSessionBeforeReadingBody() throws Exception {+ MockHttpServletResponse response = run(upload("unknown", 1024));++ assertEquals(400, response.getStatus());+ verify(chain, never()).doFilter(any(), any());+ }++ @Test+ void rejectsBodyLargerThanTheSessionsRemainingRoom() throws Exception {+ MockHttpServletResponse response = run(upload("live", ROOM + OVERHEAD + 1));++ assertEquals(413, response.getStatus());+ verify(chain, never()).doFilter(any(), any());+ }++ @Test+ void allowsMultipartOverheadOnTopOfTheRemainingRoom() throws Exception {+ assertEquals(200, run(upload("live", ROOM + OVERHEAD)).getStatus());+ }++ @Test+ void rejectsBodyWithoutContentLength() throws Exception {+ MockHttpServletResponse response = run(upload("live", -1));++ assertEquals(411, response.getStatus());+ verify(chain, never()).doFilter(any(), any());+ }++ @Test+ void handlesContextPath() throws Exception {+ MockHttpServletRequest request = upload("unknown", 1024);+ request.setContextPath("/app");+ request.setRequestURI("/app/api/v1/mobile-scanner/upload/unknown");++ assertEquals(400, run(request).getStatus());+ }++ @Test+ void ignoresOtherRequests() throws Exception {+ MockHttpServletRequest get =+ new MockHttpServletRequest("GET", "/api/v1/mobile-scanner/upload/unknown");+ MockHttpServletRequest other =+ new MockHttpServletRequest("POST", "/api/v1/mobile-scanner/create-session/x");++ assertEquals(200, run(get).getStatus());+ assertEquals(200, run(other).getStatus());+ }++ @Test+ void leavesDisabledFeatureToTheController() throws Exception {+ properties.getSystem().setEnableMobileScanner(false);+ properties.getSystem().setEnableMobileSignature(false);++ assertEquals(200, run(upload("unknown", 1024)).getStatus());+ verify(chain).doFilter(any(), any());+ }++ private static MockHttpServletRequest upload(String sessionId, long contentLength) {+ // The mock derives its length from its content, so large bodies are only declared.+ return new MockHttpServletRequest("POST", "/api/v1/mobile-scanner/upload/" + sessionId) {+ @Override+ public long getContentLengthLong() {+ return contentLength;+ }+ };+ }++ private MockHttpServletResponse run(MockHttpServletRequest request) throws Exception {+ MockHttpServletResponse response = new MockHttpServletResponse();+ filter.doFilter(request, response, chain);+ return response;+ }+}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/MobileScannerControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/MobileScannerControllerTest.javaindex dc9c9538cd..1abb53b6d2 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/MobileScannerControllerTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/MobileScannerControllerTest.java@@ -6,6 +6,9 @@ import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.*;import java.io.IOException;+import java.io.InputStream;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.Collections;import java.util.List;import java.util.Map;@@ -13,9 +16,12 @@ import java.util.Map;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;+import org.junit.jupiter.api.io.TempDir;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.core.io.Resource;import org.springframework.http.HttpStatus;+import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.mock.web.MockMultipartFile;import org.springframework.web.multipart.MultipartFile;@@ -24,6 +30,7 @@ import stirling.software.common.model.ApplicationProperties;import stirling.software.common.service.MobileScannerService;import stirling.software.common.service.MobileScannerService.FileMetadata;import stirling.software.common.service.MobileScannerService.SessionInfo;+import stirling.software.common.service.MobileScannerService.UploadLimitException;@ExtendWith(MockitoExtension.class)class MobileScannerControllerTest {@@ -199,6 +206,128 @@ class MobileScannerControllerTest {assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode());}+ @Test+ void uploadFiles_whenFileTooLarge_returns413() throws Exception {+ enableMobileScanner();+ doThrow(new UploadLimitException("too big", false))+ .when(mobileScannerService)+ .uploadFiles(eq("test-session"), any());++ ResponseEntity<Map<String, Object>> response =+ controller.uploadFiles("test-session", List.of(scan()));++ assertEquals(HttpStatus.CONTENT_TOO_LARGE, response.getStatusCode());+ }++ @Test+ void uploadFiles_whenServerFull_returns503() throws Exception {+ enableMobileScanner();+ doThrow(new UploadLimitException("full", true))+ .when(mobileScannerService)+ .uploadFiles(eq("test-session"), any());++ ResponseEntity<Map<String, Object>> response =+ controller.uploadFiles("test-session", List.of(scan()));++ assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode());+ }++ @Test+ void createSession_whenSessionCapReached_returns503() {+ enableMobileScanner();+ when(mobileScannerService.createSession("test-session"))+ .thenThrow(new UploadLimitException("too many", true));++ ResponseEntity<Map<String, Object>> response = controller.createSession("test-session");++ assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode());+ }++ // --- downloadFile tests ---++ @Test+ void downloadFile_streamsFileAndDeletesItOnlyAfterStreamCloses(@TempDir Path dir)+ throws Exception {+ enableMobileScanner();+ Path file = Files.write(dir.resolve("scan.jpg"), new byte[] {1, 2, 3});+ when(mobileScannerService.getFile("test-session", "scan.jpg")).thenReturn(file);++ ResponseEntity<Resource> response = controller.downloadFile("test-session", "scan.jpg");++ assertEquals(HttpStatus.OK, response.getStatusCode());+ assertEquals(3L, response.getBody().contentLength());+ verify(mobileScannerService, never()).deleteFileAfterDownload(any(), any());+ try (InputStream in = response.getBody().getInputStream()) {+ assertArrayEquals(new byte[] {1, 2, 3}, in.readAllBytes());+ verify(mobileScannerService, never()).deleteFileAfterDownload(any(), any());+ in.close();+ }+ verify(mobileScannerService, times(1)).deleteFileAfterDownload("test-session", "scan.jpg");+ }++ @Test+ void downloadFile_partialReadReleasesClaimInsteadOfDeleting(@TempDir Path dir)+ throws Exception {+ enableMobileScanner();+ Path file = Files.write(dir.resolve("scan.jpg"), new byte[] {1, 2, 3});+ when(mobileScannerService.getFile("test-session", "scan.jpg")).thenReturn(file);++ ResponseEntity<Resource> response = controller.downloadFile("test-session", "scan.jpg");+ try (InputStream in = response.getBody().getInputStream()) {+ in.read();+ }++ verify(mobileScannerService).releaseDownloadClaim("test-session", "scan.jpg");+ verify(mobileScannerService, never()).deleteFileAfterDownload(any(), any());+ }++ @Test+ void downloadFile_transferToCountsAsFullRead(@TempDir Path dir) throws Exception {+ enableMobileScanner();+ Path file = Files.write(dir.resolve("scan.jpg"), new byte[] {1, 2, 3});+ when(mobileScannerService.getFile("test-session", "scan.jpg")).thenReturn(file);++ ResponseEntity<Resource> response = controller.downloadFile("test-session", "scan.jpg");+ try (InputStream in = response.getBody().getInputStream()) {+ in.transferTo(java.io.OutputStream.nullOutputStream());+ }++ verify(mobileScannerService).deleteFileAfterDownload("test-session", "scan.jpg");+ verify(mobileScannerService, never()).releaseDownloadClaim(any(), any());+ }++ @Test+ void downloadFile_contentTypeComesFromFilename(@TempDir Path dir) throws Exception {+ enableMobileScanner();+ Path jpg = Files.write(dir.resolve("scan.jpg"), new byte[] {1});+ Path unknown = Files.write(dir.resolve("scan.zzz"), new byte[] {1});+ when(mobileScannerService.getFile("test-session", "scan.jpg")).thenReturn(jpg);+ when(mobileScannerService.getFile("test-session", "scan.zzz")).thenReturn(unknown);++ assertEquals(+ MediaType.IMAGE_JPEG,+ controller.downloadFile("test-session", "scan.jpg").getHeaders().getContentType());+ assertEquals(+ MediaType.APPLICATION_OCTET_STREAM,+ controller.downloadFile("test-session", "scan.zzz").getHeaders().getContentType());+ }++ @Test+ void downloadFile_whenMissing_returns404() throws Exception {+ enableMobileScanner();+ when(mobileScannerService.getFile("test-session", "gone.jpg"))+ .thenThrow(new IOException("File not found"));++ ResponseEntity<Resource> response = controller.downloadFile("test-session", "gone.jpg");++ assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());+ verify(mobileScannerService, never()).deleteFileAfterDownload(any(), any());+ }++ private static MultipartFile scan() {+ return new MockMultipartFile("files", "scan.jpg", "image/jpeg", new byte[] {1, 2, 3});+ }+// --- getSessionFiles tests ---@Testdiff --git a/frontend/src/editor/core/hooks/useMobileTransferSession.ts b/frontend/src/editor/core/hooks/useMobileTransferSession.tsindex bc0f876fa2..7d6cd88fd4 100644--- a/frontend/src/editor/core/hooks/useMobileTransferSession.ts+++ b/frontend/src/editor/core/hooks/useMobileTransferSession.ts@@ -87,6 +87,9 @@ export function useMobileTransferSession({const pollIntervalRef = useRef<number | null>(null);const timerIntervalRef = useRef<number | null>(null);const processedFiles = useRef<Set<string>>(new Set());+ // Files are served once, so an overlapping poll would get a 404. Keyed by+ // session so a poll still running for a replaced session doesn't block the new one.+ const pollInFlight = useRef<string | null>(null);// The QR-code URL the phone opens. It must land on the public route under// the app's base path, otherwise the phone hits the auth-gated catch-all@@ -136,11 +139,14 @@ export function useMobileTransferSession({}, [createSession]);const pollForFiles = useCallback(async () => {- if (!active) return;+ if (!active || pollInFlight.current === sessionId) return;+ pollInFlight.current = sessionId;try {+ // Timeouts keep one stalled request from stopping polling for good.const response = await apiClient.get(`/api/v1/mobile-scanner/files/${sessionId}`,+ { timeout: 30_000 },);if (!response.status || response.status !== 200) {throw new Error("Failed to check for files");@@ -158,7 +164,7 @@ export function useMobileTransferSession({try {const downloadResponse = await apiClient.get(`/api/v1/mobile-scanner/download/${sessionId}/${fileMetadata.filename}`,- { responseType: "blob" },+ { responseType: "blob", timeout: 300_000 },);if (downloadResponse.status === 200) {@@ -179,20 +185,11 @@ export function useMobileTransferSession({);}}-- // Delete the entire session immediately after downloading, so uploads- // sit on the server only for the seconds between polls.- try {- await apiClient.delete(`/api/v1/mobile-scanner/session/${sessionId}`);- } catch (cleanupErr) {- console.warn(- "[useMobileTransferSession] post-download cleanup failed:",- cleanupErr,- );- }} catch (err) {console.error("[useMobileTransferSession] polling failed:", err);setError(pollingErrorMessage);+ } finally {+ if (pollInFlight.current === sessionId) pollInFlight.current = null;}}, [active, sessionId, onFileReceived, pollingErrorMessage]);diff --git a/testing/cucumber/features/mobile_scanner.feature b/testing/cucumber/features/mobile_scanner.featureindex 96cfde56fd..0590d1a71c 100644--- a/testing/cucumber/features/mobile_scanner.feature+++ b/testing/cucumber/features/mobile_scanner.feature@@ -3,26 +3,30 @@ Feature: Mobile Scanner Session APITests for the mobile scanner REST API, which manages short-lived uploadsessions used by mobile scanning clients.- All endpoints are PUBLIC (no authentication required). Sessions are- identified by a caller-supplied session ID string.+ The logged-in desktop creates, lists, downloads and deletes sessions. Only+ validate-session and upload are public, for the phone that scans the QR code.+ Uploads go only to sessions the desktop created.Session IDs must match [a-zA-Z0-9-]+ (alphanumeric and hyphens only –underscores are rejected with 400).+ Background:+ Given I am logged in as admin+# =========================================================================# SESSION LIFECYCLE# =========================================================================@positiveScenario: Create a new mobile scanner session- When I send a POST request to "/api/v1/mobile-scanner/create-session/bdd-test-session-001" with no authentication+ When I send a POST request to "/api/v1/mobile-scanner/create-session/bdd-test-session-001" with JWT authenticationThen the response status code should be 200And the response JSON field "success" should be trueAnd the response JSON field "sessionId" should not be empty@positive- Scenario: Validate an existing mobile scanner session- When I send a POST request to "/api/v1/mobile-scanner/create-session/bdd-test-session-002" with no authentication+ Scenario: Validate an existing mobile scanner session without authentication+ When I send a POST request to "/api/v1/mobile-scanner/create-session/bdd-test-session-002" with JWT authenticationThen the response status code should be 200When I send a GET request to "/api/v1/mobile-scanner/validate-session/bdd-test-session-002" with no authenticationThen the response status code should be 200@@ -30,39 +34,58 @@ Feature: Mobile Scanner Session API@positiveScenario: List files in an existing session returns empty list initially- When I send a POST request to "/api/v1/mobile-scanner/create-session/bdd-test-session-003" with no authentication+ When I send a POST request to "/api/v1/mobile-scanner/create-session/bdd-test-session-003" with JWT authenticationThen the response status code should be 200- When I send a GET request to "/api/v1/mobile-scanner/files/bdd-test-session-003" with no authentication+ When I send a GET request to "/api/v1/mobile-scanner/files/bdd-test-session-003" with JWT authenticationThen the response status code should be 200@positiveScenario: Delete an existing mobile scanner session- When I send a POST request to "/api/v1/mobile-scanner/create-session/bdd-test-session-004" with no authentication+ When I send a POST request to "/api/v1/mobile-scanner/create-session/bdd-test-session-004" with JWT authenticationThen the response status code should be 200- When I send a DELETE request to "/api/v1/mobile-scanner/session/bdd-test-session-004" with no authentication+ When I send a DELETE request to "/api/v1/mobile-scanner/session/bdd-test-session-004" with JWT authenticationThen the response status code should be 200And the response JSON field "success" should be true@positiveScenario: Full session lifecycle – create, validate, list files, delete- When I send a POST request to "/api/v1/mobile-scanner/create-session/bdd-test-session-full" with no authentication+ When I send a POST request to "/api/v1/mobile-scanner/create-session/bdd-test-session-full" with JWT authenticationThen the response status code should be 200And the response JSON field "sessionId" should not be emptyWhen I send a GET request to "/api/v1/mobile-scanner/validate-session/bdd-test-session-full" with no authenticationThen the response status code should be 200And the response JSON field "valid" should be true- When I send a GET request to "/api/v1/mobile-scanner/files/bdd-test-session-full" with no authentication+ When I send a GET request to "/api/v1/mobile-scanner/files/bdd-test-session-full" with JWT authenticationThen the response status code should be 200- When I send a DELETE request to "/api/v1/mobile-scanner/session/bdd-test-session-full" with no authentication+ When I send a DELETE request to "/api/v1/mobile-scanner/session/bdd-test-session-full" with JWT authenticationThen the response status code should be 200+ # =========================================================================+ # AUTHENTICATION+ # =========================================================================++ @negative+ Scenario: Creating a session requires authentication+ When I send a POST request to "/api/v1/mobile-scanner/create-session/bdd-test-session-anon" with no authentication+ Then the response status code should be 401++ @negative+ Scenario: Listing files requires authentication+ When I send a GET request to "/api/v1/mobile-scanner/files/bdd-test-session-anon" with no authentication+ Then the response status code should be 401++ @negative+ Scenario: Deleting a session requires authentication+ When I send a DELETE request to "/api/v1/mobile-scanner/session/bdd-test-session-anon" with no authentication+ Then the response status code should be 401+# =========================================================================# EDGE CASES# =========================================================================@negativeScenario: Session ID with underscores is rejected as invalid format- When I send a POST request to "/api/v1/mobile-scanner/create-session/invalid_underscore_id" with no authentication+ When I send a POST request to "/api/v1/mobile-scanner/create-session/invalid_underscore_id" with JWT authenticationThen the response status code should be 400@negative@@ -70,12 +93,17 @@ Feature: Mobile Scanner Session APIWhen I send a GET request to "/api/v1/mobile-scanner/validate-session/nonexistent-session-xyz" with no authenticationThen the response status code should be one of "200, 404"+ @negative+ Scenario: Uploading to a non-existent session is rejected+ When I send a POST request to "/api/v1/mobile-scanner/upload/nonexistent-session-xyz" with no authentication+ Then the response status code should be 400+@negativeScenario: List files for a non-existent session returns 404 or empty- When I send a GET request to "/api/v1/mobile-scanner/files/nonexistent-session-abc" with no authentication+ When I send a GET request to "/api/v1/mobile-scanner/files/nonexistent-session-abc" with JWT authenticationThen the response status code should be one of "200, 404"@negativeScenario: Delete a non-existent session returns 404 or success- When I send a DELETE request to "/api/v1/mobile-scanner/session/nonexistent-session-xyz" with no authentication+ When I send a DELETE request to "/api/v1/mobile-scanner/session/nonexistent-session-xyz" with JWT authenticationThen the response status code should be one of "200, 404"