From a001ef89e9bdf30bf04e7cd3ae4c08b28f048e21 Mon Sep 17 00:00:00 2001 From: Andrew Lalis Date: Wed, 29 Mar 2023 09:26:38 +0200 Subject: [PATCH] Added content-length protections. --- .../andrewlalis/gymboardcdn/service/UploadService.java | 10 ++++++++++ .../gymboardcdn/service/UploadServiceTest.java | 1 + 2 files changed, 11 insertions(+) diff --git a/gymboard-cdn/src/main/java/nl/andrewlalis/gymboardcdn/service/UploadService.java b/gymboard-cdn/src/main/java/nl/andrewlalis/gymboardcdn/service/UploadService.java index 4cf8225..52eac9d 100644 --- a/gymboard-cdn/src/main/java/nl/andrewlalis/gymboardcdn/service/UploadService.java +++ b/gymboard-cdn/src/main/java/nl/andrewlalis/gymboardcdn/service/UploadService.java @@ -25,6 +25,8 @@ import java.time.format.DateTimeFormatter; public class UploadService { private static final Logger log = LoggerFactory.getLogger(UploadService.class); + private static final long MAX_UPLOAD_SIZE_BYTES = (1024 * 1024 * 1024); // 1 Gb + private final StoredFileRepository storedFileRepository; private final VideoProcessingTaskRepository videoTaskRepository; private final FileService fileService; @@ -46,6 +48,14 @@ public class UploadService { */ @Transactional public FileUploadResponse processableVideoUpload(HttpServletRequest request) { + String contentLengthStr = request.getHeader("Content-Length"); + if (contentLengthStr == null || !contentLengthStr.matches("\\d+")) { + throw new ResponseStatusException(HttpStatus.LENGTH_REQUIRED); + } + long contentLength = Long.parseUnsignedLong(contentLengthStr); + if (contentLength > MAX_UPLOAD_SIZE_BYTES) { + throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE); + } Path tempFile; String filename = request.getHeader("X-Gymboard-Filename"); if (filename == null) filename = "unnamed.mp4"; diff --git a/gymboard-cdn/src/test/java/nl/andrewlalis/gymboardcdn/service/UploadServiceTest.java b/gymboard-cdn/src/test/java/nl/andrewlalis/gymboardcdn/service/UploadServiceTest.java index ad6ca88..d458290 100644 --- a/gymboard-cdn/src/test/java/nl/andrewlalis/gymboardcdn/service/UploadServiceTest.java +++ b/gymboard-cdn/src/test/java/nl/andrewlalis/gymboardcdn/service/UploadServiceTest.java @@ -44,6 +44,7 @@ public class UploadServiceTest { ); HttpServletRequest mockRequest = mock(HttpServletRequest.class); when(mockRequest.getHeader("X-Filename")).thenReturn("testing.mp4"); + when(mockRequest.getHeader("Content-Length")).thenReturn("123"); ServletInputStream mockRequestInputStream = mock(ServletInputStream.class); when(mockRequest.getInputStream()).thenReturn(mockRequestInputStream); var expectedResponse = new FileUploadResponse("abc");