diff --git a/README.md b/README.md index d660234..e93bb8f 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [![Java](https://img.shields.io/badge/Java-17-orange)](https://github.com/easy-4-java/validation-api-extension) [![License](https://img.shields.io/badge/license-Apache%202.0-green)](./LICENSE) -Javax Validation extensions and common constraint validators — a standalone Bean Validation (JSR-380, `javax.validation`) extension library with ready-to-use constraint annotations and framework-agnostic file upload validation backed by Apache Tika. +Jakarta Validation extensions and common constraint validators — a standalone Bean Validation (`jakarta.validation`) extension library with ready-to-use constraint annotations and framework-agnostic file upload validation backed by Apache Tika. ## Table of Contents @@ -22,7 +22,7 @@ Javax Validation extensions and common constraint validators — a standalone Be ## 1. Project Overview -`validation-api-extension` is a pure-Java extension for Bean Validation 2.0 (`javax.validation`). It provides: +`validation-api-extension` on `main` is a pure-Java extension for Jakarta Validation 3.1 (`jakarta.validation`). It provides: - Common constraint annotations (`@IdCard`, `@PhoneNumber`, `@Regexp`, `@Contains`, `@NumberValue`, `@StringDateValue`, `@AllowableValues`) with their validators, backed by regex property resources and libphonenumber. - File upload validation (`@FileNotEmpty` / `@FilesNotEmpty`) that checks file presence, extension whitelist, size limit and — in strict mode — the real file content via Apache Tika (do not trust the client-declared `Content-Type`). @@ -31,8 +31,8 @@ Javax Validation extensions and common constraint validators — a standalone Be **What it is not** - Not a validation engine — it plugs into any Bean Validation provider (Hibernate Validator is used in tests). -- Not a Jakarta Validation (`jakarta.validation`) build on the 1.0.x line — the 3.0.x line switches to Jakarta namespaces (see Section 10). -- Not tied to Spring / Javalin / Quarkus — the core module depends only on the `javax.validation` API. +- The 1.0.x and 2.0.x maintenance branches use `javax.validation`; `main` and 3.0.x use `jakarta.validation`. +- Not tied to Spring / Javalin / Quarkus — the core module uses the `jakarta.validation` API on `main`. **Typical scenarios** @@ -64,10 +64,10 @@ Javax Validation extensions and common constraint validators — a standalone Be | Requirement | Version | |:---|:---| -| JDK | 17+ (baseline of the `feature/2.0.x` branch, `maven.compiler.release=8`) | +| JDK | 17+ on `main` (`maven.compiler.release=17`) | | Maven | 3.0+ | -| Bean Validation API | `javax.validation:validation-api` 2.0.1.Final | -| Runtime provider | Any JSR-380 provider (tests use Hibernate Validator 6.2.4.Final) | +| Bean Validation API | `jakarta.validation:jakarta.validation-api` 3.1.1 on `main` | +| Runtime provider | A Jakarta Validation 3.1 provider (tests use Hibernate Validator 8.0.3.Final) | **Version line matrix** @@ -77,7 +77,7 @@ Javax Validation extensions and common constraint validators — a standalone Be | `feature/2.0.x` | 17 | Javax Validation 2.0.1 | `2.0.x.*` | | `feature/3.0.x` | 21 | Jakarta Validation 3.1.1 | `3.0.x.*` | -Besides the `javax` / `jakarta` namespace adaptation, the three lines keep the same public API, implementation and documentation. Dependency baselines evolve per line (verified from the branch POMs): +The table below describes the maintenance branches. The `main` branch uses Java 17, Jakarta Validation and Tika 4.0.0. Tika 4 changes parser and detector SPI signatures, so applications with custom Tika integrations must migrate them; do not assume binary compatibility with Tika 2 or 3. Dependency baselines for the maintenance branches are: | Key dependency | `1.0.x` | `2.0.x` | `3.0.x` | |:---|:---|:---|:---| @@ -92,7 +92,7 @@ The `1.0.x` line pins Apache Tika at **2.9.4**, the newest Tika version loadable ## 4. Architecture & Modules ```text - Bean Validation (javax.validation, e.g. Hibernate Validator) + Bean Validation (jakarta.validation, e.g. Hibernate Validator) | +----------------------------------------------------+ | @IdCard @PhoneNumber @Regexp @Contains | @@ -136,29 +136,32 @@ The `1.0.x` line pins Apache Tika at **2.9.4**, the newest Tika version loadable io.github.easy4j validation-api-extension - 2.0.x.x.20260630-SNAPSHOT + 2.0.x.20260630-SNAPSHOT ``` **Gradle** ```gradle -implementation 'io.github.easy4j:validation-api-extension:2.0.x.x.20260630-SNAPSHOT' +implementation 'io.github.easy4j:validation-api-extension:2.0.x.20260630-SNAPSHOT' ``` -For container formats (`doc/docx/xls/xlsx`, ...), applications are recommended to bring the standard Tika parser package explicitly (provided-scope in this library): +For container formats (`doc/docx/xls/xlsx`, ...), applications using `main` should add the matching Tika 4 parser package explicitly. This library declares it with `provided` scope, so its parser modules are available while building and testing the library but are not supplied transitively to consumers at runtime. Keep the parser package and `tika-core` on the same Tika version: ```xml org.apache.tika tika-parsers-standard-package - 2.9.4 + 4.0.0 + pom ``` +In Gradle, use `implementation 'org.apache.tika:tika-parsers-standard-package:4.0.0@pom'`. The `1.0.x` Java 8 branch remains on Tika 2.9.4; do not use this Tika 4 example there. Custom parsers and detectors built against older Tika SPI must be migrated before use with Tika 4. For `TikaUtil.detectMimeType(InputStream)`, a `ByteArrayInputStream` is fully inspected and reset. Other markable streams are fully inspected and reset up to 1 MiB; larger ones fail with `IOException` so a truncated container is not misidentified. A non-markable stream may advance, and the method never closes a caller-owned stream. Use the `File` or `UploadFile` overload for larger inputs when possible. + ## 6. Quick Start -**Constraint validation** (any JSR-380 provider): +**Constraint validation** (a Jakarta Validation provider): ```java public class UserDto { diff --git a/README.zh-CN.md b/README.zh-CN.md index 3b2339e..ebe8b42 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -4,7 +4,7 @@ [![Java](https://img.shields.io/badge/Java-17-orange)](https://github.com/easy-4-java/validation-api-extension) [![License](https://img.shields.io/badge/license-Apache%202.0-green)](./LICENSE) -Javax Validation extensions and common constraint validators —— 独立的 Bean Validation(JSR-380,`javax.validation`)扩展库,提供开箱即用的约束注解,以及基于 Apache Tika 的框架无关文件上传校验能力。 +Jakarta Validation extensions and common constraint validators —— 独立的 Bean Validation(`jakarta.validation`)扩展库,提供开箱即用的约束注解,以及基于 Apache Tika 的框架无关文件上传校验能力。 ## 目录 @@ -22,7 +22,7 @@ Javax Validation extensions and common constraint validators —— 独立的 Be ## 1. 项目概述 -`validation-api-extension` 是 Bean Validation 2.0(`javax.validation`)的纯 Java 扩展库,提供: +`validation-api-extension` 的 `main` 分支是 Jakarta Validation 3.1(`jakarta.validation`)的纯 Java 扩展库,提供: - 常用约束注解(`@IdCard`、`@PhoneNumber`、`@Regexp`、`@Contains`、`@NumberValue`、`@StringDateValue`、`@AllowableValues`)及其校验器,底层由正则属性资源与 libphonenumber 支撑。 - 文件上传校验(`@FileNotEmpty` / `@FilesNotEmpty`):检查文件是否存在、扩展名白名单、大小上限,并在严格模式下通过 Apache Tika 校验真实文件内容(不信任客户端声明的 `Content-Type`)。 @@ -31,8 +31,8 @@ Javax Validation extensions and common constraint validators —— 独立的 Be **它不是什么** - 不是校验引擎 —— 它插拔到任意 Bean Validation 实现(测试使用 Hibernate Validator)。 -- 在 1.0.x 版本线上不是 Jakarta Validation(`jakarta.validation`)构建 —— 3.0.x 版本线切换到 Jakarta 命名空间(见第 10 节)。 -- 不绑定 Spring / Javalin / Quarkus —— 核心模块仅依赖 `javax.validation` API。 +- 1.0.x 和 2.0.x 维护分支使用 `javax.validation`;`main` 与 3.0.x 使用 `jakarta.validation`。 +- 不绑定 Spring / Javalin / Quarkus —— `main` 的核心模块使用 `jakarta.validation` API。 **典型场景** @@ -64,10 +64,10 @@ Javax Validation extensions and common constraint validators —— 独立的 Be | 要求 | 版本 | |:---|:---| -| JDK | 17+(`feature/2.0.x` 分支基线,`maven.compiler.release=8`) | +| JDK | `main` 为 17+(`maven.compiler.release=17`) | | Maven | 3.0+ | -| Bean Validation API | `javax.validation:validation-api` 2.0.1.Final | -| 运行时实现 | 任意 JSR-380 实现(测试使用 Hibernate Validator 6.2.4.Final) | +| Bean Validation API | `main` 使用 `jakarta.validation:jakarta.validation-api` 3.1.1 | +| 运行时实现 | Jakarta Validation 3.1 实现(测试使用 Hibernate Validator 8.0.3.Final) | **版本线矩阵** @@ -77,7 +77,7 @@ Javax Validation extensions and common constraint validators —— 独立的 Be | `feature/2.0.x` | 17 | Javax Validation 2.0.1 | `2.0.x.*` | | `feature/3.0.x` | 21 | Jakarta Validation 3.1.1 | `3.0.x.*` | -除 `javax` / `jakarta` 命名空间适配外,三条版本线保持相同的公共 API、实现逻辑与文档。依赖基线随版本线递进(已从各分支 POM 核实): +下表描述维护分支;`main` 使用 Java 17、Jakarta Validation 和 Tika 4.0.0。Tika 4 更改了解析器和检测器 SPI 签名,使用自定义 Tika 集成的应用需要迁移,不能假定与 Tika 2/3 二进制兼容。维护分支的依赖基线如下: | 关键依赖 | `1.0.x` | `2.0.x` | `3.0.x` | |:---|:---|:---|:---| @@ -92,7 +92,7 @@ Javax Validation extensions and common constraint validators —— 独立的 Be ## 4. 架构与模块 ```text - Bean Validation(javax.validation,如 Hibernate Validator) + Bean Validation(jakarta.validation,如 Hibernate Validator) | +----------------------------------------------------+ | @IdCard @PhoneNumber @Regexp @Contains | @@ -136,29 +136,32 @@ Javax Validation extensions and common constraint validators —— 独立的 Be io.github.easy4j validation-api-extension - 2.0.x.x.20260630-SNAPSHOT + 2.0.x.20260630-SNAPSHOT ``` **Gradle** ```gradle -implementation 'io.github.easy4j:validation-api-extension:2.0.x.x.20260630-SNAPSHOT' +implementation 'io.github.easy4j:validation-api-extension:2.0.x.20260630-SNAPSHOT' ``` -对于 `doc/docx/xls/xlsx` 等容器格式,建议应用显式引入标准 Tika 解析包(本库中为 provided 作用域): +对于 `doc/docx/xls/xlsx` 等容器格式,使用 `main` 的应用应显式引入匹配的 Tika 4 解析包。本库将其声明为 `provided`:构建和测试本库时可用,但不会作为运行时传递依赖提供给使用方。解析包与 `tika-core` 应保持同一版本: ```xml org.apache.tika tika-parsers-standard-package - 2.9.4 + 4.0.0 + pom ``` +Gradle 使用 `implementation 'org.apache.tika:tika-parsers-standard-package:4.0.0@pom'`。Java 8 的 `1.0.x` 分支仍使用 Tika 2.9.4,不适用上述 Tika 4 示例。基于旧版 Tika SPI 的自定义解析器和检测器需要迁移后才能用于 Tika 4。`TikaUtil.detectMimeType(InputStream)` 会完整检查并复位 `ByteArrayInputStream`。其他可标记流在 1 MiB 以内完整检查并复位;超过上限时抛出 `IOException`,避免将截断的容器误判为普通 ZIP。不可标记流的位置可能前移,此方法不会关闭调用方持有的流。较大输入尽量使用 `File` 或 `UploadFile` 重载。 + ## 6. 快速开始 -**约束校验**(任意 JSR-380 实现): +**约束校验**(Jakarta Validation 实现): ```java public class UserDto { diff --git a/pom.xml b/pom.xml index 70613dd..0f84388 100644 --- a/pom.xml +++ b/pom.xml @@ -58,6 +58,8 @@ ${java.version} 3.0 UTF-8 + + UTF-8 @@ -77,7 +79,7 @@ 1.18.46 2.0.8 2.0.18 - 3.3.1 + 4.0.0 2.8 @@ -165,6 +167,7 @@ org.apache.tika tika-parsers-standard-package ${tika.version} + pom @@ -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