fix: correct file mime type validation parameter to restore functionality (#6673)

#### What type of PR is this?
/kind bug
/area core
/milestone 2.20.x

#### What this PR does / why we need it:
修复文件上传时类型校验失效的问题

此问题由 #6390 导致

#### Does this PR introduce a user-facing change?
```release-note
修复文件上传时类型校验失效的问题
```
pull/6675/head^2
guqing 2024-09-25 10:59:25 +08:00 committed by GitHub
parent 86b95ccfd0
commit f6409a0cb0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 20 additions and 13 deletions

View File

@ -6,6 +6,7 @@ import static run.halo.app.infra.utils.FileUtils.checkDirectoryTraversal;
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.DataBuffer;
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;
@ -156,19 +158,14 @@ class LocalAttachmentUploadHandler implements AttachmentHandler {
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",
@ -180,6 +177,16 @@ class LocalAttachmentUploadHandler implements AttachmentHandler {
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<Attachment> delete(DeleteContext deleteContext) {
return Mono.just(deleteContext)