From dc33187af7b52043c07bbae02ef77680c765d9a9 Mon Sep 17 00:00:00 2001 From: guqing Date: Wed, 18 Sep 2024 16:13:31 +0800 Subject: [PATCH] fix: correct file mime type validation parameter to restore functionality --- .../LocalAttachmentUploadHandler.java | 33 +++++++++++-------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/application/src/main/java/run/halo/app/core/extension/attachment/endpoint/LocalAttachmentUploadHandler.java b/application/src/main/java/run/halo/app/core/extension/attachment/endpoint/LocalAttachmentUploadHandler.java index b0db21fc81..c3bbbfdcc1 100644 --- a/application/src/main/java/run/halo/app/core/extension/attachment/endpoint/LocalAttachmentUploadHandler.java +++ b/application/src/main/java/run/halo/app/core/extension/attachment/endpoint/LocalAttachmentUploadHandler.java @@ -6,6 +6,7 @@ import static run.halo.app.infra.utils.FileUtils.deleteFileSilently; import java.io.IOException; +import java.io.InputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.FileAlreadyExistsException; @@ -25,6 +26,7 @@ import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.http.MediaType; import org.springframework.http.codec.multipart.FilePart; +import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; @@ -155,19 +157,14 @@ private Mono validateFile(FilePart file, PolicySetting setting) { var typeValidator = file.content() .next() .handle((dataBuffer, sink) -> { - var mimeType = "Unknown"; - try { - mimeType = FileTypeDetectUtils.detectMimeType(dataBuffer.asInputStream()); - var isAllow = setting.getAllowedFileTypes() - .stream() - .map(FileCategoryMatcher::of) - .anyMatch(matcher -> matcher.match(file.filename())); - if (isAllow) { - sink.next(dataBuffer); - return; - } - } catch (IOException e) { - log.warn("Failed to detect file type", e); + var mimeType = detectMimeType(dataBuffer.asInputStream()); + var isAllow = setting.getAllowedFileTypes() + .stream() + .map(FileCategoryMatcher::of) + .anyMatch(matcher -> matcher.match(mimeType)); + if (isAllow) { + sink.next(dataBuffer); + return; } sink.error(new FileTypeNotAllowedException("File type is not allowed", "problemDetail.attachment.upload.fileTypeNotSupported", @@ -179,6 +176,16 @@ private Mono validateFile(FilePart file, PolicySetting setting) { return Mono.when(validations); } + @NonNull + private String detectMimeType(InputStream inputStream) { + try { + return FileTypeDetectUtils.detectMimeType(inputStream); + } catch (IOException e) { + log.warn("Failed to detect file type", e); + return "Unknown"; + } + } + @Override public Mono delete(DeleteContext deleteContext) { return Mono.just(deleteContext)