@@ -255,6 +258,7 @@
org.apache.tika
tika-parsers-standard-package
+ pom
provided
@@ -481,7 +485,7 @@
${maven-surefire-plugin.version}
false
- -Xmx1024m -Dfile.encoding=UTF-8
+ @{argLine} -Xmx1024m -Dfile.encoding=UTF-8
diff --git a/src/main/java/io/github/easy4j/validation/utils/TikaUtil.java b/src/main/java/io/github/easy4j/validation/utils/TikaUtil.java
index 382c639..f3f9a3b 100644
--- a/src/main/java/io/github/easy4j/validation/utils/TikaUtil.java
+++ b/src/main/java/io/github/easy4j/validation/utils/TikaUtil.java
@@ -7,8 +7,10 @@
import org.apache.tika.mime.MimeTypes;
import java.io.File;
+import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.ByteArrayInputStream;
import java.util.Objects;
/**
@@ -23,6 +25,7 @@
*/
public final class TikaUtil {
+ private static final int MAX_BUFFERED_DETECTION_BYTES = 1024 * 1024;
private static final MimeTypes DEFAULT_MIME_TYPES = MimeTypes.getDefaultMimeTypes();
private static final Tika TIKA = new Tika();
@@ -46,6 +49,13 @@ public static MimeType detectMimeType(File file) throws IOException {
/**
* Detects the MIME type from an input stream.
*
+ * For a {@link ByteArrayInputStream}, detection inspects the full content and restores
+ * the original position without copying it. Other markable streams are buffered up to
+ * 1 MiB for complete detection and then reset; larger inputs fail with an {@link IOException}
+ * instead of being identified from an incomplete prefix. For streams without
+ * {@code mark/reset}, Tika may advance the stream. This method does not close the
+ * caller's stream.
+ *
* @param inputStream the input stream (may be {@code null})
* @return the detected MIME type, or {@code null} if the stream is {@code null}
* @throws IOException if detection fails
@@ -54,7 +64,36 @@ public static MimeType detectMimeType(InputStream inputStream) throws IOExceptio
if (Objects.isNull(inputStream)) {
return null;
}
- return toMimeType(TIKA.detect(inputStream));
+ if (inputStream instanceof ByteArrayInputStream) {
+ inputStream.mark(0);
+ try {
+ return toMimeType(TIKA.detect(nonClosing(inputStream)));
+ } finally {
+ inputStream.reset();
+ }
+ }
+ if (inputStream.markSupported()) {
+ inputStream.mark(MAX_BUFFERED_DETECTION_BYTES + 1);
+ try {
+ byte[] content = inputStream.readNBytes(MAX_BUFFERED_DETECTION_BYTES + 1);
+ if (content.length > MAX_BUFFERED_DETECTION_BYTES) {
+ throw new IOException("Markable stream exceeds 1 MiB detection limit");
+ }
+ return toMimeType(TIKA.detect(new ByteArrayInputStream(content)));
+ } finally {
+ inputStream.reset();
+ }
+ }
+ return toMimeType(TIKA.detect(nonClosing(inputStream)));
+ }
+
+ private static InputStream nonClosing(InputStream inputStream) {
+ return new FilterInputStream(inputStream) {
+ @Override
+ public void close() {
+ // The caller owns the supplied stream.
+ }
+ };
}
/**
diff --git a/src/test/java/io/github/easy4j/validation/utils/TikaUtilTest.java b/src/test/java/io/github/easy4j/validation/utils/TikaUtilTest.java
index e0dac04..1f60e9b 100644
--- a/src/test/java/io/github/easy4j/validation/utils/TikaUtilTest.java
+++ b/src/test/java/io/github/easy4j/validation/utils/TikaUtilTest.java
@@ -6,9 +6,18 @@
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
+import java.io.BufferedInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.Random;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.*;
@@ -31,10 +40,159 @@ void shouldReturnNullForNullInputStream() throws IOException {
@Test
void shouldDetectMimeTypeFromInputStream() throws IOException {
- byte[] pdfContent = "%PDF-1.7\n%%EOF".getBytes();
+ byte[] pdfContent = "%PDF-1.7\n%%EOF".getBytes(StandardCharsets.US_ASCII);
try (InputStream is = new ByteArrayInputStream(pdfContent)) {
MimeType mimeType = TikaUtil.detectMimeType(is);
- assertNotNull(mimeType);
+ assertEquals("application/pdf", mimeType.getName());
+ }
+ }
+
+ @Test
+ void shouldPreserveMarkableCallerStreamPositionAndOwnership() throws IOException {
+ byte[] pdfContent = "%PDF-1.7\n%%EOF".getBytes(StandardCharsets.US_ASCII);
+ AtomicBoolean closed = new AtomicBoolean();
+ InputStream stream = new ByteArrayInputStream(pdfContent) {
+ @Override
+ public void close() throws IOException {
+ closed.set(true);
+ super.close();
+ }
+ };
+
+ assertEquals("application/pdf", TikaUtil.detectMimeType(stream).getName());
+ assertFalse(closed.get(), "the caller owns the stream");
+ assertArrayEquals(pdfContent, stream.readAllBytes(), "detection must restore the stream position");
+ }
+
+ @Test
+ void shouldRestoreBufferedStreamWithoutReadingUnboundedContent() throws IOException {
+ byte[] content = new byte[128 * 1024];
+ byte[] header = "%PDF-1.7\n%%EOF".getBytes(StandardCharsets.US_ASCII);
+ System.arraycopy(header, 0, content, 0, header.length);
+ try (InputStream stream = new BufferedInputStream(new ByteArrayInputStream(content))) {
+ assertEquals("application/pdf", TikaUtil.detectMimeType(stream).getName());
+ assertArrayEquals(header, stream.readNBytes(header.length));
+ }
+ }
+
+ @Test
+ void shouldRecognizeJarWithManifestBeyondFirst64KiB() throws IOException {
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ try (ZipOutputStream archive = new ZipOutputStream(output)) {
+ archive.putNextEntry(new ZipEntry("payload.bin"));
+ byte[] filler = new byte[70 * 1024];
+ new Random(1234).nextBytes(filler);
+ archive.write(filler);
+ archive.closeEntry();
+ archive.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
+ archive.write("Manifest-Version: 1.0\r\n\r\n".getBytes(StandardCharsets.US_ASCII));
+ archive.closeEntry();
+ }
+ byte[] jar = output.toByteArray();
+ assertTrue(jar.length > 64 * 1024);
+ try (InputStream stream = new ByteArrayInputStream(jar)) {
+ assertEquals("application/java-archive", TikaUtil.detectMimeType(stream).getName());
+ assertArrayEquals(jar, stream.readAllBytes());
+ }
+ }
+
+ @Test
+ void shouldRecognizeOfficeContainersWithMediaBeforeContentTypes() throws IOException {
+ byte[] docx = officeArchive("word", "document.xml",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
+ "");
+ byte[] xlsx = officeArchive("xl", "workbook.xml",
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
+ "");
+
+ assertOfficeMimeType(docx, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
+ assertOfficeMimeType(xlsx, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
+ }
+
+ private static void assertOfficeMimeType(byte[] content, String expectedType) throws IOException {
+ assertTrue(content.length > 64 * 1024);
+ try (InputStream stream = new BufferedInputStream(new ByteArrayInputStream(content))) {
+ assertEquals(expectedType, TikaUtil.detectMimeType(stream).getName());
+ assertArrayEquals(content, stream.readAllBytes());
+ }
+ }
+
+ private static byte[] officeArchive(String directory, String documentName,
+ String contentType, String documentXml) throws IOException {
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ try (ZipOutputStream archive = new ZipOutputStream(output)) {
+ byte[] media = new byte[70 * 1024];
+ new Random(1234).nextBytes(media);
+ writeZipEntry(archive, directory + "/media/image1.png", media);
+ String documentPath = directory + "/" + documentName;
+ String types = ""
+ + ""
+ + ""
+ + ""
+ + "";
+ writeZipEntry(archive, "[Content_Types].xml", types.getBytes(StandardCharsets.UTF_8));
+ String relationships = ""
+ + "";
+ writeZipEntry(archive, "_rels/.rels", relationships.getBytes(StandardCharsets.UTF_8));
+ writeZipEntry(archive, documentPath, documentXml.getBytes(StandardCharsets.UTF_8));
+ }
+ return output.toByteArray();
+ }
+
+ private static void writeZipEntry(ZipOutputStream archive, String path, byte[] content)
+ throws IOException {
+ archive.putNextEntry(new ZipEntry(path));
+ archive.write(content);
+ archive.closeEntry();
+ }
+
+ @Test
+ void shouldNotCloseNonMarkableCallerStream() throws IOException {
+ byte[] content = "%PDF-1.7\n%%EOF".getBytes(StandardCharsets.US_ASCII);
+ ByteArrayInputStream delegate = new ByteArrayInputStream(content);
+ AtomicBoolean closed = new AtomicBoolean();
+ InputStream stream = new InputStream() {
+ @Override
+ public int read() {
+ return delegate.read();
+ }
+
+ @Override
+ public int read(byte[] bytes, int offset, int length) {
+ return delegate.read(bytes, offset, length);
+ }
+
+ @Override
+ public void close() {
+ closed.set(true);
+ }
+ };
+
+ assertEquals("application/pdf", TikaUtil.detectMimeType(stream).getName());
+ assertFalse(closed.get(), "the caller owns the stream even without mark/reset");
+ }
+
+ @Test
+ void shouldRejectOversizedBufferedStreamWithoutLosingItsPosition() throws IOException {
+ byte[] content = new byte[1024 * 1024 + 1];
+ byte[] header = "%PDF-1.7\n%%EOF".getBytes(StandardCharsets.US_ASCII);
+ System.arraycopy(header, 0, content, 0, header.length);
+ try (InputStream stream = new BufferedInputStream(new ByteArrayInputStream(content))) {
+ IOException error = assertThrows(IOException.class, () -> TikaUtil.detectMimeType(stream));
+ assertTrue(error.getMessage().contains("1 MiB"));
+ assertArrayEquals(header, stream.readNBytes(header.length));
+ }
+ }
+
+ @Test
+ void shouldDetectFileContentDespiteMisleadingExtension() throws IOException {
+ Path file = Files.createTempFile("tika-content-", ".txt");
+ try {
+ Files.write(file, "%PDF-1.7\n%%EOF".getBytes(StandardCharsets.US_ASCII));
+ assertEquals("application/pdf", TikaUtil.detectMimeType(file.toFile()).getName());
+ } finally {
+ Files.deleteIfExists(file);
}
}
@@ -65,7 +223,24 @@ void shouldDetectContentMimeType() throws IOException {
UploadFile uploadFile = new DefaultUploadFile("field", "test.pdf", "application/pdf",
pdfContent.length, () -> new ByteArrayInputStream(pdfContent));
MimeType mimeType = TikaUtil.detectContentMimeType(uploadFile);
- assertNotNull(mimeType);
+ assertEquals("application/pdf", mimeType.getName());
+ }
+
+ @Test
+ void shouldIgnoreSpoofedFilenameAndCloseUploadStream() throws IOException {
+ byte[] pdfContent = "%PDF-1.7\n%%EOF".getBytes(StandardCharsets.US_ASCII);
+ AtomicBoolean closed = new AtomicBoolean();
+ UploadFile uploadFile = new DefaultUploadFile("field", "picture.png", "image/png",
+ pdfContent.length, () -> new ByteArrayInputStream(pdfContent) {
+ @Override
+ public void close() throws IOException {
+ closed.set(true);
+ super.close();
+ }
+ });
+
+ assertEquals("application/pdf", TikaUtil.detectContentMimeType(uploadFile).getName());
+ assertTrue(closed.get(), "the upload stream must be closed after detection");
}
@Test