This is an automated email from the ASF dual-hosted git repository.

chungen0126 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git


The following commit(s) were added to refs/heads/master by this push:
     new 62dabac5427 HDDS-16661. Validate unsigned S3 checksum trailer 
completion and framing (#11586)
62dabac5427 is described below

commit 62dabac5427ce071b31db0f8b1ae566c3de4fde2
Author: KUAN-HAO HUANG <[email protected]>
AuthorDate: Mon Oct 26 17:50:08 2026 +0800

    HDDS-16661. Validate unsigned S3 checksum trailer completion and framing 
(#11586)
---
 .../hadoop/ozone/s3/SignedChunksInputStream.java   |  39 ++-
 .../hadoop/ozone/s3/UnsignedChunksInputStream.java | 209 +++++++-------
 .../hadoop/ozone/s3/endpoint/EndpointBase.java     |   3 +-
 .../hadoop/ozone/s3/endpoint/ObjectEndpoint.java   |   8 +
 .../ozone/s3/endpoint/S3ObjectWriteGuard.java      |  14 +-
 .../ozone/s3/TestUnsignedChunkInputStream.java     | 300 ++++++++++-----------
 .../hadoop/ozone/s3/endpoint/TestObjectPut.java    | 103 ++++++-
 .../hadoop/ozone/s3/endpoint/TestPartUpload.java   |  35 +++
 .../ozone/s3/endpoint/TestS3ObjectWriteGuard.java  |  23 ++
 9 files changed, 469 insertions(+), 265 deletions(-)

diff --git 
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/SignedChunksInputStream.java
 
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/SignedChunksInputStream.java
index 0e3330e16b7..bf2e678c3d3 100644
--- 
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/SignedChunksInputStream.java
+++ 
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/SignedChunksInputStream.java
@@ -24,6 +24,7 @@
 import java.io.InputStream;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
+import java.util.Base64;
 import java.util.Locale;
 import java.util.Objects;
 import java.util.regex.Matcher;
@@ -124,24 +125,44 @@ public class SignedChunksInputStream extends InputStream {
 
   /** Supported checksum trailers, or no trailer for a regular signed stream. 
*/
   public enum TrailerHeader {
-    NONE(""),
-    CRC32("x-amz-checksum-crc32"),
-    CRC32C("x-amz-checksum-crc32c"),
-    CRC64NVME("x-amz-checksum-crc64nvme"),
-    SHA1("x-amz-checksum-sha1"),
-    SHA256("x-amz-checksum-sha256");
+    NONE("", 0),
+    CRC32("x-amz-checksum-crc32", 4),
+    CRC32C("x-amz-checksum-crc32c", 4),
+    CRC64NVME("x-amz-checksum-crc64nvme", 8),
+    SHA1("x-amz-checksum-sha1", 20),
+    SHA256("x-amz-checksum-sha256", 32);
 
     private final String headerName;
+    private final int checksumLength;
 
-    TrailerHeader(String headerName) {
+    TrailerHeader(String headerName, int checksumLength) {
       this.headerName = headerName;
+      this.checksumLength = checksumLength;
     }
 
-    /** Parse the required single-checksum declaration of a signed trailer 
upload. */
+    String getHeaderName() {
+      return headerName;
+    }
+
+    byte[] decodeValue(String value, String resource) {
+      try {
+        byte[] checksum = Base64.getDecoder().decode(value);
+        if (checksum.length == checksumLength) {
+          return checksum;
+        }
+      } catch (IllegalArgumentException ignored) {
+        // Invalid Base64 and incorrect decoded length are both malformed 
checksum values.
+      }
+      OS3Exception ex = S3ErrorTable.newError(S3ErrorTable.INVALID_REQUEST, 
resource);
+      ex.setErrorMessage("Value for " + headerName + " header is invalid");
+      throw ex;
+    }
+
+    /** Parse the required single-checksum declaration of a trailer upload. */
     public static TrailerHeader fromHeader(String header, String keyPath) {
       if (StringUtils.isBlank(header)) {
         OS3Exception ex = S3ErrorTable.newError(S3ErrorTable.INVALID_ARGUMENT, 
keyPath);
-        ex.setErrorMessage("The " + X_AMZ_TRAILER + " header is required for 
signed trailing headers");
+        ex.setErrorMessage("The " + X_AMZ_TRAILER + " header is required for 
trailing headers");
         throw ex;
       }
       String name = header.trim().toLowerCase(Locale.ROOT);
diff --git 
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/UnsignedChunksInputStream.java
 
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/UnsignedChunksInputStream.java
index 93565b0d820..3f581758bb8 100644
--- 
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/UnsignedChunksInputStream.java
+++ 
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/UnsignedChunksInputStream.java
@@ -21,7 +21,12 @@
 
 import java.io.IOException;
 import java.io.InputStream;
+import java.util.Locale;
 import java.util.Objects;
+import java.util.regex.Pattern;
+import org.apache.hadoop.ozone.s3.SignedChunksInputStream.TrailerHeader;
+import org.apache.hadoop.ozone.s3.exception.OS3Exception;
+import org.apache.hadoop.ozone.s3.exception.S3ErrorTable;
 
 /**
  * Input stream implementation to read body of an unsigned chunked upload.
@@ -29,7 +34,6 @@
  * Currently, the only valid value of x-amz-content-sha256 header to indicate
  * transfer unsigned payload in multiple chunks is 
STREAMING-UNSIGNED-PAYLOAD-TRAILER.
  * Therefore, the input stream should work with chunked payloads with checksum 
trailer.
- * Nevertheless, this input stream also supports chunked upload without 
trailer.
  * </p>
  * <p>
  * Example chunk data:
@@ -38,6 +42,7 @@
  * &lt;65536-bytes&gt;\r\n
  * 0\r\n
  * x-amz-checksum-crc64nvme:2wstOANdZ/o=\r\n
+ * \r\n
  * </pre>
  * </p>
  * <p>
@@ -52,8 +57,8 @@
  * </p>
  *
  * <p>
- * Note that there is not actual trailer checksum verification taking place. 
The InputStream only
- * returns the actual chunk payload from chunked signatures format.
+ * This stream validates chunk and trailer framing, including the checksum 
encoding and length.
+ * It does not compare the trailer checksum with the payload.
  * </p>
  *
  * Reference:
@@ -70,48 +75,37 @@
  */
 public class UnsignedChunksInputStream extends InputStream {
 
-  private final InputStream originalStream;
-
-  /**
-   * Size of the chunk payload. If zero, the content length should be parsed to
-   * retrieve the subsequent chunk payload size.
-   */
-  private int remainingData = 0;
+  private static final Pattern CHUNK_SIZE_PATTERN = 
Pattern.compile("[0-9A-Fa-f]{1,16}");
+  private static final int MAX_LINE_LENGTH = 8 * 1024;
 
-  /**
-   * Every chunked uploads (multiple chunks) contains an additional final 
zero-byte
-   * chunk. This can be used as the end-of-file marker.
-   */
-  private boolean isFinalChunkEncountered = false;
+  private final InputStream originalStream;
+  private final String keyPath;
+  private final TrailerHeader trailerHeader;
+  private long remainingData;
+  private boolean isFinalChunkEncountered;
+  private byte[] trailerChecksum;
 
-  public UnsignedChunksInputStream(InputStream inputStream) {
+  public UnsignedChunksInputStream(InputStream inputStream, String keyPath, 
TrailerHeader trailerHeader) {
     originalStream = inputStream;
+    this.keyPath = keyPath;
+    this.trailerHeader = Objects.requireNonNull(trailerHeader, "trailerHeader 
== null");
+    if (trailerHeader == TrailerHeader.NONE) {
+      throw new IllegalArgumentException("Unsigned chunked uploads require a 
checksum trailer");
+    }
   }
 
   @Override
   public int read() throws IOException {
-    if (isFinalChunkEncountered) {
+    if (isFinalChunkEncountered || !ensureChunkPayload()) {
       return -1;
     }
-    if (remainingData > 0) {
-      int curr = originalStream.read();
-      remainingData--;
-      if (remainingData == 0) {
-        //read the "\r\n" at the end of the data section
-        originalStream.read();
-        originalStream.read();
-      }
-      return curr;
-    } else {
-      remainingData = readContentLengthFromHeader();
-      if (remainingData <= 0) {
-        // since currently trailer checksum verification is not supported, we 
can
-        // stop reading after encountering the final zero-byte chunk.
-        isFinalChunkEncountered = true;
-        return -1;
-      }
-      return read();
+    int value = originalStream.read();
+    if (value == -1) {
+      throw invalidBody("Truncated chunk payload");
     }
+    remainingData--;
+    endChunkIfComplete();
+    return value;
   }
 
   @Override
@@ -122,70 +116,103 @@ public int read(byte[] b, int off, int len) throws 
IOException {
           + len + " don't match the array length of " + b.length);
     } else if (len == 0) {
       return 0;
-    } else if (isFinalChunkEncountered) {
-      return -1;
     }
-    int currentOff = off;
-    int currentLen = len;
     int totalReadBytes = 0;
-    int realReadLen = 0;
-    int maxReadLen = 0;
-    do {
-      if (remainingData > 0) {
-        // The chunk payload size has been decoded, now read the actual chunk 
payload
-        maxReadLen = Math.min(remainingData, currentLen);
-        realReadLen = originalStream.read(b, currentOff, maxReadLen);
-        if (realReadLen == -1) {
-          break;
-        }
-        currentOff += realReadLen;
-        currentLen -= realReadLen;
-        totalReadBytes += realReadLen;
-        remainingData -= realReadLen;
-        if (remainingData == 0) {
-          //read the "\r\n" at the end of the data section
-          originalStream.read();
-          originalStream.read();
-        }
-      } else {
-        remainingData = readContentLengthFromHeader();
-        if (remainingData == 0) {
-          // there is always a final zero byte chunk so we can stop reading
-          // if we encounter this chunk
-          isFinalChunkEncountered = true;
-        }
-        if (isFinalChunkEncountered || remainingData == -1) {
-          break;
-        }
+    while (totalReadBytes < len && !isFinalChunkEncountered && 
ensureChunkPayload()) {
+      int readLength = originalStream.read(b, off + totalReadBytes,
+          (int) Math.min(remainingData, len - totalReadBytes));
+      if (readLength == -1) {
+        throw invalidBody("Truncated chunk payload");
       }
-    } while (currentLen > 0);
+      totalReadBytes += readLength;
+      remainingData -= readLength;
+      endChunkIfComplete();
+    }
     return totalReadBytes > 0 ? totalReadBytes : -1;
   }
 
-  private int readContentLengthFromHeader() throws IOException {
-    int prev = -1;
-    int curr = 0;
-    StringBuilder buf = new StringBuilder();
+  private boolean ensureChunkPayload() throws IOException {
+    if (remainingData > 0) {
+      return true;
+    }
+    String size = readLine();
+    if (!CHUNK_SIZE_PATTERN.matcher(size).matches()) {
+      throw invalidBody("Invalid unsigned chunk size");
+    }
+    try {
+      remainingData = Long.parseLong(size, 16);
+    } catch (NumberFormatException ex) {
+      throw invalidBody("Invalid unsigned chunk size");
+    }
+    if (remainingData > 0) {
+      return true;
+    }
+    readTrailer();
+    isFinalChunkEncountered = true;
+    return false;
+  }
 
-    //read everything until the next \r\n
-    while (!eol(prev, curr) && curr != -1) {
-      int next = originalStream.read();
-      if (next != -1) {
-        buf.append((char) next);
+  private void endChunkIfComplete() throws IOException {
+    if (remainingData == 0 && (originalStream.read() != '\r' || 
originalStream.read() != '\n')) {
+      throw invalidBody("Invalid chunk data terminator");
+    }
+  }
+
+  /** Finish the zero-byte chunk and trailer after the caller consumes the 
decoded content length. */
+  public void verifyComplete() throws IOException {
+    if (!isFinalChunkEncountered && read() != -1) {
+      throw invalidBody("Decoded content length ended before the chunked 
stream");
+    }
+  }
+
+  /** @return the decoded checksum after successful trailer completion, or 
null before completion. */
+  public byte[] getTrailerChecksum() {
+    return trailerChecksum == null ? null : trailerChecksum.clone();
+  }
+
+  private void readTrailer() throws IOException {
+    String trailer = readLine();
+    int separator = trailer.indexOf(':');
+    if (separator <= 0) {
+      throw invalidBody("Missing or invalid trailing checksum header");
+    }
+    String name = trailer.substring(0, 
separator).trim().toLowerCase(Locale.ROOT);
+    if (!trailerHeader.getHeaderName().equals(name)) {
+      throw invalidBody("Unexpected trailing header: " + name);
+    }
+    byte[] checksum = trailerHeader.decodeValue(trailer.substring(separator + 
1).trim(), keyPath);
+    if (!readLine().isEmpty()) {
+      throw invalidBody("Invalid trailer terminator");
+    }
+    if (originalStream.read() != -1) {
+      throw invalidBody("Unexpected data after trailing checksum");
+    }
+    trailerChecksum = checksum;
+  }
+
+  private String readLine() throws IOException {
+    StringBuilder line = new StringBuilder();
+    int previous = -1;
+    while (true) {
+      int current = originalStream.read();
+      if (current == -1) {
+        throw invalidBody("Chunked stream ended before completion");
       }
-      prev = curr;
-      curr = next;
-    }
-    // Example of a single chunk data:
-    //  10000\r\n
-    //  <65536-bytes>\r\n
-    //
-    // 10000 will be read and decoded from base-16 representation to 65536, 
which is the size of
-    // the subsequent chunk payload.
-    String readString = buf.toString().trim();
-    if (readString.isEmpty()) {
-      return -1;
+      line.append((char) current);
+      if (line.length() > MAX_LINE_LENGTH) {
+        throw invalidBody("Chunk or trailing header line is too long");
+      }
+      if (eol(previous, current)) {
+        line.setLength(line.length() - 2);
+        return line.toString();
+      }
+      previous = current;
     }
-    return Integer.parseInt(readString, 16);
+  }
+
+  private OS3Exception invalidBody(String message) {
+    OS3Exception ex = S3ErrorTable.newError(S3ErrorTable.INVALID_REQUEST, 
keyPath);
+    ex.setErrorMessage(message);
+    return ex;
   }
 }
diff --git 
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/EndpointBase.java
 
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/EndpointBase.java
index 53c930247a3..91e6d7f519b 100644
--- 
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/EndpointBase.java
+++ 
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/EndpointBase.java
@@ -893,7 +893,8 @@ protected S3ChunkInputStreamInfo getS3ChunkInputStreamInfo(
     if (payloadType.isStreaming()) {
       validateMultiChunksUpload(getHeaders(), amzDecodedLength, keyPath);
       if (payloadType.isUnsigned()) {
-        chunkInputStream = new UnsignedChunksInputStream(body);
+        chunkInputStream = new UnsignedChunksInputStream(body, keyPath,
+            
TrailerHeader.fromHeader(getHeaders().getHeaderString(X_AMZ_TRAILER), keyPath));
       } else {
         TrailerHeader trailerHeader = payloadType == 
S3ContentSha256Type.STREAMING_AWS4_HMAC_SHA256_PAYLOAD_TRAILER
             ? 
TrailerHeader.fromHeader(getHeaders().getHeaderString(X_AMZ_TRAILER), keyPath) 
: TrailerHeader.NONE;
diff --git 
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/ObjectEndpoint.java
 
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/ObjectEndpoint.java
index 7cd5c81f054..8cf13edd52a 100644
--- 
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/ObjectEndpoint.java
+++ 
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/ObjectEndpoint.java
@@ -40,6 +40,7 @@
 import static 
org.apache.hadoop.ozone.s3.util.S3Consts.RANGE_HEADER_MATCH_PATTERN;
 import static 
org.apache.hadoop.ozone.s3.util.S3Consts.RANGE_HEADER_SUPPORTED_UNIT;
 import static org.apache.hadoop.ozone.s3.util.S3Consts.STORAGE_CLASS_HEADER;
+import static 
org.apache.hadoop.ozone.s3.util.S3Consts.STREAMING_UNSIGNED_PAYLOAD_TRAILER;
 import static org.apache.hadoop.ozone.s3.util.S3Consts.TAG_COUNT_HEADER;
 import static org.apache.hadoop.ozone.s3.util.S3Consts.TAG_DIRECTIVE_HEADER;
 import static org.apache.hadoop.ozone.s3.util.S3Utils.normalizeContentEncoding;
@@ -101,6 +102,7 @@
 import org.apache.hadoop.ozone.om.helpers.OmMultipartUploadCompleteInfo;
 import org.apache.hadoop.ozone.s3.HeaderPreprocessor;
 import org.apache.hadoop.ozone.s3.MultiDigestInputStream;
+import org.apache.hadoop.ozone.s3.UnsignedChunksInputStream;
 import org.apache.hadoop.ozone.s3.exception.OS3Exception;
 import org.apache.hadoop.ozone.s3.exception.S3ErrorTable;
 import org.apache.hadoop.ozone.s3.util.RFC1123Util;
@@ -253,6 +255,12 @@ Response handlePutRequest(ObjectRequestContext context, 
String keyPath, InputStr
           StringUtils.endsWith(keyPath, "/")
       ) {
         context.setAction(S3GAction.CREATE_DIRECTORY);
+        if 
(STREAMING_UNSIGNED_PAYLOAD_TRAILER.equals(getHeaders().getHeaderString(S3Consts.X_AMZ_CONTENT_SHA256)))
 {
+          S3ChunkInputStreamInfo info = getS3ChunkInputStreamInfo(body, 
length, amzDecodedLength, keyPath);
+          multiDigestInputStream = info.getMultiDigestInputStream();
+          validateContentLength(info.getEffectiveLength(), 0, keyPath).run();
+          ((UnsignedChunksInputStream) 
multiDigestInputStream.getWrappedStream()).verifyComplete();
+        }
         getClientProtocol()
             .createDirectory(volume.getName(), bucketName, keyPath);
         long metadataLatencyNs =
diff --git 
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/S3ObjectWriteGuard.java
 
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/S3ObjectWriteGuard.java
index e8f100b0e43..6d662671437 100644
--- 
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/S3ObjectWriteGuard.java
+++ 
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/S3ObjectWriteGuard.java
@@ -31,6 +31,7 @@
 import org.apache.hadoop.ozone.client.io.OzoneOutputStream;
 import org.apache.hadoop.ozone.s3.MultiDigestInputStream;
 import org.apache.hadoop.ozone.s3.SignedChunksInputStream;
+import org.apache.hadoop.ozone.s3.UnsignedChunksInputStream;
 import org.apache.hadoop.ozone.s3.exception.S3ErrorTable;
 import org.apache.ratis.util.function.CheckedRunnable;
 
@@ -138,7 +139,7 @@ long copyFrom(InputStream body, int bufferSize) throws 
IOException {
       writtenLength += readLength;
     }
     try {
-      verifySignedChunksComplete(body);
+      verifyChunksComplete(body);
     } catch (IOException | RuntimeException ex) {
       recordTransferFailure(ex);
       throw ex;
@@ -146,10 +147,13 @@ long copyFrom(InputStream body, int bufferSize) throws 
IOException {
     return writtenLength;
   }
 
-  private static void verifySignedChunksComplete(InputStream body) throws 
IOException {
-    SignedChunksInputStream signed = SignedChunksInputStream.unwrap(body);
-    if (signed != null) {
-      signed.verifyComplete();
+  private static void verifyChunksComplete(InputStream body) throws 
IOException {
+    InputStream chunks = body instanceof MultiDigestInputStream
+        ? ((MultiDigestInputStream) body).getWrappedStream() : body;
+    if (chunks instanceof SignedChunksInputStream) {
+      ((SignedChunksInputStream) chunks).verifyComplete();
+    } else if (chunks instanceof UnsignedChunksInputStream) {
+      ((UnsignedChunksInputStream) chunks).verifyComplete();
     }
   }
 
diff --git 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/TestUnsignedChunkInputStream.java
 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/TestUnsignedChunkInputStream.java
index 0f468923cfa..9d1c79b95be 100644
--- 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/TestUnsignedChunkInputStream.java
+++ 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/TestUnsignedChunkInputStream.java
@@ -18,206 +18,192 @@
 package org.apache.hadoop.ozone.s3;
 
 import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
 import java.io.IOException;
-import java.io.InputStream;
+import java.util.Base64;
+import java.util.stream.Stream;
 import org.apache.commons.io.IOUtils;
+import org.apache.hadoop.ozone.s3.SignedChunksInputStream.TrailerHeader;
+import org.apache.hadoop.ozone.s3.exception.OS3Exception;
+import org.apache.hadoop.ozone.s3.exception.S3ErrorTable;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
 
 /**
  * Test {@link UnsignedChunksInputStream}.
  */
 public class TestUnsignedChunkInputStream {
 
-  @Test
-  void testEmptyFile() throws IOException {
-    try (InputStream is = wrapContent("0\r\n")) {
-      assertEquals("", IOUtils.toString(is, UTF_8));
+  private static final String KEY_PATH = "bucket/key";
+  private static final String CONTENT = "1234567890abcde";
+  // Generated by botocore's AwsChunkedWrapper with CRC32 and a 10-byte chunk 
size.
+  private static final String BODY = "a\r\n1234567890\r\n5\r\nabcde\r\n0\r\n"
+      + "x-amz-checksum-crc32:HydN+w==\r\n\r\n";
+
+  @ParameterizedTest
+  @CsvSource({"CRC32,AAAAAA==", "CRC32C,AAAAAA==", "CRC64NVME,AAAAAAAAAAA=",
+      "SHA1,2jmj7l5rSw0yVb/vlWAYkK/YBwk=", 
"SHA256,47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="})
+  void emptyPayload(TrailerHeader header, String value) throws IOException {
+    String body = "0\r\n" + header.getHeaderName() + ":" + value + "\r\n\r\n";
+    try (UnsignedChunksInputStream stream = wrapContent(body, header)) {
+      stream.verifyComplete();
+      assertThat(stream.read()).isEqualTo(-1);
+      
assertThat(stream.getTrailerChecksum()).isEqualTo(Base64.getDecoder().decode(value));
     }
   }
 
-  @Test
-  void testEmptyFileWithTrailer() throws IOException {
-    try (InputStream is = wrapContent("0\r\n" 
-        + "x-amz-checksum-crc64nvme:AAAAAAAAAAA=\r\n")) {
-      assertEquals("", IOUtils.toString(is, UTF_8));
+  @ParameterizedTest
+  @ValueSource(ints = {0, 1, 2, 10, 15, 64})
+  void readAcrossChunks(int bufferSize) throws IOException {
+    try (UnsignedChunksInputStream stream = wrapContent(BODY, 
TrailerHeader.CRC32)) {
+      ByteArrayOutputStream result = new ByteArrayOutputStream();
+      if (bufferSize == 0) {
+        int value;
+        while ((value = stream.read()) != -1) {
+          result.write(value);
+        }
+      } else {
+        byte[] buffer = new byte[bufferSize + 2];
+        int length;
+        while ((length = stream.read(buffer, 2, bufferSize)) != -1) {
+          result.write(buffer, 2, length);
+        }
+      }
+      assertThat(result.toString(UTF_8.name())).isEqualTo(CONTENT);
+      
assertThat(stream.getTrailerChecksum()).isEqualTo(Base64.getDecoder().decode("HydN+w=="));
+      stream.verifyComplete();
+      assertThat(stream.read()).isEqualTo(-1);
+      assertThat(stream.read(new byte[1])).isEqualTo(-1);
+      assertThat(stream.read(new byte[0])).isEqualTo(0);
     }
   }
 
   @Test
-  public void testEmptyFileWithoutEnd() throws IOException {
-    try (InputStream is = wrapContent("0\r\n"
-        + "x-amz-checksum-crc64nvme:AAAAAAAAAAA=")) {
-      assertEquals("", IOUtils.toString(is, UTF_8));
+  void exactLengthReadStillRequiresCompletion() throws IOException {
+    ByteArrayInputStream original = new 
ByteArrayInputStream(BODY.getBytes(UTF_8));
+    try (UnsignedChunksInputStream stream = new 
UnsignedChunksInputStream(original, KEY_PATH, TrailerHeader.CRC32)) {
+      assertThat(IOUtils.readFully(stream, 
CONTENT.length())).isEqualTo(CONTENT.getBytes(UTF_8));
+      assertThat(stream.getTrailerChecksum()).isNull();
+      assertThat(original.available()).isPositive();
+
+      stream.verifyComplete();
+      assertThat(original.available()).isZero();
+      byte[] checksum = stream.getTrailerChecksum();
+      checksum[0] ^= 1;
+      
assertThat(stream.getTrailerChecksum()).isEqualTo(Base64.getDecoder().decode("HydN+w=="));
+      stream.verifyComplete();
     }
   }
 
   @Test
-  void testSingleChunk() throws IOException {
-    //test simple read()
-    try (InputStream is = wrapContent("0A\r\n"
-        + "1234567890\r\n"
-        + "0\r\n")) {
-      assertEquals("1234567890", IOUtils.toString(is, UTF_8));
-    }
-    
-    //test read(byte[],int,int)
-    try (InputStream is = wrapContent("0A\r\n"
-        + "1234567890\r\n"
-        + "0\r\n")) {
-      byte[] bytes = new byte[10];
-      IOUtils.read(is, bytes, 0, 10);
-      assertEquals("1234567890", new String(bytes, UTF_8));
-    }
-    
-    //test read(byte[],int,int) with length parameter larger than the payload
-    try (InputStream is = wrapContent("0A\r\n"
-        + "1234567890\r\n"
-        + "0\r\n")) {
-      byte[] bytes = new byte[15];
-      int readLength = IOUtils.read(is, bytes, 0, 15);
-      assertEquals(10, readLength);
-      assertEquals("1234567890", new String(bytes, UTF_8).substring(0, 10));
+  void skipConsumesDecodedPayload() throws IOException {
+    try (UnsignedChunksInputStream stream = wrapContent(BODY, 
TrailerHeader.CRC32)) {
+      assertThat(stream.skip(10)).isEqualTo(10);
+      assertThat(IOUtils.toString(stream, UTF_8)).isEqualTo("abcde");
+      
assertThat(stream.getTrailerChecksum()).isEqualTo(Base64.getDecoder().decode("HydN+w=="));
     }
   }
 
-  @Test
-  void testSingleChunkWithTrailer() throws IOException {
-    try (InputStream is = wrapContent("0A\r\n"
-        + "1234567890\r\n"
-        + "0\r\n"
-        + "x-amz-checksum-crc64nvme:2wstOANdZ/o=\r\n")) {
-      assertEquals("1234567890", IOUtils.toString(is, UTF_8));
-    }
-
-    //test read(byte[],int,int)
-    try (InputStream is = wrapContent("0A\r\n"
-        + "1234567890\r\n"
-        + "0\r\n"
-        + "x-amz-checksum-crc64nvme:2wstOANdZ/o=\r\n")) {
-      byte[] bytes = new byte[10];
-      IOUtils.read(is, bytes, 0, 10);
-      assertEquals("1234567890", new String(bytes, UTF_8));
-    }
-
-    //test read(byte[],int,int) with length parameter larger than the payload
-    try (InputStream is = wrapContent("0A\r\n"
-        + "1234567890\r\n"
-        + "0\r\n"
-        + "x-amz-checksum-crc64nvme:2wstOANdZ/o=\r\n")) {
-      byte[] bytes = new byte[15];
-      int readLength = IOUtils.read(is, bytes, 0, 15);
-      assertEquals(10, readLength);
-      assertEquals("1234567890", new String(bytes, UTF_8).substring(0, 10));
+  @ParameterizedTest
+  @ValueSource(ints = {0, 5, 10, 14})
+  void decodedLengthEndsBeforePayload(int length) throws IOException {
+    try (UnsignedChunksInputStream stream = wrapContent(BODY, 
TrailerHeader.CRC32)) {
+      IOUtils.readFully(stream, length);
+      OS3Exception error = assertThrows(OS3Exception.class, 
stream::verifyComplete);
+      
assertThat(error.getCode()).isEqualTo(S3ErrorTable.INVALID_REQUEST.getCode());
+      assertThat(error.getErrorMessage()).contains("Decoded content length 
ended before");
     }
   }
 
-  @Test
-  void testSingleChunkWithoutEnd() throws IOException {
-    try (InputStream is = wrapContent("0A\r\n"
-        + "1234567890\r\n"
-        + "0")) {
-      assertEquals("1234567890", IOUtils.toString(is, UTF_8));
-    }
-    //test read(byte[],int,int)
-    try (InputStream is = wrapContent("0A\r\n"
-        + "1234567890\r\n"
-        + "0")) {
-      byte[] bytes = new byte[10];
-      IOUtils.read(is, bytes, 0, 10);
-      assertEquals("1234567890", new String(bytes, UTF_8));
-    }
-    //test read(byte[],int,int) with length parameter larger than the payload
-    try (InputStream is = wrapContent("0A\r\n"
-        + "1234567890\r\n"
-        + "0")) {
-      byte[] bytes = new byte[15];
-      int readLength = IOUtils.read(is, bytes, 0, 10);
-      assertEquals(10, readLength);
-      assertEquals("1234567890", new String(bytes, UTF_8).substring(0, 10));
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  void rejectEveryTruncatedBody(boolean singleByte) throws IOException {
+    for (int length = 0; length < BODY.length(); length++) {
+      assertInvalidBody(BODY.substring(0, length), singleByte);
     }
   }
 
-  @Test
-  void testMultiChunks() throws IOException {
-    //test simple read()
-    try (InputStream is = wrapContent("0a\r\n"
-        + "1234567890\r\n"
-        + "05\r\n"
-        + "abcde\r\n"
-        + "0\r\n")) {
-      String result = IOUtils.toString(is, UTF_8);
-      assertEquals("1234567890abcde", result);
-    }
+  static Stream<Arguments> malformedBodies() {
+    return Stream.of(
+        "0\r\n\r\n",
+        "0\r\nx-amz-checksum-sha1:HydN+w==\r\n\r\n",
+        "0\r\nx-amz-checksum-crc32 HydN+w==\r\n\r\n",
+        "0\r\nx-amz-checksum-crc32:\r\n\r\n",
+        "0\r\nx-amz-checksum-crc32:not-base64\r\n\r\n",
+        "0\r\nx-amz-checksum-crc32:AAAA\r\n\r\n",
+        "0\r\nx-amz-checksum-crc32:AAAAAAAAAAA=\r\n\r\n",
+        
"0\r\nx-amz-checksum-crc32:AAAAAA==\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n",
+        "0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\nextra",
+        "0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n\r\n",
+        "1\r\naXX0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n",
+        "1\r\na\rX0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n",
+        "-1\r\n", "+1\r\n", "xyz\r\n", " 0\r\n", "0x0\r\n", 
"8000000000000000\r\n",
+        "10000000000000000\r\n", "0;chunk-signature=abc\r\n",
+        "A".repeat(8193) + "\r\n",
+        "0\r\nx-amz-checksum-crc32:" + "A".repeat(8193) + "\r\n\r\n")
+        .flatMap(body -> Stream.of(Arguments.of(body, false), 
Arguments.of(body, true)));
+  }
 
-    //test read(byte[],int,int)
-    try (InputStream is = wrapContent("0a\r\n"
-        + "1234567890\r\n"
-        + "05\r\n"
-        + "abcde\r\n"
-        + "0\r\n")) {
-      byte[] bytes = new byte[15];
-      IOUtils.read(is, bytes, 0, 15);
-      assertEquals("1234567890abcde", new String(bytes, UTF_8));
-    }
+  @ParameterizedTest
+  @MethodSource("malformedBodies")
+  void rejectMalformedBody(String body, boolean singleByte) throws IOException 
{
+    assertInvalidBody(body, singleByte);
+  }
 
-    //test read(byte[],int,int) with length parameter larger than the payload
-    try (InputStream is = wrapContent("0a\r\n"
-        + "1234567890\r\n"
-        + "05\r\n"
-        + "abcde\r\n"
-        + "0\r\n")) {
-      byte[] bytes = new byte[20];
-      int readLength = IOUtils.read(is, bytes, 0, 20);
-      assertEquals(15, readLength);
-      assertEquals("1234567890abcde", new String(bytes, UTF_8).substring(0, 
15));
+  @ParameterizedTest
+  @CsvSource({"CRC32,3", "CRC32C,5", "CRC64NVME,4", "SHA1,19", "SHA256,33"})
+  void rejectWrongChecksumLength(TrailerHeader header, int length) throws 
IOException {
+    String value = Base64.getEncoder().encodeToString(new byte[length]);
+    try (UnsignedChunksInputStream stream = wrapContent("0\r\n" + 
header.getHeaderName() + ":" + value + "\r\n\r\n",
+        header)) {
+      OS3Exception error = assertThrows(OS3Exception.class, 
stream::verifyComplete);
+      
assertThat(error.getCode()).isEqualTo(S3ErrorTable.INVALID_REQUEST.getCode());
+      assertThat(error.getErrorMessage()).contains(header.getHeaderName());
     }
   }
 
   @Test
-  void testMultiChunksWithTrailer() throws IOException {
-    //test simple read()
-    try (InputStream is = wrapContent("0a\r\n"
-        + "1234567890\r\n"
-        + "05\r\n"
-        + "abcde\r\n"
-        + "0\r\n"
-        + "x-amz-checksum-crc64nvme:2wstOANdZ/o=\r\n")) {
-      String result = IOUtils.toString(is, UTF_8);
-      assertEquals("1234567890abcde", result);
+  void acceptDocumentedOptionalLineFeed() throws IOException {
+    String body = BODY.replace("x-amz-checksum-crc32:HydN+w==", 
"X-AMZ-CHECKSUM-CRC32:HydN+w==\n");
+    try (UnsignedChunksInputStream stream = wrapContent(body, 
TrailerHeader.CRC32)) {
+      assertThat(IOUtils.toString(stream, UTF_8)).isEqualTo(CONTENT);
     }
+  }
 
-    //test read(byte[],int,int)
-    try (InputStream is = wrapContent("0a\r\n"
-        + "1234567890\r\n"
-        + "05\r\n"
-        + "abcde\r\n"
-        + "0\r\n"
-        + "x-amz-checksum-crc64nvme:2wstOANdZ/o=\n")) {
-      byte[] bytes = new byte[15];
-      IOUtils.read(is, bytes, 0, 15);
-      assertEquals("1234567890abcde", new String(bytes, UTF_8));
+  @Test
+  void chunkLengthDoesNotRequireIntegerRangeOrAllocation() throws IOException {
+    try (UnsignedChunksInputStream stream = wrapContent("80000000\r\na", 
TrailerHeader.CRC32)) {
+      assertThat(stream.read()).isEqualTo('a');
+      assertThrows(OS3Exception.class, stream::read);
     }
+  }
 
-    //test read(byte[],int,int) with length parameter larger than the payload
-    try (InputStream is = wrapContent("0a\r\n"
-        + "1234567890\r\n"
-        + "05\r\n"
-        + "abcde\r\n"
-        + "0\r\n"
-        + "x-amz-checksum-crc64nvme:2wstOANdZ/o=\n")) {
-      byte[] bytes = new byte[20];
-      int readLength = IOUtils.read(is, bytes, 0, 20);
-      assertEquals(15, readLength);
-      assertEquals("1234567890abcde", new String(bytes, UTF_8).substring(0, 
15));
+  private void assertInvalidBody(String body, boolean singleByte) throws 
IOException {
+    try (UnsignedChunksInputStream stream = wrapContent(body, 
TrailerHeader.CRC32)) {
+      OS3Exception error = assertThrows(OS3Exception.class, () -> {
+        if (singleByte) {
+          int value;
+          do {
+            value = stream.read();
+          } while (value != -1);
+        } else {
+          IOUtils.toByteArray(stream);
+        }
+      }, () -> "Accepted malformed body: " + body);
+      
assertThat(error.getCode()).isEqualTo(S3ErrorTable.INVALID_REQUEST.getCode());
+      assertThat(stream.getTrailerChecksum()).isNull();
     }
   }
 
-  private InputStream wrapContent(String content) {
-    return new UnsignedChunksInputStream(
-        new ByteArrayInputStream(content.getBytes(UTF_8)));
+  private UnsignedChunksInputStream wrapContent(String content, TrailerHeader 
header) {
+    return new UnsignedChunksInputStream(new 
ByteArrayInputStream(content.getBytes(UTF_8)), KEY_PATH, header);
   }
-
 }
diff --git 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestObjectPut.java
 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestObjectPut.java
index 13061989758..84469e0e949 100644
--- 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestObjectPut.java
+++ 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestObjectPut.java
@@ -497,8 +497,9 @@ static Stream<Arguments> payloadClassificationCases() {
   void testPayloadClassification(String header, Class<? extends InputStream> 
streamType, boolean sha256,
       boolean hmacSignedStreaming) throws Exception {
     when(headers.getHeaderString(X_AMZ_CONTENT_SHA256)).thenReturn(header);
-    // ECDSA and unsigned trailer modes keep their existing behavior without a 
trailer declaration.
-    if (STREAMING_AWS4_HMAC_SHA256_PAYLOAD_TRAILER.equals(header)) {
+    // ECDSA trailer mode keeps its existing behavior without a trailer 
declaration.
+    if (STREAMING_AWS4_HMAC_SHA256_PAYLOAD_TRAILER.equals(header)
+        || STREAMING_UNSIGNED_PAYLOAD_TRAILER.equals(header)) {
       
when(headers.getHeaderString(X_AMZ_TRAILER)).thenReturn("x-amz-checksum-crc32c");
     }
     for (boolean headerAuth : new boolean[]{true, false}) {
@@ -1158,6 +1159,47 @@ void testDirectoryCreation() throws Exception {
     assertThat(key.isFile()).as("directory").isFalse();
   }
 
+  @Test
+  void testDirectoryCreationWithUnsignedTrailer() throws Exception {
+    configureUnsignedTrailer(0, false);
+
+    assertSucceeds(() -> put(objectEndpoint, FSO_BUCKET_NAME, "dir/",
+        "0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n"));
+    assertThat(fsoBucket.getKey("dir/").isFile()).isFalse();
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"", "0\r\n", 
"0\r\nx-amz-checksum-crc32:AAAAAA==\r\n"})
+  void testDirectoryCreationRejectsIncompleteUnsignedTrailer(String body) {
+    configureUnsignedTrailer(0, false);
+
+    assertErrorResponse(S3ErrorTable.INVALID_REQUEST,
+        () -> put(objectEndpoint, FSO_BUCKET_NAME, "dir/", body));
+    assertThatThrownBy(() -> 
fsoBucket.getKey("dir/")).isInstanceOf(IOException.class);
+  }
+
+  @Test
+  void testDirectoryCreationRequiresUnsignedTrailerDeclaration() {
+    configureUnsignedTrailer(0, false);
+    when(headers.getHeaderString(X_AMZ_TRAILER)).thenReturn(null);
+
+    assertErrorResponse(S3ErrorTable.INVALID_ARGUMENT,
+        () -> put(objectEndpoint, FSO_BUCKET_NAME, "dir/", 
"0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n"));
+    assertThatThrownBy(() -> 
fsoBucket.getKey("dir/")).isInstanceOf(IOException.class);
+  }
+
+  @Test
+  void testDirectoryCreationRejectsUnsignedDecodedLengthMismatch() {
+    configureUnsignedTrailer(5, false);
+    when(objectEndpoint.getContext().getMethod()).thenReturn(HttpMethod.PUT);
+    when(headers.getHeaderString(HttpHeaders.CONTENT_LENGTH)).thenReturn(null);
+    byte[] body = 
"0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n".getBytes(StandardCharsets.UTF_8);
+
+    assertErrorResponse(S3ErrorTable.INVALID_REQUEST,
+        () -> objectEndpoint.put(FSO_BUCKET_NAME, "dir/", new 
ByteArrayInputStream(body)));
+    assertThatThrownBy(() -> 
fsoBucket.getKey("dir/")).isInstanceOf(IOException.class);
+  }
+
   @Test
   void testDirectoryCreationOverFile() throws Exception {
     // GIVEN
@@ -1242,6 +1284,63 @@ private void configureSignedChunksWithTrailer(long 
decodedLength) {
     
when(headers.getHeaderString(X_AMZ_TRAILER)).thenReturn("x-amz-checksum-crc32c");
   }
 
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  void testPutObjectWithUnsignedTrailer(boolean datastream) throws Exception {
+    configureUnsignedTrailer(15, datastream);
+    // Generated by botocore's AwsChunkedWrapper with CRC32 and a 10-byte 
chunk size.
+    String body = 
"a\r\n1234567890\r\n5\r\nabcde\r\n0\r\nx-amz-checksum-crc32:HydN+w==\r\n\r\n";
+
+    assertSucceeds(() -> putObject(body));
+    assertKeyContent(bucket, KEY_NAME, "1234567890abcde");
+  }
+
+  @Test
+  void testPutEmptyObjectWithUnsignedTrailer() throws Exception {
+    configureUnsignedTrailer(0, false);
+
+    assertSucceeds(() -> 
putObject("0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n"));
+    assertKeyContent(bucket, KEY_NAME, "");
+  }
+
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  void testPutObjectRejectsIncompleteUnsignedTrailer(boolean datastream) {
+    configureUnsignedTrailer(CONTENT.length(), datastream);
+
+    assertErrorResponse(S3ErrorTable.INVALID_REQUEST,
+        () -> putObject("a\r\n" + CONTENT + 
"\r\n0\r\nx-amz-checksum-crc32:AAAAAA==\r\n"));
+    assertKeyWasNotCommitted();
+  }
+
+  @Test
+  void testPutEmptyObjectRejectsMissingUnsignedTrailer() {
+    configureUnsignedTrailer(0, false);
+
+    assertErrorResponse(S3ErrorTable.INVALID_REQUEST, () -> 
putObject("0\r\n"));
+    assertKeyWasNotCommitted();
+  }
+
+  @ParameterizedTest
+  @NullAndEmptySource
+  @ValueSource(strings = {" "})
+  void testPutObjectRequiresUnsignedTrailerDeclaration(String declaration) {
+    configureUnsignedTrailer(0, false);
+    when(headers.getHeaderString(X_AMZ_TRAILER)).thenReturn(declaration);
+
+    assertErrorResponse(S3ErrorTable.INVALID_ARGUMENT,
+        () -> putObject("0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n"));
+    assertKeyWasNotCommitted();
+  }
+
+  private void configureUnsignedTrailer(long decodedLength, boolean 
datastream) {
+    
when(headers.getHeaderString(X_AMZ_CONTENT_SHA256)).thenReturn(STREAMING_UNSIGNED_PAYLOAD_TRAILER);
+    
when(headers.getHeaderString(DECODED_CONTENT_LENGTH_HEADER)).thenReturn(String.valueOf(decodedLength));
+    
when(headers.getHeaderString(X_AMZ_TRAILER)).thenReturn("x-amz-checksum-crc32");
+    doReturn(datastream).when(objectEndpoint).isDatastreamEnabled();
+    doReturn(0L).when(objectEndpoint).getDatastreamMinLength();
+  }
+
   private void configureSignedChunkHeaders(long decodedLength) {
     
when(headers.getHeaderString(X_AMZ_CONTENT_SHA256)).thenReturn(STREAMING_AWS4_HMAC_SHA256_PAYLOAD);
     
when(headers.getHeaderString(DECODED_CONTENT_LENGTH_HEADER)).thenReturn(String.valueOf(decodedLength));
diff --git 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestPartUpload.java
 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestPartUpload.java
index 3932e38ff65..edf57b18bec 100644
--- 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestPartUpload.java
+++ 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestPartUpload.java
@@ -30,6 +30,7 @@
 import static org.apache.hadoop.ozone.s3.util.S3Consts.STORAGE_CLASS_HEADER;
 import static 
org.apache.hadoop.ozone.s3.util.S3Consts.STREAMING_AWS4_HMAC_SHA256_PAYLOAD;
 import static 
org.apache.hadoop.ozone.s3.util.S3Consts.STREAMING_AWS4_HMAC_SHA256_PAYLOAD_TRAILER;
+import static 
org.apache.hadoop.ozone.s3.util.S3Consts.STREAMING_UNSIGNED_PAYLOAD_TRAILER;
 import static org.apache.hadoop.ozone.s3.util.S3Consts.X_AMZ_CONTENT_SHA256;
 import static org.apache.hadoop.ozone.s3.util.S3Consts.X_AMZ_TRAILER;
 import static org.assertj.core.api.Assertions.assertThat;
@@ -346,6 +347,40 @@ private void configureSignedChunksWithTrailer(int 
contentLength) throws IOExcept
     
when(headers.getHeaderString(X_AMZ_TRAILER)).thenReturn("x-amz-checksum-crc32c");
   }
 
+  @ParameterizedTest
+  @ValueSource(strings = {"", "1234567890abcde"})
+  void testPartUploadWithUnsignedTrailer(String content) throws Exception {
+    String keyName = UUID.randomUUID().toString();
+    String uploadID = initiateMultipartUpload(rest, OzoneConsts.S3_BUCKET, 
keyName);
+    configureUnsignedTrailer(content.length());
+    // The empty and multi-chunk bodies match botocore's CRC32 encoding.
+    String body = content.isEmpty() ? 
"0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n"
+        : 
"a\r\n1234567890\r\n5\r\nabcde\r\n0\r\nx-amz-checksum-crc32:HydN+w==\r\n\r\n";
+
+    assertSucceeds(() -> put(rest, OzoneConsts.S3_BUCKET, keyName, 1, 
uploadID, body));
+    assertContentLength(uploadID, keyName, content.length());
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"", "1234567890abcde"})
+  void testPartUploadRejectsIncompleteUnsignedTrailer(String content) throws 
Exception {
+    String keyName = UUID.randomUUID().toString();
+    String uploadID = initiateMultipartUpload(rest, OzoneConsts.S3_BUCKET, 
keyName);
+    configureUnsignedTrailer(content.length());
+    String body = (content.isEmpty() ? "" : "f\r\n" + content + "\r\n")
+        + "0\r\nx-amz-checksum-crc32:AAAAAA==\r\n";
+
+    assertErrorResponse(S3ErrorTable.INVALID_REQUEST,
+        () -> put(rest, OzoneConsts.S3_BUCKET, keyName, 1, uploadID, body));
+    assertNoParts(uploadID, keyName);
+  }
+
+  private void configureUnsignedTrailer(int contentLength) {
+    
when(headers.getHeaderString(X_AMZ_CONTENT_SHA256)).thenReturn(STREAMING_UNSIGNED_PAYLOAD_TRAILER);
+    
when(headers.getHeaderString(DECODED_CONTENT_LENGTH_HEADER)).thenReturn(String.valueOf(contentLength));
+    
when(headers.getHeaderString(X_AMZ_TRAILER)).thenReturn("x-amz-checksum-crc32");
+  }
+
   private void configureSignedChunkHeaders(int contentLength) {
     when(headers.getHeaderString(X_AMZ_CONTENT_SHA256))
         .thenReturn(STREAMING_AWS4_HMAC_SHA256_PAYLOAD);
diff --git 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestS3ObjectWriteGuard.java
 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestS3ObjectWriteGuard.java
index 501fd5603f1..25e394c160e 100644
--- 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestS3ObjectWriteGuard.java
+++ 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestS3ObjectWriteGuard.java
@@ -32,8 +32,13 @@
 import 
org.apache.hadoop.ozone.client.OzoneBucketStub.KeyMetadataAwareOutputStream;
 import org.apache.hadoop.ozone.client.io.OzoneDataStreamOutput;
 import org.apache.hadoop.ozone.client.io.OzoneOutputStream;
+import org.apache.hadoop.ozone.s3.MultiDigestInputStream;
+import org.apache.hadoop.ozone.s3.SignedChunksInputStream.TrailerHeader;
+import org.apache.hadoop.ozone.s3.UnsignedChunksInputStream;
 import org.apache.hadoop.ozone.s3.exception.OS3Exception;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
 
 /**
  * Tests for close-time commit guards used by S3 object writes.
@@ -158,6 +163,24 @@ private static S3ObjectWriteGuard newGuard(long 
expectedLength) {
         expectedLength, KEY_PATH);
   }
 
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  void unsignedTrailerFailureBlocksCommitAfterExactLengthRead(boolean 
datastream) throws ReflectiveOperationException {
+    S3ObjectWriteGuard guard = datastream ? new S3ObjectStreamingWriteGuard(
+        new OzoneDataStreamOutput(new 
KeyMetadataAwareByteBufferStreamOutput(Collections.emptyMap()), null),
+        CONTENT.length, KEY_PATH) : newGuard(CONTENT.length);
+    // All decoded bytes are present; the trailer is missing its final blank 
line.
+    byte[] body = 
"7\r\ncontent\r\n0\r\nx-amz-checksum-crc32:AAAAAA==\r\n".getBytes(UTF_8);
+    UnsignedChunksInputStream chunks = new UnsignedChunksInputStream(
+        new ByteArrayInputStream(body), KEY_PATH, TrailerHeader.CRC32);
+    MultiDigestInputStream input = new MultiDigestInputStream(chunks, 
Collections.emptyList());
+
+    OS3Exception failure = assertThrows(OS3Exception.class, () -> 
guard.copyFrom(input, CONTENT.length));
+
+    assertThat(writtenLength(guard)).isEqualTo(CONTENT.length);
+    assertCommitBlockedBy(guard, failure);
+  }
+
   private static InputStream failingInputStream(Throwable failure) {
     return new InputStream() {
       @Override


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to