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 c3830a43a65 HDDS-17500. Return x-amz-server-side-encryption on GET and 
HEAD for encrypted objects (#11972)
c3830a43a65 is described below

commit c3830a43a6594bd1a66b4bb3efd51b20f976ff52
Author: Andrey Yarovoy <[email protected]>
AuthorDate: Tue Nov 10 08:55:17 2026 -0500

    HDDS-17500. Return x-amz-server-side-encryption on GET and HEAD for 
encrypted objects (#11972)
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .../org/apache/hadoop/ozone/client/OzoneKey.java   |  19 ++-
 .../hadoop/ozone/client/OzoneKeyDetails.java       |   6 +
 .../dist/src/main/smoketest/s3/objectputget.robot  |  26 ++++
 .../hadoop/ozone/s3/endpoint/EndpointBase.java     |   5 +-
 .../hadoop/ozone/s3/endpoint/ObjectEndpoint.java   |  12 +-
 .../ozone/s3/endpoint/ServerSideEncryption.java    |  36 ++++++
 .../hadoop/ozone/client/OzoneBucketStub.java       |  25 +++-
 .../s3/endpoint/TestServerSideEncryption.java      | 133 +++++++++++++++++++++
 8 files changed, 250 insertions(+), 12 deletions(-)

diff --git 
a/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/OzoneKey.java
 
b/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/OzoneKey.java
index 7cd0bc42c59..c78785ffadc 100644
--- 
a/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/OzoneKey.java
+++ 
b/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/OzoneKey.java
@@ -70,6 +70,11 @@ public class OzoneKey {
    */
   private final boolean isFile;
 
+  /**
+   * Name of the KMS key the data is encrypted with, null if the key is not 
encrypted or it is not known.
+   */
+  private String encryptionKeyName;
+
   @SuppressWarnings("parameternumber")
   public OzoneKey(String volumeName, String bucketName,
       String keyName, long size, long creationTime,
@@ -213,16 +218,28 @@ public boolean isFile() {
     return isFile;
   }
 
+  /**
+   * Returns the name of the KMS key the data is encrypted with, null if the 
key is not encrypted or it is not known.
+   */
+  @JsonIgnore
+  public String getEncryptionKeyName() {
+    return encryptionKeyName;
+  }
+
   /**
    * Constructs OzoneKey from OmKeyInfo.
    *
    */
   public static OzoneKey fromKeyInfo(OmKeyInfo keyInfo) {
-    return new OzoneKey(keyInfo.getVolumeName(), keyInfo.getBucketName(),
+    final OzoneKey key = new OzoneKey(keyInfo.getVolumeName(), 
keyInfo.getBucketName(),
         keyInfo.getKeyName(), keyInfo.getDataSize(), keyInfo.getCreationTime(),
         keyInfo.getModificationTime(), keyInfo.getReplicationConfig(),
         keyInfo.getMetadata(), keyInfo.isFile(), keyInfo.getOwnerName(),
         keyInfo.getTags());
+    if (keyInfo.getFileEncryptionInfo() != null) {
+      key.encryptionKeyName = keyInfo.getFileEncryptionInfo().getKeyName();
+    }
+    return key;
   }
 
 }
diff --git 
a/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/OzoneKeyDetails.java
 
b/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/OzoneKeyDetails.java
index 7514f2a7cd7..48cf5ed625d 100644
--- 
a/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/OzoneKeyDetails.java
+++ 
b/hadoop-ozone/client/src/main/java/org/apache/hadoop/ozone/client/OzoneKeyDetails.java
@@ -95,6 +95,12 @@ public FileEncryptionInfo getFileEncryptionInfo() {
     return feInfo;
   }
 
+  @Override
+  @JsonIgnore
+  public String getEncryptionKeyName() {
+    return feInfo != null ? feInfo.getKeyName() : null;
+  }
+
   public Long getGeneration() {
     return generation;
   }
diff --git a/hadoop-ozone/dist/src/main/smoketest/s3/objectputget.robot 
b/hadoop-ozone/dist/src/main/smoketest/s3/objectputget.robot
index 0ef9f274e8c..cc7af206bab 100644
--- a/hadoop-ozone/dist/src/main/smoketest/s3/objectputget.robot
+++ b/hadoop-ozone/dist/src/main/smoketest/s3/objectputget.robot
@@ -351,6 +351,32 @@ Put object with server-side encryption
                                 Should contain             ${result}    404
     END
 
+Get and head object report server-side encryption
+    [tags]    aws-skip
+                                Execute                    echo "sse" > 
/tmp/ssetestfile
+    IF    '${BUCKET}' == 'encrypted'
+        # without an SSE header, an object in an encrypted bucket is reported 
as encrypted with the bucket's KMS key
+                                Execute AWSS3APICli        put-object --bucket 
${BUCKET} --key ${PREFIX}/getobject/sse/kms --body /tmp/ssetestfile
+        ${result} =             Execute AWSS3APICli        head-object 
--bucket ${BUCKET} --key ${PREFIX}/getobject/sse/kms
+                                Should contain             ${result}    
"ServerSideEncryption": "aws:kms"
+                                Should contain             ${result}    
"SSEKMSKeyId"
+        ${result} =             Execute AWSS3APICli        get-object --bucket 
${BUCKET} --key ${PREFIX}/getobject/sse/kms /tmp/ssetestfile.result
+                                Should contain             ${result}    
"ServerSideEncryption": "aws:kms"
+        # an object written with AES256 reports AES256
+                                Execute AWSS3APICli        put-object --bucket 
${BUCKET} --key ${PREFIX}/getobject/sse/aes --body /tmp/ssetestfile 
--server-side-encryption AES256
+        ${result} =             Execute AWSS3APICli        head-object 
--bucket ${BUCKET} --key ${PREFIX}/getobject/sse/aes
+                                Should contain             ${result}    
"ServerSideEncryption": "AES256"
+                                Should not contain         ${result}    
SSEKMSKeyId
+        ${result} =             Execute AWSS3APICli        get-object --bucket 
${BUCKET} --key ${PREFIX}/getobject/sse/aes /tmp/ssetestfile.result
+                                Should contain             ${result}    
"ServerSideEncryption": "AES256"
+    ELSE
+                                Execute AWSS3APICli        put-object --bucket 
${BUCKET} --key ${PREFIX}/getobject/sse/plain --body /tmp/ssetestfile
+        ${result} =             Execute AWSS3APICli        head-object 
--bucket ${BUCKET} --key ${PREFIX}/getobject/sse/plain
+                                Should not contain         ${result}    
ServerSideEncryption
+        ${result} =             Execute AWSS3APICli        get-object --bucket 
${BUCKET} --key ${PREFIX}/getobject/sse/plain /tmp/ssetestfile.result
+                                Should not contain         ${result}    
ServerSideEncryption
+    END
+
 Put object with customer-provided encryption key
     [tags]    aws-skip
                                 Execute                    echo "ssec" > 
/tmp/ssectestfile
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 368cc800af1..7e178c19dfe 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
@@ -511,8 +511,9 @@ protected void addCustomMetadataHeaders(
     Map<String, String> metadata = key.getMetadata();
     for (Map.Entry<String, String> entry : metadata.entrySet()) {
       String metadataKey = entry.getKey();
-      // System ETag / Content-Type are returned via their own response header.
-      if (RESERVED_METADATA_KEYS.containsKey(metadataKey)) {
+      // System ETag / Content-Type are returned via their own response 
header, the SSE algorithm via the SSE header.
+      if (RESERVED_METADATA_KEYS.containsKey(metadataKey)
+          || ServerSideEncryption.ALGORITHM_METADATA_KEY.equals(metadataKey)) {
         continue;
       }
       // Rebuild a remapped user value (e.g. ozone-s3-internal-content-type -> 
content-type).
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 13e5d80bdd4..411548fd649 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
@@ -59,6 +59,7 @@
 import java.time.Instant;
 import java.time.ZoneId;
 import java.time.ZonedDateTime;
+import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
@@ -237,7 +238,7 @@ Response handlePutRequest(ObjectRequestContext context, 
String keyPath, InputStr
       if (copyHeader != null) {
         //Copy object, as copy source available.
         context.setAction(S3GAction.COPY_OBJECT);
-        CopyObjectResponse copyObjectResponse = copyObject(bucket, keyPath, 
replicationConfig, perf);
+        CopyObjectResponse copyObjectResponse = copyObject(bucket, keyPath, 
replicationConfig, sseHeaders, perf);
         return 
ServerSideEncryption.withHeaders(Response.status(Status.OK).entity(copyObjectResponse).header(
             "Connection", "close").build(), sseHeaders);
       }
@@ -288,6 +289,7 @@ Response handlePutRequest(ObjectRequestContext context, 
String keyPath, InputStr
           getCustomMetadataFromHeaders(getHeaders().getRequestHeaders());
       putContentType(customMetadata);
       putStandardObjectHeaders(customMetadata);
+      ServerSideEncryption.putAlgorithm(customMetadata, sseHeaders);
       Map<String, String> tags = getTaggingFromHeaders(getHeaders());
 
       long putLength;
@@ -494,6 +496,7 @@ Response handleGetRequest(ObjectRequestContext context, 
String keyPath)
       addLastModifiedDate(responseBuilder, keyDetails);
       addTagCountIfAny(responseBuilder, keyDetails);
       addCustomMetadataHeaders(responseBuilder, keyDetails);
+      
ServerSideEncryption.readHeaders(keyDetails).forEach(responseBuilder::header);
 
       long metadataLatencyNs = 
getMetrics().updateGetKeyMetadataStats(startNanos);
       perf.appendMetaLatencyNanos(metadataLatencyNs);
@@ -729,6 +732,7 @@ public Response head(
     addLastModifiedDate(response, key);
     addTagCountIfAny(response, key);
     addCustomMetadataHeaders(response, key);
+    ServerSideEncryption.readHeaders(key).forEach(response::header);
     getMetrics().updateHeadKeySuccessStats(startNanos);
     auditReadSuccess(context.getAction());
     return response.build();
@@ -824,6 +828,7 @@ public Response initializeMultipartUpload(
           getCustomMetadataFromHeaders(getHeaders().getRequestHeaders());
       putContentType(customMetadata);
       putStandardObjectHeaders(customMetadata);
+      ServerSideEncryption.putAlgorithm(customMetadata, sseHeaders);
 
       Map<String, String> tags = getTaggingFromHeaders(getHeaders());
 
@@ -1228,7 +1233,7 @@ srcKeyLen > getDatastreamMinLength()) {
   }
 
   private CopyObjectResponse copyObject(OzoneBucket destinationBucket, String 
destkey,
-      ReplicationConfig replicationConfig,
+      ReplicationConfig replicationConfig, Map<String, String> sseHeaders,
       PerformanceStringBuilder perf)
       throws OS3Exception, IOException {
     String destBucket = destinationBucket.getName();
@@ -1315,7 +1320,7 @@ private CopyObjectResponse copyObject(OzoneBucket 
destinationBucket, String dest
       Map<String, String> customMetadata;
       if (StringUtils.isEmpty(metadataCopyDirective) || 
metadataCopyDirective.equals(CopyDirective.COPY.name())) {
         // The custom metadata will be copied from the source key
-        customMetadata = sourceKeyDetails.getMetadata();
+        customMetadata = new HashMap<>(sourceKeyDetails.getMetadata());
       } else if (metadataCopyDirective.equals(CopyDirective.REPLACE.name())) {
         // Replace the metadata with the metadata form the request headers
         customMetadata = 
getCustomMetadataFromHeaders(getHeaders().getRequestHeaders());
@@ -1329,6 +1334,7 @@ private CopyObjectResponse copyObject(OzoneBucket 
destinationBucket, String dest
             "The metadata copy directive specified is invalid. Valid values 
are COPY or REPLACE.");
         throw ex;
       }
+      ServerSideEncryption.putAlgorithm(customMetadata, sseHeaders);
 
       // A whole-object copy writes byte-identical content, so a plain 
(non-multipart) MD5 ETag
       // stored on the source is also the correct content MD5 for the 
destination and the data does
diff --git 
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/ServerSideEncryption.java
 
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/ServerSideEncryption.java
index 629da014937..8afe6829c31 100644
--- 
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/ServerSideEncryption.java
+++ 
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/ServerSideEncryption.java
@@ -23,6 +23,7 @@
 import static 
org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_SSE_CUSTOMER_ALGORITHM_HEADER;
 import static 
org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_SSE_CUSTOMER_KEY_HEADER;
 import static 
org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_SSE_CUSTOMER_KEY_MD5_HEADER;
+import static 
org.apache.hadoop.ozone.s3.util.S3Consts.RESERVED_USER_METADATA_KEY_PREFIX;
 import static org.apache.hadoop.ozone.s3.util.S3Consts.SSE_CONTEXT_HEADER;
 import static 
org.apache.hadoop.ozone.s3.util.S3Consts.SSE_CUSTOMER_ALGORITHM_HEADER;
 import static org.apache.hadoop.ozone.s3.util.S3Consts.SSE_CUSTOMER_KEY_HEADER;
@@ -38,6 +39,7 @@
 import javax.ws.rs.core.Response;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.hadoop.ozone.client.OzoneBucket;
+import org.apache.hadoop.ozone.client.OzoneKey;
 import org.apache.hadoop.ozone.s3.exception.OS3Exception;
 import org.apache.hadoop.ozone.s3.exception.S3ErrorTable;
 
@@ -55,6 +57,12 @@ final class ServerSideEncryption {
   static final String AWS_KMS = "aws:kms";
   static final String AWS_KMS_DSSE = "aws:kms:dsse";
 
+  /**
+   * The key metadata that stores the algorithm an object was written with. A 
user metadata key can never be equal to
+   * it, in any version, because a header name cannot contain {@code ':'}.
+   */
+  static final String ALGORITHM_METADATA_KEY = 
RESERVED_USER_METADATA_KEY_PREFIX + "sse:algorithm";
+
   private static final List<String> CUSTOMER_KEY_HEADERS = ImmutableList.of(
       SSE_CUSTOMER_ALGORITHM_HEADER, SSE_CUSTOMER_KEY_HEADER, 
SSE_CUSTOMER_KEY_MD5_HEADER,
       COPY_SOURCE_SSE_CUSTOMER_ALGORITHM_HEADER, 
COPY_SOURCE_SSE_CUSTOMER_KEY_HEADER,
@@ -110,6 +118,34 @@ static Map<String, String> checkWrite(HttpHeaders headers, 
OzoneBucket bucket, S
         : ImmutableMap.of(SSE_HEADER, algorithm);
   }
 
+  /**
+   * Stores the algorithm accepted by {@link #checkWrite} in the metadata of 
the key being written, for
+   * {@link #readHeaders}. A copy does not keep the algorithm of its source: 
like a new object, it gets the algorithm
+   * of its own request.
+   */
+  static void putAlgorithm(Map<String, String> metadata, Map<String, String> 
sseHeaders) {
+    metadata.remove(ALGORITHM_METADATA_KEY);
+    final String algorithm = sseHeaders.get(SSE_HEADER);
+    if (algorithm != null) {
+      metadata.put(ALGORITHM_METADATA_KEY, algorithm);
+    }
+  }
+
+  /**
+   * Returns the SSE headers of a GetObject or HeadObject response. Like in 
AWS, an encrypted object reports its
+   * encryption: the algorithm it was written with, or {@code aws:kms} if it 
was written without one (or before the
+   * algorithm was stored), and for {@code aws:kms} the KMS key. An object 
that is not encrypted reports none.
+   */
+  static Map<String, String> readHeaders(OzoneKey key) {
+    final String kmsKey = key.getEncryptionKeyName();
+    if (kmsKey == null) {
+      return ImmutableMap.of();
+    }
+    return AES256.equals(key.getMetadata().get(ALGORITHM_METADATA_KEY))
+        ? ImmutableMap.of(SSE_HEADER, AES256)
+        : ImmutableMap.of(SSE_HEADER, AWS_KMS, SSE_KMS_KEY_ID_HEADER, kmsKey);
+  }
+
   /** Adds the SSE headers returned by {@link #checkWrite} to {@code 
response}. */
   static Response withHeaders(Response response, Map<String, String> 
sseHeaders) {
     if (sseHeaders.isEmpty()) {
diff --git 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/client/OzoneBucketStub.java
 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/client/OzoneBucketStub.java
index f2ce631d67e..7c0ace9fb11 100644
--- 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/client/OzoneBucketStub.java
+++ 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/client/OzoneBucketStub.java
@@ -42,6 +42,9 @@
 import javax.xml.bind.DatatypeConverter;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.lang3.StringUtils;
+import org.apache.hadoop.crypto.CipherSuite;
+import org.apache.hadoop.crypto.CryptoProtocolVersion;
+import org.apache.hadoop.fs.FileEncryptionInfo;
 import org.apache.hadoop.hdds.client.RatisReplicationConfig;
 import org.apache.hadoop.hdds.client.ReplicationConfig;
 import org.apache.hadoop.hdds.client.ReplicationFactor;
@@ -182,7 +185,7 @@ public void close() throws IOException {
                 size,
                 mtime,
                 mtime,
-                new ArrayList<>(), finalReplicationCon, getMetadata(), null,
+                new ArrayList<>(), finalReplicationCon, getMetadata(), 
fileEncryptionInfo(),
                 () -> readKey(key), true,
                 UserGroupInformation.getCurrentUser().getShortUserName(),
                 tags
@@ -225,7 +228,7 @@ public void close() throws IOException {
                 size,
                 mtime,
                 mtime,
-                new ArrayList<>(), finalReplicationCon, metadata, null,
+                new ArrayList<>(), finalReplicationCon, metadata, 
fileEncryptionInfo(),
                 () -> readKey(keyName), true, null, null
             ));
           }
@@ -338,7 +341,7 @@ public void close() throws IOException {
                 size,
                 mtime,
                 mtime,
-                new ArrayList<>(), rConfig, objectMetadata, null,
+                new ArrayList<>(), rConfig, objectMetadata, 
fileEncryptionInfo(),
                 () -> readKey(key), false,
                 UserGroupInformation.getCurrentUser().getShortUserName(),
                 tags
@@ -563,20 +566,30 @@ public void putKeyMetadataForTest(String key, String 
metadataKey, String metadat
         details.getGeneration()));
   }
 
-  private static OzoneKey toHeadOzoneKey(OzoneKeyDetails details, long 
dataSize) {
-    return new OzoneKey(details.getVolumeName(),
+  private OzoneKey toHeadOzoneKey(OzoneKeyDetails details, long dataSize) {
+    // like OzoneKey.fromKeyInfo, keep the encryption key name of an encrypted 
key
+    return new OzoneKeyDetails(details.getVolumeName(),
         details.getBucketName(),
         details.getName(),
         dataSize,
         details.getCreationTime().toEpochMilli(),
         details.getModificationTime().toEpochMilli(),
+        new ArrayList<>(),
         details.getReplicationConfig(),
         details.getMetadata(),
+        details.getFileEncryptionInfo(),
+        () -> readKey(details.getName()),
         details.isFile(),
         details.getOwner(),
         details.getTags());
   }
 
+  /** Like OM, a file in an encrypted bucket is encrypted with the bucket key. 
*/
+  private FileEncryptionInfo fileEncryptionInfo() {
+    return getEncryptionKeyName() == null ? null : new 
FileEncryptionInfo(CipherSuite.AES_CTR_NOPADDING,
+        CryptoProtocolVersion.ENCRYPTION_ZONES, new byte[16], new byte[16], 
getEncryptionKeyName(), "v1");
+  }
+
   @Override
   public Iterator<? extends OzoneKey> listKeys(String keyPrefix) {
     Map<String, OzoneKey> sortedKey = new TreeMap<String, 
OzoneKey>(keyDetails);
@@ -785,7 +798,7 @@ public OmMultipartUploadCompleteInfo 
completeMultipartUpload(String key,
           System.currentTimeMillis(),
           System.currentTimeMillis(),
           new ArrayList<>(), getReplicationConfig(),
-          metadata, null,
+          metadata, fileEncryptionInfo(),
           () -> readKey(key), true,
           UserGroupInformation.getCurrentUser().getShortUserName(),
           keyToMultipartUpload.get(key).getTags()
diff --git 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestServerSideEncryption.java
 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestServerSideEncryption.java
index a14d0c2e340..8f059b563e6 100644
--- 
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestServerSideEncryption.java
+++ 
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestServerSideEncryption.java
@@ -19,6 +19,7 @@
 
 import static 
org.apache.hadoop.ozone.client.OzoneClientTestUtils.assertKeyContent;
 import static 
org.apache.hadoop.ozone.s3.endpoint.EndpointTestUtils.assertErrorResponse;
+import static 
org.apache.hadoop.ozone.s3.endpoint.EndpointTestUtils.completeMultipartUpload;
 import static org.apache.hadoop.ozone.s3.endpoint.EndpointTestUtils.get;
 import static 
org.apache.hadoop.ozone.s3.endpoint.EndpointTestUtils.getObjectAttributes;
 import static 
org.apache.hadoop.ozone.s3.endpoint.EndpointTestUtils.initiateMultipartUpload;
@@ -32,6 +33,9 @@
 import static 
org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_SSE_CUSTOMER_ALGORITHM_HEADER;
 import static 
org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_SSE_CUSTOMER_KEY_HEADER;
 import static 
org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_SSE_CUSTOMER_KEY_MD5_HEADER;
+import static 
org.apache.hadoop.ozone.s3.util.S3Consts.CUSTOM_METADATA_COPY_DIRECTIVE_HEADER;
+import static 
org.apache.hadoop.ozone.s3.util.S3Consts.CUSTOM_METADATA_HEADER_PREFIX;
+import static 
org.apache.hadoop.ozone.s3.util.S3Consts.RESERVED_USER_METADATA_KEY_PREFIX;
 import static org.apache.hadoop.ozone.s3.util.S3Consts.SSE_CONTEXT_HEADER;
 import static 
org.apache.hadoop.ozone.s3.util.S3Consts.SSE_CUSTOMER_ALGORITHM_HEADER;
 import static org.apache.hadoop.ozone.s3.util.S3Consts.SSE_CUSTOMER_KEY_HEADER;
@@ -39,6 +43,7 @@
 import static org.apache.hadoop.ozone.s3.util.S3Consts.SSE_HEADER;
 import static org.apache.hadoop.ozone.s3.util.S3Consts.SSE_KMS_KEY_ID_HEADER;
 import static org.apache.hadoop.ozone.s3.util.S3Consts.X_AMZ_CONTENT_SHA256;
+import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNull;
@@ -49,15 +54,20 @@
 import java.util.Collections;
 import java.util.stream.Stream;
 import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
 import javax.ws.rs.core.Response;
 import org.apache.hadoop.ozone.client.BucketArgs;
 import org.apache.hadoop.ozone.client.OzoneBucket;
+import org.apache.hadoop.ozone.client.OzoneBucketStub;
 import org.apache.hadoop.ozone.client.OzoneClient;
 import org.apache.hadoop.ozone.client.OzoneClientStub;
 import org.apache.hadoop.ozone.s3.exception.S3ErrorTable;
+import org.apache.hadoop.ozone.s3.util.S3Consts.QueryParams;
 import org.junit.jupiter.api.BeforeEach;
 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.MethodSource;
 import org.junit.jupiter.params.provider.ValueSource;
 
@@ -285,4 +295,127 @@ public void 
multipartUploadToEncryptedBucketWithEncryptionSucceeds() throws IOEx
       assertEquals(BUCKET_KEY, 
response.getHeaderString(SSE_KMS_KEY_ID_HEADER));
     }
   }
+
+  /** Asserts the SSE headers that GetObject and HeadObject return for {@code 
key}. */
+  private void assertReadReports(String bucket, String key, String algorithm, 
String kmsKeyId) throws IOException {
+    // the read requests carry no SSE headers
+    setHeader(SSE_HEADER, null);
+    setHeader(SSE_KMS_KEY_ID_HEADER, null);
+    setHeader(COPY_SOURCE_HEADER, null);
+    setHeader(CUSTOM_METADATA_COPY_DIRECTIVE_HEADER, null);
+    try (Response getResponse = get(objectEndpoint, bucket, key);
+         Response headResponse = objectEndpoint.head(bucket, key)) {
+      for (Response response : new Response[] {getResponse, headResponse}) {
+        assertEquals(200, response.getStatus());
+        assertEquals(algorithm, response.getHeaderString(SSE_HEADER));
+        assertEquals(kmsKeyId, 
response.getHeaderString(SSE_KMS_KEY_ID_HEADER));
+        // the stored algorithm is not returned as user metadata
+        assertThat(response.getStringHeaders().keySet())
+            .noneMatch(name -> 
name.contains(RESERVED_USER_METADATA_KEY_PREFIX));
+      }
+    }
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"", AES256, AWS_KMS})
+  public void readOfEncryptedObjectReportsItsEncryption(String writeAlgorithm) 
throws IOException {
+    if (!writeAlgorithm.isEmpty()) {
+      setHeader(SSE_HEADER, writeAlgorithm);
+    }
+    put(objectEndpoint, ENCRYPTED, KEY_NAME, CONTENT).close();
+
+    // the algorithm of the write, aws:kms with the bucket key if the write 
did not ask for encryption
+    if (AES256.equals(writeAlgorithm)) {
+      assertReadReports(ENCRYPTED, KEY_NAME, AES256, null);
+    } else {
+      assertReadReports(ENCRYPTED, KEY_NAME, AWS_KMS, BUCKET_KEY);
+    }
+  }
+
+  @Test
+  public void readOfPlainObjectReportsNoEncryption() throws IOException {
+    put(objectEndpoint, PLAIN, KEY_NAME, CONTENT).close();
+
+    assertReadReports(PLAIN, KEY_NAME, null, null);
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"", AES256})
+  public void multipartObjectReportsEncryptionOfItsUpload(String 
writeAlgorithm) throws IOException {
+    if (!writeAlgorithm.isEmpty()) {
+      setHeader(SSE_HEADER, writeAlgorithm);
+    }
+    final String uploadId = initiateMultipartUpload(objectEndpoint, ENCRYPTED, 
KEY_NAME);
+    setHeader(SSE_HEADER, null);
+    completeMultipartUpload(objectEndpoint, ENCRYPTED, KEY_NAME, uploadId,
+        Collections.singletonList(uploadPart(objectEndpoint, ENCRYPTED, 
KEY_NAME, 1, uploadId, CONTENT)));
+    objectEndpoint.queryParamsForTest().unset(QueryParams.UPLOAD_ID);
+    objectEndpoint.queryParamsForTest().unset(QueryParams.PART_NUMBER);
+
+    final String algorithm = writeAlgorithm.isEmpty() ? AWS_KMS : 
writeAlgorithm;
+    final String kmsKeyId = writeAlgorithm.isEmpty() ? BUCKET_KEY : null;
+    assertReadReports(ENCRYPTED, KEY_NAME, algorithm, kmsKeyId);
+    objectEndpoint.queryParamsForTest().setInt(QueryParams.PART_NUMBER, 1);
+    assertReadReports(ENCRYPTED, KEY_NAME, algorithm, kmsKeyId);
+  }
+
+  /** A copy reports the algorithm of the copy request, not the one its source 
was written with. */
+  @ParameterizedTest
+  @CsvSource({"AES256,,COPY", "AES256,aws:kms,COPY", "AES256,,REPLACE", 
"aws:kms,AES256,COPY",
+      "aws:kms,AES256,REPLACE"})
+  public void copyReportsEncryptionOfTheCopyRequest(String sourceAlgorithm, 
String copyAlgorithm, String directive)
+      throws IOException {
+    setHeader(SSE_HEADER, sourceAlgorithm);
+    put(objectEndpoint, ENCRYPTED, KEY_NAME, CONTENT).close();
+    setHeader(SSE_HEADER, copyAlgorithm);
+    setHeader(COPY_SOURCE_HEADER, ENCRYPTED + "/" + KEY_NAME);
+    setHeader(CUSTOM_METADATA_COPY_DIRECTIVE_HEADER, directive);
+    put(objectEndpoint, ENCRYPTED, "copy", CONTENT).close();
+
+    if (AES256.equals(copyAlgorithm)) {
+      assertReadReports(ENCRYPTED, "copy", AES256, null);
+    } else {
+      assertReadReports(ENCRYPTED, "copy", AWS_KMS, BUCKET_KEY);
+    }
+    // the source is unchanged
+    if (AES256.equals(sourceAlgorithm)) {
+      assertReadReports(ENCRYPTED, KEY_NAME, AES256, null);
+    } else {
+      assertReadReports(ENCRYPTED, KEY_NAME, AWS_KMS, BUCKET_KEY);
+    }
+  }
+
+  /**
+   * User metadata {@code x-amz-server-side-encryption} written before the 
algorithm was stored is still returned as
+   * user metadata, and not read as the algorithm.
+   */
+  @Test
+  public void userMetadataNamedLikeTheHeaderWrittenBeforeIsKept() throws 
IOException {
+    put(objectEndpoint, ENCRYPTED, KEY_NAME, CONTENT).close();
+    ((OzoneBucketStub) encryptedBucket).putKeyMetadataForTest(KEY_NAME, 
SSE_HEADER, AES256);
+
+    assertReadReports(ENCRYPTED, KEY_NAME, AWS_KMS, BUCKET_KEY);
+    try (Response response = get(objectEndpoint, ENCRYPTED, KEY_NAME)) {
+      assertEquals(AES256, 
response.getHeaderString(CUSTOM_METADATA_HEADER_PREFIX + SSE_HEADER));
+    }
+  }
+
+  /** User metadata with the name of the SSE header is kept apart from the 
stored algorithm, in any bucket. */
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  public void userMetadataNamedLikeTheAlgorithmIsKept(boolean encrypted) 
throws IOException {
+    final MultivaluedMap<String, String> requestHeaders = new 
MultivaluedHashMap<>();
+    requestHeaders.putSingle(CUSTOM_METADATA_HEADER_PREFIX + SSE_HEADER, 
"user-value");
+    when(headers.getRequestHeaders()).thenReturn(requestHeaders);
+    final String bucket = encrypted ? ENCRYPTED : PLAIN;
+    if (encrypted) {
+      setHeader(SSE_HEADER, AES256);
+    }
+    put(objectEndpoint, bucket, KEY_NAME, CONTENT).close();
+
+    assertReadReports(bucket, KEY_NAME, encrypted ? AES256 : null, null);
+    try (Response response = get(objectEndpoint, bucket, KEY_NAME)) {
+      assertEquals("user-value", 
response.getHeaderString(CUSTOM_METADATA_HEADER_PREFIX + SSE_HEADER));
+    }
+  }
 }


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

Reply via email to