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

adoroszlai 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 4cf06246596 HDDS-16660. Validate S3 trailing checksums against 
uploaded payloads (#11589)
4cf06246596 is described below

commit 4cf062465961941e15434a59590985f557e4fcb3
Author: KUAN-HAO HUANG <[email protected]>
AuthorDate: Tue Nov 3 21:41:49 2026 +0800

    HDDS-16660. Validate S3 trailing checksums against uploaded payloads 
(#11589)
---
 .../ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java   |  70 ++++++++++
 .../hadoop/ozone/s3/SignedChunksInputStream.java   |  66 +++++++---
 .../apache/hadoop/ozone/s3/TrailerChecksum.java    | 142 +++++++++++++++++++++
 .../hadoop/ozone/s3/UnsignedChunksInputStream.java |  10 +-
 .../hadoop/ozone/s3/endpoint/EndpointBase.java     |  11 +-
 .../hadoop/ozone/s3/endpoint/ObjectEndpoint.java   |  10 +-
 .../ozone/s3/endpoint/S3ObjectWriteGuard.java      |   2 +-
 .../ozone/s3/TestSignedChunksInputStream.java      |  88 ++++++++++++-
 .../hadoop/ozone/s3/TestTrailerChecksum.java       |  96 ++++++++++++++
 .../ozone/s3/TestUnsignedChunkInputStream.java     |  33 +++++
 .../hadoop/ozone/s3/endpoint/TestObjectPut.java    | 105 ++++++++++++++-
 .../hadoop/ozone/s3/endpoint/TestPartUpload.java   |  69 +++++++++-
 .../ozone/s3/endpoint/TestUploadWithStream.java    |   2 +-
 .../ozone/s3/signature/SignatureTestUtils.java     |  20 ++-
 14 files changed, 677 insertions(+), 47 deletions(-)

diff --git 
a/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java
 
b/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java
index 036d34d9234..d42284b08b0 100644
--- 
a/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java
+++ 
b/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java
@@ -121,6 +121,10 @@
 import org.junit.jupiter.params.provider.ValueSource;
 import software.amazon.awssdk.core.ResponseBytes;
 import software.amazon.awssdk.core.ResponseInputStream;
+import software.amazon.awssdk.core.async.AsyncRequestBody;
+import software.amazon.awssdk.core.interceptor.Context;
+import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
+import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
 import software.amazon.awssdk.core.sync.RequestBody;
 import software.amazon.awssdk.http.HttpExecuteRequest;
 import software.amazon.awssdk.http.HttpExecuteResponse;
@@ -135,6 +139,7 @@
 import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest;
 import software.amazon.awssdk.services.s3.model.Bucket;
 import software.amazon.awssdk.services.s3.model.BucketLifecycleConfiguration;
+import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm;
 import software.amazon.awssdk.services.s3.model.CommonPrefix;
 import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
 import 
software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse;
@@ -332,6 +337,71 @@ public void testPutObject() {
     assertEquals("\"37b51d194a7513e45b56f6524f2d51f2\"", 
getObjectResponse.eTag());
   }
 
+  @Test
+  public void testPutDirectoryWithTrailingChecksum() throws Exception {
+    final String bucketName = getBucketName();
+    final String keyName = getKeyName() + "/";
+    createFsoBucket(bucketName);
+    try {
+      List<String> payloadModes = new ArrayList<>();
+      ExecutionInterceptor interceptor = new ExecutionInterceptor() {
+        @Override
+        public void beforeTransmission(Context.BeforeTransmission context, 
ExecutionAttributes executionAttributes) {
+          
payloadModes.add(context.httpRequest().firstMatchingHeader(S3Consts.X_AMZ_CONTENT_SHA256).orElse(null));
+          
assertThat(context.httpRequest().firstMatchingHeader(S3Consts.X_AMZ_TRAILER))
+              .contains("x-amz-checksum-crc32c");
+        }
+      };
+
+      s3Client.putObject(b -> 
b.bucket(bucketName).key(keyName).checksumAlgorithm(ChecksumAlgorithm.CRC32_C)
+          .overrideConfiguration(o -> o.addPlugin(c -> c.overrideConfiguration(
+              overrides -> overrides.addExecutionInterceptor(interceptor)))), 
RequestBody.empty());
+
+      
assertThat(payloadModes).isNotEmpty().containsOnly(S3Consts.STREAMING_AWS4_HMAC_SHA256_PAYLOAD_TRAILER);
+      try (OzoneClient ozoneClient = cluster.newClient()) {
+        OzoneBucket bucket = 
ozoneClient.getObjectStore().getS3Bucket(bucketName);
+        assertThat(bucket.getFileStatus(keyName).isDirectory()).isTrue();
+      }
+    } finally {
+      s3Client.deleteObject(b -> b.bucket(bucketName).key(keyName));
+      deleteFsoBucket(bucketName);
+    }
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"", "bar"})
+  public void testPutObjectAsyncWithTrailingChecksum(String content) throws 
Exception {
+    final String bucketName = getBucketName();
+    final String keyName = getKeyName();
+    s3Client.createBucket(b -> b.bucket(bucketName));
+
+    PutObjectResponse response = s3AsyncClient.putObject(b -> 
b.bucket(bucketName).key(keyName)
+            .checksumAlgorithm(ChecksumAlgorithm.CRC32_C), 
AsyncRequestBody.fromString(content))
+        .get(30, TimeUnit.SECONDS);
+
+    assertThat(response.eTag()).isNotEmpty();
+    assertThat(s3Client.getObjectAsBytes(b -> 
b.bucket(bucketName).key(keyName)).asUtf8String()).isEqualTo(content);
+  }
+
+  @Test
+  public void testUploadPartAsyncWithTrailingChecksum() throws Exception {
+    final String bucketName = getBucketName();
+    final String keyName = getKeyName();
+    final String content = "part1data";
+    s3Client.createBucket(b -> b.bucket(bucketName));
+    String uploadId = s3Client.createMultipartUpload(b -> 
b.bucket(bucketName).key(keyName)).uploadId();
+
+    UploadPartResponse response = s3AsyncClient.uploadPart(b -> 
b.bucket(bucketName).key(keyName).uploadId(uploadId)
+            .partNumber(1).checksumAlgorithm(ChecksumAlgorithm.CRC32_C), 
AsyncRequestBody.fromString(content))
+        .get(30, TimeUnit.SECONDS);
+
+    CompletedPart part = 
CompletedPart.builder().partNumber(1).eTag(response.eTag()).build();
+    s3Client.completeMultipartUpload(b -> 
b.bucket(bucketName).key(keyName).uploadId(uploadId)
+        
.multipartUpload(CompletedMultipartUpload.builder().parts(part).build()));
+
+    assertThat(s3Client.getObjectAsBytes(b -> 
b.bucket(bucketName).key(keyName)).asUtf8String()).isEqualTo(content);
+  }
+
   @ParameterizedTest
   @ValueSource(strings = {"follower-stale", "follower-linearizable",
       "leader-only"})
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 bf2e678c3d3..d077d10b808 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
@@ -29,6 +29,8 @@
 import java.util.Objects;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
+import java.util.zip.CRC32;
+import java.util.zip.CRC32C;
 import javax.xml.bind.DatatypeConverter;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.lang3.StringUtils;
@@ -67,7 +69,8 @@
  * <p>
  * If a {@link ChunksValidator} is supplied, the signature of each chunk is 
verified (in real time, without
  * buffering the whole chunk) as the payload is read. Without a validator the 
stream only strips the chunk
- * signatures format and returns the payload. Trailer contents are consumed 
without validation.
+ * signature framing and returns the payload. When a checksum trailer is 
declared, its framing and payload
+ * checksum are verified even without a validator; chunk and trailer 
signatures are only shape-checked in that case.
  * </p>
  *
  * Reference:
@@ -110,6 +113,7 @@ public class SignedChunksInputStream extends InputStream {
 
   /** Checksum header declared by x-amz-trailer, or NONE for a regular signed 
stream. */
   private final TrailerHeader trailerHeader;
+  private final TrailerChecksum trailerChecksum;
 
   /**
    * Size of the chunk payload. If zero, the signature line should be parsed to
@@ -144,6 +148,25 @@ String getHeaderName() {
       return headerName;
     }
 
+    TrailerChecksum newChecksum() {
+      switch (this) {
+      case NONE:
+        return null;
+      case CRC32:
+        return TrailerChecksum.of(new CRC32(), checksumLength);
+      case CRC32C:
+        return TrailerChecksum.of(new CRC32C(), checksumLength);
+      case CRC64NVME:
+        return TrailerChecksum.of(new TrailerChecksum.Crc64Nvme(), 
checksumLength);
+      case SHA1:
+        return TrailerChecksum.of(DigestUtils.getSha1Digest());
+      case SHA256:
+        return TrailerChecksum.of(DigestUtils.getSha256Digest());
+      default:
+        throw new IllegalStateException("Unsupported trailer checksum: " + 
this);
+      }
+    }
+
     byte[] decodeValue(String value, String resource) {
       try {
         byte[] checksum = Base64.getDecoder().decode(value);
@@ -192,6 +215,7 @@ public SignedChunksInputStream(InputStream inputStream, 
String keyPath, TrailerH
     originalStream = inputStream;
     this.keyPath = keyPath;
     this.trailerHeader = Objects.requireNonNull(trailerHeader, "trailerHeader 
== null");
+    this.trailerChecksum = trailerHeader.newChecksum();
   }
 
   /**
@@ -317,10 +341,11 @@ private void stopAtUnexpectedEof() throws IOException {
 
   /**
    * Complete verification after the caller has consumed the decoded content 
length. This verifies the terminating
-   * zero-byte chunk and rejects a decoded length that ends in the middle of a 
chunk. No-op without a validator.
+   * zero-byte chunk and rejects a decoded length that ends in the middle of a 
chunk.
+   * Required when verifying signatures or a declared trailer checksum.
    */
   public void verifyComplete() throws IOException {
-    if (validator == null || isFinalChunkEncountered) {
+    if (!requiresCompletion() || isFinalChunkEncountered) {
       return;
     }
     if (read() != -1) {
@@ -328,13 +353,17 @@ public void verifyComplete() throws IOException {
     }
   }
 
+  private boolean requiresCompletion() {
+    return validator != null || trailerChecksum != null;
+  }
+
   /**
    * A verified stream must end with the terminating 0-byte chunk. Reaching 
EOF before it means the
-   * body was truncated, so the payload read so far was never fully 
authenticated. Without a validator
-   * the stream keeps its lenient behavior.
+   * body was truncated, so the payload could not be fully verified. 
Unverified streams without a
+   * declared trailer keep their lenient behavior.
    */
   private void checkNotTruncated() throws IOException {
-    if (validator != null) {
+    if (requiresCompletion()) {
       throw invalidBody("Chunked stream ended before the terminating 0-byte 
chunk");
     }
   }
@@ -342,7 +371,7 @@ private void checkNotTruncated() throws IOException {
   private void readChunkTerminator() throws IOException {
     int carriageReturn = originalStream.read();
     int lineFeed = originalStream.read();
-    if (validator != null && (carriageReturn != '\r' || lineFeed != '\n')) {
+    if (requiresCompletion() && (carriageReturn != '\r' || lineFeed != '\n')) {
       throw invalidBody("Invalid chunk data terminator");
     }
   }
@@ -372,15 +401,8 @@ private int readContentLengthFromHeader() throws 
IOException {
     return Integer.parseInt(matcher.group(1), 16);
   }
 
+  /** Check framing, authenticate the trailer if possible, then compare its 
checksum after the final terminator. */
   private void validateTrailer() throws IOException {
-    if (validator == null) {
-      // Consume trailers through their blank-line terminator, tolerating EOF 
as for unverified chunks.
-      String line;
-      do {
-        line = readLine(true);
-      } while (StringUtils.isNotEmpty(line));
-      return;
-    }
     String trailerLine = readLine(true);
     if (trailerLine == null || trailerLine.isEmpty()) {
       throw invalidBody("Missing trailing checksum header");
@@ -403,7 +425,10 @@ private void validateTrailer() throws IOException {
     if (!matcher.matches()) {
       throw invalidBody("Invalid trailing signature");
     }
-    validator.validateTrailer(matcher.group(1), DigestUtils.sha256Hex(name + 
":" + value + "\n"));
+    if (validator != null) {
+      validator.validateTrailer(matcher.group(1), DigestUtils.sha256Hex(name + 
":" + value + "\n"));
+    }
+    byte[] expected = trailerHeader.decodeValue(value, keyPath);
     // AWS SDKs terminate the trailer section with a blank line after the 
signature.
     if (!"".equals(readLine(true))) {
       throw invalidBody("Invalid trailer terminator");
@@ -411,6 +436,7 @@ private void validateTrailer() throws IOException {
     if (originalStream.read() != -1) {
       throw invalidBody("Unexpected data after trailing signature");
     }
+    trailerChecksum.verify(expected, keyPath);
   }
 
   private String readLine(boolean trailingHeader) throws IOException {
@@ -419,7 +445,7 @@ private String readLine(boolean trailingHeader) throws 
IOException {
     while (true) {
       int current = originalStream.read();
       if (current == -1) {
-        if (trailingHeader && validator != null && line.length() > 0) {
+        if (trailingHeader && requiresCompletion() && line.length() > 0) {
           throw invalidBody("Truncated trailing header");
         }
         if (!trailingHeader) {
@@ -440,12 +466,18 @@ private String readLine(boolean trailingHeader) throws 
IOException {
   }
 
   private void updateDigest(byte b) {
+    if (trailerChecksum != null) {
+      trailerChecksum.update(b);
+    }
     if (chunkDigest != null) {
       chunkDigest.update(b);
     }
   }
 
   private void updateDigest(byte[] b, int off, int len) {
+    if (trailerChecksum != null) {
+      trailerChecksum.update(b, off, len);
+    }
     if (chunkDigest != null) {
       chunkDigest.update(b, off, len);
     }
diff --git 
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/TrailerChecksum.java
 
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/TrailerChecksum.java
new file mode 100644
index 00000000000..781982e8437
--- /dev/null
+++ 
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/TrailerChecksum.java
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.s3;
+
+import java.security.MessageDigest;
+import java.util.zip.Checksum;
+import org.apache.hadoop.ozone.s3.exception.S3ErrorTable;
+
+/** Incrementally verifies a checksum over the decoded payload, independently 
of chunk signatures. */
+abstract class TrailerChecksum {
+  private TrailerChecksum() {
+  }
+
+  abstract void update(byte value);
+
+  abstract void update(byte[] bytes, int offset, int length);
+
+  abstract byte[] finish();
+
+  final void verify(byte[] expected, String resource) {
+    if (!MessageDigest.isEqual(expected, finish())) {
+      throw S3ErrorTable.newError(S3ErrorTable.BAD_DIGEST, resource);
+    }
+  }
+
+  static TrailerChecksum of(MessageDigest digest) {
+    return new TrailerChecksum() {
+      @Override
+      void update(byte value) {
+        digest.update(value);
+      }
+
+      @Override
+      void update(byte[] bytes, int offset, int length) {
+        digest.update(bytes, offset, length);
+      }
+
+      @Override
+      byte[] finish() {
+        return digest.digest();
+      }
+    };
+  }
+
+  static TrailerChecksum of(Checksum checksum, int checksumLength) {
+    return new TrailerChecksum() {
+      @Override
+      void update(byte value) {
+        checksum.update(value);
+      }
+
+      @Override
+      void update(byte[] bytes, int offset, int length) {
+        checksum.update(bytes, offset, length);
+      }
+
+      @Override
+      byte[] finish() {
+        byte[] actual = new byte[checksumLength];
+        long value = checksum.getValue();
+        for (int i = actual.length - 1; i >= 0; i--) {
+          actual[i] = (byte) value;
+          value >>>= Byte.SIZE;
+        }
+        return actual;
+      }
+    };
+  }
+
+  /** CRC-64/NVME: reflected polynomial 0x9a6c9329ac4bc9b5, initial value and 
final XOR all ones. */
+  static final class Crc64Nvme implements Checksum {
+    private static final long[][] TABLE = createTable();
+    private long crc = -1L;
+
+    private static long[][] createTable() {
+      long[][] table = new long[8][256];
+      for (int i = 0; i < table[0].length; i++) {
+        long value = i;
+        for (int bit = 0; bit < Byte.SIZE; bit++) {
+          value = (value >>> 1) ^ ((value & 1) == 0 ? 0 : 0x9a6c9329ac4bc9b5L);
+        }
+        table[0][i] = value;
+      }
+      for (int slice = 1; slice < table.length; slice++) {
+        for (int i = 0; i < table[slice].length; i++) {
+          long value = table[slice - 1][i];
+          table[slice][i] = table[0][(int) value & 0xff] ^ (value >>> 
Byte.SIZE);
+        }
+      }
+      return table;
+    }
+
+    @Override
+    public void update(int value) {
+      crc = TABLE[0][((int) crc ^ value) & 0xff] ^ (crc >>> Byte.SIZE);
+    }
+
+    @Override
+    public void update(byte[] bytes, int offset, int length) {
+      int end = offset + length;
+      int i = offset;
+      for (; i <= end - Long.BYTES; i += Long.BYTES) {
+        crc = TABLE[7][((int) crc ^ bytes[i]) & 0xff]
+            ^ TABLE[6][((int) (crc >>> 8) ^ bytes[i + 1]) & 0xff]
+            ^ TABLE[5][((int) (crc >>> 16) ^ bytes[i + 2]) & 0xff]
+            ^ TABLE[4][((int) (crc >>> 24) ^ bytes[i + 3]) & 0xff]
+            ^ TABLE[3][((int) (crc >>> 32) ^ bytes[i + 4]) & 0xff]
+            ^ TABLE[2][((int) (crc >>> 40) ^ bytes[i + 5]) & 0xff]
+            ^ TABLE[1][((int) (crc >>> 48) ^ bytes[i + 6]) & 0xff]
+            ^ TABLE[0][((int) (crc >>> 56) ^ bytes[i + 7]) & 0xff];
+      }
+      for (; i < end; i++) {
+        update(bytes[i]);
+      }
+    }
+
+    @Override
+    public long getValue() {
+      return ~crc;
+    }
+
+    @Override
+    public void reset() {
+      crc = -1L;
+    }
+  }
+}
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 3f581758bb8..975f653e89f 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
@@ -57,8 +57,8 @@
  * </p>
  *
  * <p>
- * This stream validates chunk and trailer framing, including the checksum 
encoding and length.
- * It does not compare the trailer checksum with the payload.
+ * This stream validates chunk and trailer framing, including the checksum 
encoding and length,
+ * and compares the trailer checksum with the decoded payload before reporting 
completion.
  * </p>
  *
  * Reference:
@@ -81,6 +81,7 @@ public class UnsignedChunksInputStream extends InputStream {
   private final InputStream originalStream;
   private final String keyPath;
   private final TrailerHeader trailerHeader;
+  private final TrailerChecksum payloadChecksum;
   private long remainingData;
   private boolean isFinalChunkEncountered;
   private byte[] trailerChecksum;
@@ -92,6 +93,7 @@ public UnsignedChunksInputStream(InputStream inputStream, 
String keyPath, Traile
     if (trailerHeader == TrailerHeader.NONE) {
       throw new IllegalArgumentException("Unsigned chunked uploads require a 
checksum trailer");
     }
+    this.payloadChecksum = trailerHeader.newChecksum();
   }
 
   @Override
@@ -103,6 +105,7 @@ public int read() throws IOException {
     if (value == -1) {
       throw invalidBody("Truncated chunk payload");
     }
+    payloadChecksum.update((byte) value);
     remainingData--;
     endChunkIfComplete();
     return value;
@@ -124,6 +127,7 @@ public int read(byte[] b, int off, int len) throws 
IOException {
       if (readLength == -1) {
         throw invalidBody("Truncated chunk payload");
       }
+      payloadChecksum.update(b, off + totalReadBytes, readLength);
       totalReadBytes += readLength;
       remainingData -= readLength;
       endChunkIfComplete();
@@ -170,6 +174,7 @@ public byte[] getTrailerChecksum() {
     return trailerChecksum == null ? null : trailerChecksum.clone();
   }
 
+  /** Check framing and decode the value, then compare the checksum only after 
the final terminator. */
   private void readTrailer() throws IOException {
     String trailer = readLine();
     int separator = trailer.indexOf(':');
@@ -187,6 +192,7 @@ private void readTrailer() throws IOException {
     if (originalStream.read() != -1) {
       throw invalidBody("Unexpected data after trailing checksum");
     }
+    payloadChecksum.verify(checksum, keyPath);
     trailerChecksum = checksum;
   }
 
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 e9f7d751899..a017f6af6e9 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
@@ -879,6 +879,15 @@ protected static int parsePartNumberMarker(String 
partNumberMarker) {
    */
   protected S3ChunkInputStreamInfo getS3ChunkInputStreamInfo(
       InputStream body, long contentLength, String amzDecodedLength, String 
keyPath) throws OS3Exception {
+    return getS3ChunkInputStreamInfo(body, contentLength, amzDecodedLength, 
keyPath, true);
+  }
+
+  /**
+   * Same as {@link #getS3ChunkInputStreamInfo(InputStream, long, String, 
String)}. Pass {@code opensKey = false}
+   * when no key is opened for the payload, which then needs no derived key 
from OM.
+   */
+  protected S3ChunkInputStreamInfo getS3ChunkInputStreamInfo(InputStream body, 
long contentLength,
+      String amzDecodedLength, String keyPath, boolean opensKey) throws 
OS3Exception {
     final String amzContentSha256Header = 
validateSignatureHeader(getHeaders(), keyPath, signatureInfo.isSignPayload());
     final S3ContentSha256Type payloadType = 
S3ContentSha256Type.fromHeaderValue(amzContentSha256Header);
     final InputStream chunkInputStream;
@@ -915,7 +924,7 @@ protected S3ChunkInputStreamInfo getS3ChunkInputStreamInfo(
     // Header auth only: for a presigned (query) request the payload hash is 
not part of the signed
     // canonical request, so its seed signature cannot start the chunk 
signature chain.
     boolean verifyChunkSignature = signatureInfo.isSignPayload() && 
payloadType.isHmacSignedStreaming();
-    if (verifyChunkSignature && 
OzoneSecurityUtil.isSecurityEnabled(getOzoneConfiguration())
+    if (opensKey && verifyChunkSignature && 
OzoneSecurityUtil.isSecurityEnabled(getOzoneConfiguration())
         && 
!OzoneManagerVersion.S3_DERIVED_KEY.isSupportedBy(getClientProtocol().getOmVersion()))
 {
       OS3Exception ex = newError(S3ErrorTable.NOT_IMPLEMENTED, keyPath);
       ex.setErrorMessage("The connected Ozone Manager does not support signed 
chunk verification.");
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 28241c77274..2a426938edf 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
@@ -41,6 +41,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_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.TAG_COUNT_HEADER;
 import static org.apache.hadoop.ozone.s3.util.S3Consts.TAG_DIRECTIVE_HEADER;
@@ -103,7 +104,6 @@
 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;
@@ -260,11 +260,13 @@ 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);
+        if (STREAMING_UNSIGNED_PAYLOAD_TRAILER.equals(amzContentSha256)
+            || 
STREAMING_AWS4_HMAC_SHA256_PAYLOAD_TRAILER.equals(amzContentSha256)) {
+          // No key is opened for a directory: verify trailer framing and 
checksum without a chunk signing key.
+          S3ChunkInputStreamInfo info = getS3ChunkInputStreamInfo(body, 
length, amzDecodedLength, keyPath, false);
           multiDigestInputStream = info.getMultiDigestInputStream();
           validateContentLength(info.getEffectiveLength(), 0, keyPath).run();
-          ((UnsignedChunksInputStream) 
multiDigestInputStream.getWrappedStream()).verifyComplete();
+          S3ObjectWriteGuard.verifyChunksComplete(multiDigestInputStream);
         }
         getClientProtocol()
             .createDirectory(volume.getName(), bucketName, keyPath);
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 2be6ae64480..969dfb998dd 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
@@ -147,7 +147,7 @@ long copyFrom(InputStream body, int bufferSize) throws 
IOException {
     return writtenLength;
   }
 
-  private static void verifyChunksComplete(InputStream body) throws 
IOException {
+  static void verifyChunksComplete(InputStream body) throws IOException {
     InputStream chunks = body instanceof MultiDigestInputStream
         ? ((MultiDigestInputStream) body).getWrappedStream() : body;
     if (chunks instanceof SignedChunksInputStream) {
diff --git 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/TestSignedChunksInputStream.java
 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/TestSignedChunksInputStream.java
index 84b948ead22..68579622a28 100644
--- 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/TestSignedChunksInputStream.java
+++ 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/TestSignedChunksInputStream.java
@@ -27,6 +27,8 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.Arrays;
+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;
@@ -35,8 +37,10 @@
 import org.apache.hadoop.ozone.s3.signature.SignatureTestUtils;
 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.EmptySource;
+import org.junit.jupiter.params.provider.MethodSource;
 import org.junit.jupiter.params.provider.NullAndEmptySource;
 import org.junit.jupiter.params.provider.ValueSource;
 
@@ -87,11 +91,14 @@ void testEmptyFile() throws IOException {
       "false, false, true", "false, true, true", "true, false, true", "true, 
true, true"})
   void consumesFramingWithoutValidator(boolean buffered, boolean empty, 
boolean trailer) throws IOException {
     String payload = empty ? "" : "data";
+    String checksum = empty ? "AAAAAA==" : "rth90Q==";
     String body = (empty ? "" : "4;chunk-signature=" + FAKE_SIGNATURE + 
"\r\ndata\r\n")
         + "0;chunk-signature=" + FAKE_SIGNATURE + "\r\n"
-        + (trailer ? 
"x-amz-checksum-crc32c:sOO8/Q==\r\nx-amz-trailer-signature:" + FAKE_SIGNATURE + 
"\r\n" : "")
+        + (trailer ? "x-amz-checksum-crc32c:" + checksum + 
"\r\nx-amz-trailer-signature:"
+            + FAKE_SIGNATURE + "\r\n" : "")
         + "\r\n";
-    ByteArrayInputStream original = new ByteArrayInputStream((body + 
"after-trailer").getBytes(UTF_8));
+    String extra = trailer ? "" : "after-trailer";
+    ByteArrayInputStream original = new ByteArrayInputStream((body + 
extra).getBytes(UTF_8));
     try (SignedChunksInputStream stream = new SignedChunksInputStream(
         original, KEY_PATH, trailer ? TrailerHeader.CRC32C : 
TrailerHeader.NONE)) {
       if (buffered) {
@@ -102,7 +109,7 @@ void consumesFramingWithoutValidator(boolean buffered, 
boolean empty, boolean tr
         }
       }
       assertThat(stream.read()).isEqualTo(-1);
-      assertThat(IOUtils.toString(original, UTF_8)).isEqualTo("after-trailer");
+      assertThat(IOUtils.toString(original, UTF_8)).isEqualTo(extra);
     }
   }
 
@@ -117,14 +124,13 @@ void consumesFramingWithoutValidator(boolean buffered, 
boolean empty, boolean tr
       "malformed-header\r\nx-amz-trailer-signature:" + TRAILER_SIGNATURE + 
"\r\n\r\n",
       "x-amz-checksum-sha256:checksum\r\nx-amz-trailer-signature:" + 
TRAILER_SIGNATURE + "\r\n\r\n"
   })
-  void toleratesMalformedTrailersWithoutValidator(String trailers) throws 
IOException {
+  void rejectsMalformedTrailersWithoutValidator(String trailers) throws 
IOException {
     String body = "4;chunk-signature=" + FAKE_SIGNATURE + "\r\ndata\r\n"
         + "0;chunk-signature=" + FAKE_SIGNATURE + "\r\n" + trailers;
     ByteArrayInputStream original = new 
ByteArrayInputStream(body.getBytes(UTF_8));
     try (SignedChunksInputStream stream = new 
SignedChunksInputStream(original, KEY_PATH, TrailerHeader.CRC32C)) {
-      assertThat(IOUtils.toString(stream, UTF_8)).isEqualTo("data");
-      assertThat(stream.read()).isEqualTo(-1);
-      assertThat(original.available()).isZero();
+      OS3Exception error = assertThrows(OS3Exception.class, () -> 
IOUtils.toByteArray(stream));
+      
assertThat(error.getCode()).isEqualTo(S3ErrorTable.INVALID_REQUEST.getCode());
     }
   }
 
@@ -331,6 +337,74 @@ void testMultiChunksWithTrailer() throws Exception {
     }
   }
 
+  static Stream<Arguments> checksumCases() {
+    return Stream.of(
+        Arguments.of(TrailerHeader.CRC32, "y/Q5Jg=="),
+        Arguments.of(TrailerHeader.CRC32C, "4waSgw=="),
+        Arguments.of(TrailerHeader.CRC64NVME, "rosUhgp5mIg="),
+        Arguments.of(TrailerHeader.SHA1, "98O8HYCOBHMq32eZZczDTKeuNEE="),
+        Arguments.of(TrailerHeader.SHA256, 
"FeKw08M4keuw8e9gnsQZQgwg4yDOlMZfvIwzEkSOsiU="))
+        .flatMap(args -> Stream.of(false, true).flatMap(buffered -> 
Stream.of(false, true)
+            .map(verify -> Arguments.of(args.get()[0], args.get()[1], 
buffered, verify))));
+  }
+
+  @ParameterizedTest
+  @MethodSource("checksumCases")
+  void verifiesPayloadChecksum(TrailerHeader header, String value, boolean 
buffered, boolean verify)
+      throws IOException {
+    String payload = "123456789";
+    for (boolean correct : new boolean[]{true, false}) {
+      byte[] checksum = Base64.getDecoder().decode(value);
+      if (!correct) {
+        checksum[0] ^= 1;
+      }
+      String body = SignatureTestUtils.signedChunkedBodyWithTrailer(
+          new String[]{"1234", "56", "789"}, header.getHeaderName(), 
Base64.getEncoder().encodeToString(checksum));
+      try (SignedChunksInputStream stream = new SignedChunksInputStream(
+          new ByteArrayInputStream(body.getBytes(UTF_8)), KEY_PATH, header)) {
+        if (verify) {
+          stream.attachValidator(new 
ChunksValidator(SignatureTestUtils.signingKey(),
+              SignatureTestUtils.signatureInfo().getDateTime(), 
SignatureTestUtils.signatureInfo().getCredentialScope(),
+              SignatureTestUtils.signatureInfo().getSignature(), KEY_PATH));
+        }
+        if (buffered) {
+          byte[] actual = new byte[payload.length() + 4];
+          Arrays.fill(actual, (byte) '!');
+          assertThat(stream.read(actual, 2, 5)).isEqualTo(5);
+          assertThat(stream.read(actual, 7, 4)).isEqualTo(4);
+          assertThat(actual).isEqualTo(("!!" + payload + 
"!!").getBytes(UTF_8));
+        } else {
+          for (char expected : payload.toCharArray()) {
+            assertThat(stream.read()).isEqualTo(expected);
+          }
+        }
+        if (correct) {
+          stream.verifyComplete();
+          assertThat(stream.read()).isEqualTo(-1);
+          stream.verifyComplete();
+        } else {
+          OS3Exception error = assertThrows(OS3Exception.class, 
stream::verifyComplete);
+          
assertThat(error.getCode()).isEqualTo(S3ErrorTable.BAD_DIGEST.getCode());
+        }
+      }
+    }
+  }
+
+  @ParameterizedTest
+  @EmptySource
+  @ValueSource(strings = {"not-base64", "AAAA", "AAAAAAAAAAA="})
+  void rejectsMalformedChecksumWithValidSignature(String value) throws 
IOException {
+    String body = SignatureTestUtils.signedChunkedBodyWithTrailer("", 
"x-amz-checksum-crc32c", value);
+    try (SignedChunksInputStream stream = new SignedChunksInputStream(
+        new ByteArrayInputStream(body.getBytes(UTF_8)), KEY_PATH, 
TrailerHeader.CRC32C)) {
+      stream.attachValidator(new 
ChunksValidator(SignatureTestUtils.signingKey(),
+          SignatureTestUtils.signatureInfo().getDateTime(), 
SignatureTestUtils.signatureInfo().getCredentialScope(),
+          SignatureTestUtils.signatureInfo().getSignature(), KEY_PATH));
+      OS3Exception error = assertThrows(OS3Exception.class, 
stream::verifyComplete);
+      
assertThat(error.getCode()).isEqualTo(S3ErrorTable.INVALID_REQUEST.getCode());
+    }
+  }
+
   @Test
   void verifiesTrailerSignature() throws Exception {
     String body = trailerBody();
diff --git 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/TestTrailerChecksum.java
 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/TestTrailerChecksum.java
new file mode 100644
index 00000000000..f27ce801474
--- /dev/null
+++ 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/TestTrailerChecksum.java
@@ -0,0 +1,96 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.s3;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.Base64;
+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.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/** Tests payload checksums with independent AWS CRT and hashlib reference 
values. */
+class TestTrailerChecksum {
+
+  @ParameterizedTest
+  @CsvSource({"CRC32,y/Q5Jg==,AAAAAA==",
+      "CRC32C,4waSgw==,AAAAAA==",
+      "CRC64NVME,rosUhgp5mIg=,AAAAAAAAAAA=",
+      "SHA1,98O8HYCOBHMq32eZZczDTKeuNEE=,2jmj7l5rSw0yVb/vlWAYkK/YBwk=",
+      
"SHA256,FeKw08M4keuw8e9gnsQZQgwg4yDOlMZfvIwzEkSOsiU=,47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="})
+  void verifiesKnownVectorsAcrossReadBoundaries(TrailerHeader header, String 
expected, String empty) {
+    header.newChecksum().verify(Base64.getDecoder().decode(empty), "key");
+    byte[] payload = "!123456789!".getBytes(UTF_8);
+    for (int split = 0; split <= 9; split++) {
+      TrailerChecksum checksum = header.newChecksum();
+      checksum.update(payload, 1, split);
+      for (int i = 1 + split; i <= 9; i++) {
+        checksum.update(payload[i]);
+      }
+      checksum.verify(Base64.getDecoder().decode(expected), "key");
+    }
+
+    TrailerChecksum wrong = header.newChecksum();
+    wrong.update(payload, 0, payload.length);
+    OS3Exception error = assertThrows(OS3Exception.class,
+        () -> wrong.verify(Base64.getDecoder().decode(expected), "key"));
+    assertThat(error.getCode()).isEqualTo(S3ErrorTable.BAD_DIGEST.getCode());
+  }
+
+  @Test
+  void crc64MatchesAwsVectorsAndResets() {
+    TrailerChecksum.Crc64Nvme checksum = new TrailerChecksum.Crc64Nvme();
+    byte[] payload = new byte[32];
+    checksum.update(payload, 0, payload.length);
+    assertThat(checksum.getValue()).isEqualTo(0xcf3473434d4ecf3bL);
+    checksum.reset();
+    assertThat(checksum.getValue()).isZero();
+    for (int i = 0; i < payload.length; i++) {
+      payload[i] = (byte) i;
+    }
+    checksum.update(payload, 0, payload.length);
+    assertThat(checksum.getValue()).isEqualTo(0xb9d9d4a8492cbd7fL);
+  }
+
+  @ParameterizedTest
+  @ValueSource(ints = {0, 1, 7, 8, 9, 15, 16, 17, 31, 32, 33, 255, 256, 257, 
8192, 8199})
+  void crc64BulkUpdatesMatchSingleBytes(int length) {
+    byte[] payload = new byte[length + 8];
+    for (int i = 0; i < payload.length; i++) {
+      payload[i] = (byte) (i * 131 + 17);
+    }
+    for (int offset = 0; offset < 8; offset++) {
+      TrailerChecksum.Crc64Nvme expected = new TrailerChecksum.Crc64Nvme();
+      for (int i = offset; i < offset + length; i++) {
+        expected.update(payload[i]);
+      }
+      for (int split = 0; split <= Math.min(length, 16); split++) {
+        TrailerChecksum.Crc64Nvme actual = new TrailerChecksum.Crc64Nvme();
+        actual.update(payload, offset, split);
+        actual.update(payload, offset + split, length - split);
+        assertThat(actual.getValue()).isEqualTo(expected.getValue());
+      }
+    }
+  }
+}
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 9d1c79b95be..25c44c2609c 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
@@ -86,6 +86,39 @@ void readAcrossChunks(int bufferSize) throws IOException {
     }
   }
 
+  @ParameterizedTest
+  @CsvSource({"CRC32,y/Q5Jg==",
+      "CRC32C,4waSgw==",
+      "CRC64NVME,rosUhgp5mIg=",
+      "SHA1,98O8HYCOBHMq32eZZczDTKeuNEE=",
+      "SHA256,FeKw08M4keuw8e9gnsQZQgwg4yDOlMZfvIwzEkSOsiU="})
+  void verifiesPayloadChecksum(TrailerHeader header, String value) throws 
IOException {
+    for (boolean singleByte : new boolean[]{false, true}) {
+      for (boolean correct : new boolean[]{true, false}) {
+        String payload = correct ? "123456789" : "123456780";
+        String body = "4\r\n" + payload.substring(0, 4) + "\r\n5\r\n" + 
payload.substring(4)
+            + "\r\n0\r\n" + header.getHeaderName() + ":" + value + "\r\n\r\n";
+        try (UnsignedChunksInputStream stream = wrapContent(body, header)) {
+          if (singleByte) {
+            for (char expected : payload.toCharArray()) {
+              assertThat(stream.read()).isEqualTo(expected);
+            }
+          } else {
+            assertThat(IOUtils.readFully(stream, 
payload.length())).isEqualTo(payload.getBytes(UTF_8));
+          }
+          if (correct) {
+            stream.verifyComplete();
+            
assertThat(stream.getTrailerChecksum()).isEqualTo(Base64.getDecoder().decode(value));
+          } else {
+            OS3Exception error = assertThrows(OS3Exception.class, 
stream::verifyComplete);
+            
assertThat(error.getCode()).isEqualTo(S3ErrorTable.BAD_DIGEST.getCode());
+            assertThat(stream.getTrailerChecksum()).isNull();
+          }
+        }
+      }
+    }
+  }
+
   @Test
   void exactLengthReadStillRequiresCompletion() throws IOException {
     ByteArrayInputStream original = new 
ByteArrayInputStream(BODY.getBytes(UTF_8));
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 5d385a378a3..072741027d3 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
@@ -343,9 +343,8 @@ void testPutObjectWithValidSignedChunks() throws Exception {
   void testPutObjectWithValidSignedChunksAndTrailer(String content) throws 
Exception {
     configureSignedChunksWithTrailer(content.length());
 
-    // The trailer value is covered by the HMAC; checksum calculation is 
outside this test.
     assertSucceeds(() -> putObject(signedChunkedBodyWithTrailer(
-        content, "x-amz-checksum-crc32c", "sOO8/Q==")));
+        content, "x-amz-checksum-crc32c", content.isEmpty() ? "AAAAAA==" : 
"KAwGng==")));
 
     assertThat(assertKeyContent(bucket, KEY_NAME, 
content).getDataSize()).isEqualTo(content.length());
   }
@@ -1216,10 +1215,17 @@ void testDirectoryCreation() throws Exception {
   }
 
   @ParameterizedTest
-  @ValueSource(booleans = {false, true})
-  void testDirectoryCreationWithUnsignedTrailer(boolean hasContentLength) 
throws Exception {
-    configureUnsignedTrailer(0, false);
-    String body = "0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n";
+  @CsvSource({"false, false", "false, true", "true, false", "true, true"})
+  void testDirectoryCreationWithTrailer(boolean signed, boolean 
hasContentLength) throws Exception {
+    String body;
+    if (signed) {
+      configureSignedChunksWithTrailer(0);
+      
when(headers.getHeaderString(X_AMZ_TRAILER)).thenReturn("x-amz-checksum-crc32");
+      body = signedChunkedBodyWithTrailer("", "x-amz-checksum-crc32", 
"AAAAAA==");
+    } else {
+      configureUnsignedTrailer(0, false);
+      body = "0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n";
+    }
     when(objectEndpoint.getContext().getMethod()).thenReturn(HttpMethod.PUT);
     when(headers.getHeaderString(HttpHeaders.CONTENT_LENGTH))
         .thenReturn(hasContentLength ? String.valueOf(body.length()) : null);
@@ -1230,6 +1236,24 @@ void testDirectoryCreationWithUnsignedTrailer(boolean 
hasContentLength) throws E
     assertThat(fsoBucket.getKey("dir/").isFile()).isFalse();
   }
 
+  @Test
+  void testDirectoryCreationWithSignedTrailerOnOmWithoutDerivedKey() throws 
Exception {
+    
objectEndpoint.getOzoneConfiguration().setBoolean(OzoneConfigKeys.OZONE_SECURITY_ENABLED_KEY,
 true);
+    configureSignedChunksWithTrailer(0);
+    
when(headers.getHeaderString(X_AMZ_TRAILER)).thenReturn("x-amz-checksum-crc32");
+    OzoneClient client = spy(objectEndpoint.getClient());
+    ClientProtocol protocol = spy(client.getProxy());
+    
when(protocol.getOmVersion()).thenReturn(OzoneManagerVersion.LOOKUP_FILE_REJECTS_OBS);
+    when(client.getProxy()).thenReturn(protocol);
+    objectEndpoint.setClient(client);
+    // Rebuild the handler chain to use the spied endpoint and client.
+    objectEndpoint.init();
+
+    assertSucceeds(() -> put(objectEndpoint, FSO_BUCKET_NAME, "dir/",
+        signedChunkedBodyWithTrailer("", "x-amz-checksum-crc32", "AAAAAA==")));
+    assertThat(fsoBucket.getKey("dir/").isFile()).isFalse();
+  }
+
   @ParameterizedTest
   @ValueSource(booleans = {false, true})
   void testPutNonEmptyObjectWithTrailingSlashWithoutContentLength(boolean 
signed) throws Exception {
@@ -1451,6 +1475,75 @@ void 
testPutObjectRequiresUnsignedTrailerDeclaration(String declaration) {
     assertKeyWasNotCommitted();
   }
 
+  static Stream<Arguments> checksumTrailers() {
+    // Independent checksums of "123456789", computed with AWS CRT and Python 
hashlib.
+    return Stream.of(
+        Arguments.of("crc32", "y/Q5Jg=="),
+        Arguments.of("crc32c", "4waSgw=="),
+        Arguments.of("crc64nvme", "rosUhgp5mIg="),
+        Arguments.of("sha1", "98O8HYCOBHMq32eZZczDTKeuNEE="),
+        Arguments.of("sha256", "FeKw08M4keuw8e9gnsQZQgwg4yDOlMZfvIwzEkSOsiU="))
+        .flatMap(args -> Stream.of(false, true).flatMap(signed -> 
Stream.of(false, true)
+            .map(datastream -> Arguments.of(args.get()[0], args.get()[1], 
signed, datastream))));
+  }
+
+  @ParameterizedTest
+  @MethodSource("checksumTrailers")
+  void testPutObjectRejectsWrongTrailerChecksum(String algorithm, String 
checksum, boolean signed, boolean datastream)
+      throws Exception {
+    String header = "x-amz-checksum-" + algorithm;
+    configureUnsignedTrailer(CONTENT.length(), datastream);
+    if (signed) {
+      configureSignedChunksWithTrailer(CONTENT.length());
+    }
+    when(headers.getHeaderString(X_AMZ_TRAILER)).thenReturn(header);
+    String body = signed ? signedChunkedBodyWithTrailer(CONTENT, header, 
checksum)
+        : "a\r\n" + CONTENT + "\r\n0\r\n" + header + ":" + checksum + 
"\r\n\r\n";
+
+    assertErrorResponse(S3ErrorTable.BAD_DIGEST, () -> putObject(body));
+    assertKeyWasNotCommitted();
+
+    // A valid upload still succeeds, and a rejected overwrite preserves it.
+    
when(headers.getHeaderString(DECODED_CONTENT_LENGTH_HEADER)).thenReturn("9");
+    String validBody = signed ? signedChunkedBodyWithTrailer("123456789", 
header, checksum)
+        : "9\r\n123456789\r\n0\r\n" + header + ":" + checksum + "\r\n\r\n";
+    assertSucceeds(() -> putObject(validBody));
+    assertKeyContent(bucket, KEY_NAME, "123456789");
+    
when(headers.getHeaderString(DECODED_CONTENT_LENGTH_HEADER)).thenReturn(String.valueOf(CONTENT.length()));
+    assertErrorResponse(S3ErrorTable.BAD_DIGEST, () -> putObject(body));
+    assertKeyContent(bucket, KEY_NAME, "123456789");
+  }
+
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  void testPutEmptyObjectRejectsWrongTrailerChecksum(boolean signed) {
+    configureUnsignedTrailer(0, false);
+    if (signed) {
+      configureSignedChunksWithTrailer(0);
+    }
+    
when(headers.getHeaderString(X_AMZ_TRAILER)).thenReturn("x-amz-checksum-crc32");
+    String body = signed ? signedChunkedBodyWithTrailer("", 
"x-amz-checksum-crc32", "y/Q5Jg==")
+        : "0\r\nx-amz-checksum-crc32:y/Q5Jg==\r\n\r\n";
+
+    assertErrorResponse(S3ErrorTable.BAD_DIGEST, () -> putObject(body));
+    assertKeyWasNotCommitted();
+  }
+
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  void testDirectoryCreationRejectsWrongTrailerChecksum(boolean signed) {
+    configureUnsignedTrailer(0, false);
+    if (signed) {
+      configureSignedChunksWithTrailer(0);
+    }
+    
when(headers.getHeaderString(X_AMZ_TRAILER)).thenReturn("x-amz-checksum-crc32");
+    String body = signed ? signedChunkedBodyWithTrailer("", 
"x-amz-checksum-crc32", "y/Q5Jg==")
+        : "0\r\nx-amz-checksum-crc32:y/Q5Jg==\r\n\r\n";
+
+    assertErrorResponse(S3ErrorTable.BAD_DIGEST, () -> put(objectEndpoint, 
FSO_BUCKET_NAME, "dir/", body));
+    assertThatThrownBy(() -> 
fsoBucket.getKey("dir/")).isInstanceOf(IOException.class);
+  }
+
   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));
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 4b83424d57b..55b8356d81c 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
@@ -33,6 +33,7 @@
 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.apache.hadoop.ozone.s3.util.S3Utils.parseETag;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotEquals;
@@ -270,7 +271,7 @@ public void testPartUploadWithValidSignedTrailer() throws 
Exception {
     String keyName = UUID.randomUUID().toString();
     String content = "1234567890abcde";
     String chunkedContent = signedChunkedBodyWithTrailer(
-        content, "x-amz-checksum-crc32c", "sOO8/Q==");
+        content, "x-amz-checksum-crc32c", "qYszzw==");
     configureSignedChunksWithTrailer(content.length());
 
     String uploadID = initiateMultipartUpload(rest, OzoneConsts.S3_BUCKET, 
keyName);
@@ -390,6 +391,72 @@ void testPartUploadRejectsIncompleteUnsignedTrailer(String 
content) throws Excep
     assertNoParts(uploadID, keyName);
   }
 
+  static Stream<Arguments> checksumTrailers() {
+    // Independent checksums of "123456789", computed with AWS CRT and Python 
hashlib.
+    return Stream.of(
+        Arguments.of("crc32", "y/Q5Jg=="),
+        Arguments.of("crc32c", "4waSgw=="),
+        Arguments.of("crc64nvme", "rosUhgp5mIg="),
+        Arguments.of("sha1", "98O8HYCOBHMq32eZZczDTKeuNEE="),
+        Arguments.of("sha256", "FeKw08M4keuw8e9gnsQZQgwg4yDOlMZfvIwzEkSOsiU="))
+        .flatMap(args -> Stream.of(false, true)
+            .map(signed -> Arguments.of(args.get()[0], args.get()[1], 
signed)));
+  }
+
+  @ParameterizedTest
+  @MethodSource("checksumTrailers")
+  void testPartUploadRejectsWrongTrailerChecksum(String algorithm, String 
checksum, boolean signed) throws Exception {
+    String keyName = UUID.randomUUID().toString();
+    String uploadID = initiateMultipartUpload(rest, OzoneConsts.S3_BUCKET, 
keyName);
+    String content = "1234567890abcde";
+    String header = "x-amz-checksum-" + algorithm;
+    configureUnsignedTrailer(content.length());
+    if (signed) {
+      configureSignedChunksWithTrailer(content.length());
+    }
+    when(headers.getHeaderString(X_AMZ_TRAILER)).thenReturn(header);
+    String body = signed ? signedChunkedBodyWithTrailer(content, header, 
checksum)
+        : "f\r\n" + content + "\r\n0\r\n" + header + ":" + checksum + 
"\r\n\r\n";
+
+    assertErrorResponse(S3ErrorTable.BAD_DIGEST,
+        () -> put(rest, OzoneConsts.S3_BUCKET, keyName, 1, uploadID, body));
+    assertNoParts(uploadID, keyName);
+
+    
when(headers.getHeaderString(DECODED_CONTENT_LENGTH_HEADER)).thenReturn("9");
+    String validBody = signed ? signedChunkedBodyWithTrailer("123456789", 
header, checksum)
+        : "9\r\n123456789\r\n0\r\n" + header + ":" + checksum + "\r\n\r\n";
+    String eTag;
+    try (Response response = put(rest, OzoneConsts.S3_BUCKET, keyName, 1, 
uploadID, validBody)) {
+      assertThat(response.getStatus()).isEqualTo(200);
+      eTag = parseETag(response.getHeaderString(OzoneConsts.ETAG));
+    }
+    assertContentLength(uploadID, keyName, 9);
+    
when(headers.getHeaderString(DECODED_CONTENT_LENGTH_HEADER)).thenReturn(String.valueOf(content.length()));
+    assertErrorResponse(S3ErrorTable.BAD_DIGEST,
+        () -> put(rest, OzoneConsts.S3_BUCKET, keyName, 1, uploadID, body));
+    assertContentLength(uploadID, keyName, 9);
+    
assertThat(client.getObjectStore().getS3Bucket(OzoneConsts.S3_BUCKET).listParts(keyName,
 uploadID, 0, 100)
+        .getPartInfoList().get(0).getETag()).isEqualTo(eTag);
+  }
+
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  void testEmptyPartRejectsWrongTrailerChecksum(boolean signed) throws 
Exception {
+    String keyName = UUID.randomUUID().toString();
+    String uploadID = initiateMultipartUpload(rest, OzoneConsts.S3_BUCKET, 
keyName);
+    configureUnsignedTrailer(0);
+    if (signed) {
+      configureSignedChunksWithTrailer(0);
+    }
+    
when(headers.getHeaderString(X_AMZ_TRAILER)).thenReturn("x-amz-checksum-crc32");
+    String body = signed ? signedChunkedBodyWithTrailer("", 
"x-amz-checksum-crc32", "y/Q5Jg==")
+        : "0\r\nx-amz-checksum-crc32:y/Q5Jg==\r\n\r\n";
+
+    assertErrorResponse(S3ErrorTable.BAD_DIGEST,
+        () -> 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));
diff --git 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestUploadWithStream.java
 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestUploadWithStream.java
index 067b593c9c8..9dab0b50d5c 100644
--- 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestUploadWithStream.java
+++ 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestUploadWithStream.java
@@ -184,7 +184,7 @@ public void testUploadRejectsTamperedSignedChunk() throws 
Exception {
   public void testUploadWithValidSignedTrailer() throws Exception {
     OzoneBucket bucket = 
configureSignedChunksWithTrailer(S3_COPY_EXISTING_KEY_CONTENT.length());
     String body = signedChunkedBodyWithTrailer(
-        S3_COPY_EXISTING_KEY_CONTENT, "x-amz-checksum-crc32c", "sOO8/Q==");
+        S3_COPY_EXISTING_KEY_CONTENT, "x-amz-checksum-crc32c", "toGW0A==");
 
     assertSucceeds(() -> put(rest, S3BUCKET, S3KEY, body));
 
diff --git 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/signature/SignatureTestUtils.java
 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/signature/SignatureTestUtils.java
index edb75cea592..00382d556fb 100644
--- 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/signature/SignatureTestUtils.java
+++ 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/signature/SignatureTestUtils.java
@@ -139,15 +139,21 @@ public static String signedChunkedBody(String content) {
   /** Build a one-data-chunk SigV4 body with one trailing header and its 
signature. */
   public static String signedChunkedBodyWithTrailer(String content, String 
trailerName,
       String trailerValue) {
-    byte[] payload = content.getBytes(UTF_8);
+    return signedChunkedBodyWithTrailer(new String[]{content}, trailerName, 
trailerValue);
+  }
+
+  /** Build a multi-data-chunk SigV4 body with one trailing header and its 
signature. */
+  public static String signedChunkedBodyWithTrailer(String[] chunks, String 
trailerName, String trailerValue) {
     String previousSignature = SEED_SIGNATURE;
     StringBuilder body = new StringBuilder();
-    if (payload.length > 0) {
-      previousSignature = chunkSignature(SIGNING_KEY, DATE_TIME, 
CREDENTIAL_SCOPE,
-          SEED_SIGNATURE, payload);
-      body.append(Integer.toHexString(payload.length))
-          .append(";chunk-signature=").append(previousSignature).append("\r\n")
-          .append(content).append("\r\n");
+    for (String chunk : chunks) {
+      byte[] payload = chunk.getBytes(UTF_8);
+      if (payload.length > 0) {
+        previousSignature = chunkSignature(SIGNING_KEY, DATE_TIME, 
CREDENTIAL_SCOPE, previousSignature, payload);
+        body.append(Integer.toHexString(payload.length))
+            
.append(";chunk-signature=").append(previousSignature).append("\r\n")
+            .append(chunk).append("\r\n");
+      }
     }
     String finalSignature = chunkSignature(SIGNING_KEY, DATE_TIME, 
CREDENTIAL_SCOPE,
         previousSignature, new byte[0]);


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

Reply via email to