diff --git a/docs/services/s3.md b/docs/services/s3.md index 16b9cf9bbf..02f7bc0f61 100644 --- a/docs/services/s3.md +++ b/docs/services/s3.md @@ -810,8 +810,8 @@ Floci now persists and returns the following object attribute state on S3 object - canned object ACLs from `x-amz-acl` on `PutObject`, `CopyObject`, and multipart initiation - explicit ACL grant headers (`x-amz-grant-read`, `x-amz-grant-write`, `x-amz-grant-full-control`, `x-amz-grant-read-acp`, `x-amz-grant-write-acp`) with `id` and `uri` grantees on `PutObject`, `CopyObject`, and multipart initiation, where they apply when the upload completes - Object Lock headers (`x-amz-object-lock-mode`, `x-amz-object-lock-retain-until-date`, `x-amz-object-lock-legal-hold`) on `PutObject`, `CopyObject`, and multipart initiation, where they apply when the upload completes. A mode without a date or a date without a mode, an unknown mode, or a date that is not an ISO 8601 timestamp is refused with `400 InvalidArgument`. In a bucket without Object Lock, a mode, a date or a legal hold of `ON` is refused with `400 InvalidRequest`, "Bucket is missing Object Lock Configuration", as `PutObjectRetention`, `GetObjectRetention`, `PutObjectLegalHold` and `GetObjectLegalHold` are there. `GetObjectRetention` and `GetObjectLegalHold` of an object without a retention or a legal hold answer `404 NoSuchObjectLockConfiguration`. A `PutObjectRetention` body with a mode but no date, a date but no mode, or an unknown mode is refused with `400 MalformedXML`; one naming neither removes the retention -- explicit object SSE headers from `x-amz-server-side-encryption` on `PutObject`, `CopyObject`, and multipart initiation, and form fields on browser/presigned POST, replayed on `GetObject` and `HeadObject` -- SSE-KMS key IDs from `x-amz-server-side-encryption-aws-kms-key-id` on `PutObject`, browser/presigned POST, and multipart initiation, and from `CopyObject`/`UploadPartCopy` (inherited from the source object when the request doesn't specify new SSE headers), returned by `PutObject`, `CopyObject`, `UploadPartCopy`, `CompleteMultipartUpload`, `GetObject`, and `HeadObject`. A bucket's default SSE-KMS key is not simulated: `aws:kms` with no explicit key ID omits the header rather than returning a synthesized `aws/s3` key ARN +- object SSE from `x-amz-server-side-encryption` on `PutObject`, `CopyObject`, and multipart initiation, and form fields on browser/presigned POST, returned by `GetObject` and `HeadObject`. An object stored with neither an SSE header nor an SSE-C key takes its bucket's default encryption (`PutBucketEncryption`), SSE-S3 (`AES256`) when the bucket has none. A multipart upload takes it when it completes, a known deviation from AWS: the [`CreateMultipartUpload` response](https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html) carries `x-amz-server-side-encryption`, so an upload's encryption is set when it is created (that it cannot change later is inferred), and an `UploadPartCopy` response reports only the encryption the upload was created with. A `CopyObject` without encryption headers keeps the encryption of a source that has one, a known deviation from AWS: the [`CopyObject` reference](https://docs.aws.amazon.com/AmazonS3/latest/API/API_CopyObject.html) says that "if you don't specify encryption information in your copy request, the encryption setting of the target object is set to the default encryption configuration of the destination bucket". A source with no encryption stored (an SSE-C object, or one stored before the default was applied) takes the destination bucket's default +- SSE-KMS key IDs from `x-amz-server-side-encryption-aws-kms-key-id` on `PutObject`, browser/presigned POST, and multipart initiation, and from `CopyObject` (inherited from the source object when the request doesn't specify new SSE headers; the parts of an `UploadPartCopy` take the encryption of their upload), returned by `PutObject`, `CopyObject`, `CompleteMultipartUpload`, `GetObject`, and `HeadObject`, and by `UploadPartCopy` for an upload created with an SSE-KMS header. A bucket's default SSE-KMS key is applied as configured but not simulated: `aws:kms` with no key ID, in the request or in the bucket's default encryption, omits the header rather than returning a synthesized `aws/s3` key ARN Current limitations: diff --git a/src/main/java/io/floci/aws/services/s3/S3Service.java b/src/main/java/io/floci/aws/services/s3/S3Service.java index feaf93ea3a..7b13d7daf6 100644 --- a/src/main/java/io/floci/aws/services/s3/S3Service.java +++ b/src/main/java/io/floci/aws/services/s3/S3Service.java @@ -1040,10 +1040,15 @@ public class S3Service implements Resettable, ResourceProvider { object.setContentEncoding(effectiveOptions.getContentEncoding()); object.setContentDisposition(effectiveOptions.getContentDisposition()); object.setCacheControl(effectiveOptions.getCacheControl()); - object.setServerSideEncryption(normalizedServerSideEncryption); - object.setSseKmsKeyId("aws:kms".equals(normalizedServerSideEncryption) - || "aws:kms:dsse".equals(normalizedServerSideEncryption) - ? effectiveOptions.getSseKmsKeyId() + // An object written with neither an encryption header nor an SSE-C key is encrypted with the + // bucket's default encryption. + ObjectEncryption encryption = normalizedServerSideEncryption == null && sseCustomerKey == null + ? defaultEncryption(bucket) + : new ObjectEncryption(normalizedServerSideEncryption, effectiveOptions.getSseKmsKeyId()); + object.setServerSideEncryption(encryption.algorithm()); + object.setSseKmsKeyId("aws:kms".equals(encryption.algorithm()) + || "aws:kms:dsse".equals(encryption.algorithm()) + ? encryption.kmsKeyId() : null); if (sseCustomerKey != null) { object.setSseCustomerAlgorithm(sseCustomerKey.algorithm()); @@ -5389,6 +5394,9 @@ public class S3Service implements Resettable, ResourceProvider { if (upload.getSseCustomerAlgorithm() != null) { object.setSseCustomerAlgorithm(upload.getSseCustomerAlgorithm()); object.setSseCustomerKeyMd5(upload.getSseCustomerKeyMd5()); + // Encrypted with the customer's key, not the bucket default the store applied. + object.setServerSideEncryption(null); + object.setSseKmsKeyId(null); } String bucketOwnerAccount = resolveBucketEntry(bucket) .map(AccountAwareStorageBackend.OwnedEntry::account) @@ -7272,6 +7280,27 @@ public class S3Service implements Resettable, ResourceProvider { record SseCustomerKey(String algorithm, String keyMd5) {} + /** The server-side encryption an object is stored with, and its KMS key for {@code aws:kms} and {@code aws:kms:dsse}. */ + private record ObjectEncryption(String algorithm, String kmsKeyId) {} + + /** + * The encryption S3 applies to an object written to {@code bucket} without encryption headers: the + * bucket's default encryption ({@code ApplyServerSideEncryptionByDefault}), or SSE-S3 + * ({@code AES256}) for a bucket with none, the base level of encryption S3 has applied to every + * bucket since January 5, 2023. + */ + private static ObjectEncryption defaultEncryption(Bucket bucket) { + String configuration = bucket.getEncryptionConfiguration(); + String algorithm = configuration == null + ? null + : XmlParser.extractFirst(configuration, "SSEAlgorithm", null); + if (algorithm == null || !SUPPORTED_SERVER_SIDE_ENCRYPTION_VALUES.contains(algorithm.trim())) { + return new ObjectEncryption("AES256", null); + } + String kmsKeyId = XmlParser.extractFirst(configuration, "KMSMasterKeyID", null); + return new ObjectEncryption(algorithm.trim(), kmsKeyId == null || kmsKeyId.isBlank() ? null : kmsKeyId.trim()); + } + record SseCustomerHeaders(String algorithm, String key, String keyMd5) { static final SseCustomerHeaders EMPTY = new SseCustomerHeaders(null, null, null); } diff --git a/src/test/java/io/floci/aws/services/s3/S3DefaultEncryptionIntegrationTest.java b/src/test/java/io/floci/aws/services/s3/S3DefaultEncryptionIntegrationTest.java new file mode 100644 index 0000000000..997f6f8166 --- /dev/null +++ b/src/test/java/io/floci/aws/services/s3/S3DefaultEncryptionIntegrationTest.java @@ -0,0 +1,95 @@ +package io.floci.aws.services.s3; + +import io.floci.aws.testing.S3TestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.core.ResponseInputStream; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.CompletedPart; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.HeadObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.ServerSideEncryption; + +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * S3 encrypts every new object: one uploaded without encryption headers gets the bucket's default + * encryption, SSE-S3 ({@code AES256}) when the bucket has no configuration. PutObject, HeadObject and + * GetObject report it through the AWS SDK. + */ +@QuarkusTest +class S3DefaultEncryptionIntegrationTest { + + private static final String KMS_KEY = "arn:aws:kms:us-east-1:000000000000:key/11111111-2222-3333-4444-555555555555"; + + private S3Client s3; + private String bucket; + + @BeforeEach + void createBucket() { + s3 = S3TestClients.pathStyle(); + bucket = "default-encryption-" + UUID.randomUUID(); + s3.createBucket(r -> r.bucket(bucket)); + } + + @AfterEach + void deleteBucketAndCloseClient() { + S3TestClients.deleteBucket(s3, bucket); + s3.close(); + } + + @Test + void aBucketWithoutConfigurationReportsSseS3OnEveryObject() throws Exception { + PutObjectResponse put = s3.putObject(r -> r.bucket(bucket).key("plain"), RequestBody.fromString("plain")); + + assertEquals(ServerSideEncryption.AES256, put.serverSideEncryption()); + assertEquals(ServerSideEncryption.AES256, head("plain").serverSideEncryption()); + try (ResponseInputStream got = s3.getObject(r -> r.bucket(bucket).key("plain"))) { + assertEquals(ServerSideEncryption.AES256, got.response().serverSideEncryption()); + } + } + + @Test + void aKmsDefaultIsReportedWithItsKey() { + useKmsDefault(); + + PutObjectResponse put = s3.putObject(r -> r.bucket(bucket).key("kms"), RequestBody.fromString("kms")); + + assertEquals(ServerSideEncryption.AWS_KMS, put.serverSideEncryption()); + assertEquals(KMS_KEY, put.ssekmsKeyId()); + HeadObjectResponse head = head("kms"); + assertEquals(ServerSideEncryption.AWS_KMS, head.serverSideEncryption()); + assertEquals(KMS_KEY, head.ssekmsKeyId()); + } + + @Test + void aMultipartUploadCompletesIntoAnObjectWithTheDefault() { + useKmsDefault(); + + String uploadId = s3.createMultipartUpload(r -> r.bucket(bucket).key("multipart")).uploadId(); + String eTag = s3.uploadPart(r -> r.bucket(bucket).key("multipart").uploadId(uploadId).partNumber(1), + RequestBody.fromString("part")).eTag(); + s3.completeMultipartUpload(r -> r.bucket(bucket).key("multipart").uploadId(uploadId) + .multipartUpload(m -> m.parts(CompletedPart.builder().partNumber(1).eTag(eTag).build()))); + + HeadObjectResponse head = head("multipart"); + assertEquals(ServerSideEncryption.AWS_KMS, head.serverSideEncryption()); + assertEquals(KMS_KEY, head.ssekmsKeyId()); + } + + private void useKmsDefault() { + s3.putBucketEncryption(r -> r.bucket(bucket).serverSideEncryptionConfiguration(c -> c.rules(rule -> + rule.applyServerSideEncryptionByDefault(d -> d.sseAlgorithm(ServerSideEncryption.AWS_KMS) + .kmsMasterKeyID(KMS_KEY))))); + } + + private HeadObjectResponse head(String key) { + return s3.headObject(r -> r.bucket(bucket).key(key)); + } +} diff --git a/src/test/java/io/floci/aws/services/s3/S3DefaultEncryptionServiceTest.java b/src/test/java/io/floci/aws/services/s3/S3DefaultEncryptionServiceTest.java new file mode 100644 index 0000000000..5cc97806f6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/s3/S3DefaultEncryptionServiceTest.java @@ -0,0 +1,212 @@ +package io.floci.aws.services.s3; + +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.s3.model.CopyObjectOptions; +import io.floci.aws.services.s3.model.MultipartUpload; +import io.floci.aws.services.s3.model.PutObjectOptions; +import io.floci.aws.services.s3.model.S3Object; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.Base64; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * An object written without encryption headers is encrypted with its bucket's default encryption: + * the configured {@code ApplyServerSideEncryptionByDefault}, or SSE-S3 ({@code AES256}) for a bucket + * with none. An explicit header and an SSE-C key keep taking precedence. + */ +class S3DefaultEncryptionServiceTest { + + private static final String BUCKET = "default-encryption-bucket"; + private static final String SOURCE = "copy-source-bucket"; + private static final String KMS_KEY = "arn:aws:kms:us-east-1:000000000000:key/11111111-2222-3333-4444-555555555555"; + private static final byte[] DATA = "data".getBytes(StandardCharsets.UTF_8); + + @TempDir + Path tempDir; + + private InMemoryStorage objectStore; + private S3Service s3Service; + + @BeforeEach + void setUp() { + objectStore = new InMemoryStorage<>(); + s3Service = new S3Service(new InMemoryStorage<>(), objectStore, tempDir.resolve("s3"), false); + s3Service.createBucket(BUCKET, "us-east-1"); + s3Service.createBucket(SOURCE, "us-east-1"); + } + + @Test + void aBucketWithoutConfigurationEncryptsWithSseS3() { + S3Object put = put("plain.txt", new PutObjectOptions()); + + assertEquals("AES256", put.getServerSideEncryption()); + assertNull(put.getSseKmsKeyId()); + assertEquals("AES256", s3Service.getObject(BUCKET, "plain.txt").getServerSideEncryption()); + } + + @Test + void aKmsDefaultIsAppliedWithItsKey() { + s3Service.putBucketEncryption(BUCKET, configuration("aws:kms", KMS_KEY)); + + S3Object put = put("kms.txt", new PutObjectOptions()); + + assertEquals("aws:kms", put.getServerSideEncryption()); + assertEquals(KMS_KEY, put.getSseKmsKeyId()); + S3Object stored = s3Service.getObject(BUCKET, "kms.txt"); + assertEquals("aws:kms", stored.getServerSideEncryption()); + assertEquals(KMS_KEY, stored.getSseKmsKeyId()); + S3Object posted = s3Service.postObject(BUCKET, "posted.txt", DATA, "text/plain", null); + assertEquals("aws:kms", posted.getServerSideEncryption()); + assertEquals(KMS_KEY, posted.getSseKmsKeyId()); + } + + @Test + void aKmsDefaultWithoutAKeyIsAppliedWithoutOne() { + s3Service.putBucketEncryption(BUCKET, configuration("aws:kms", null)); + + S3Object put = put("kms-default-key.txt", new PutObjectOptions()); + + assertEquals("aws:kms", put.getServerSideEncryption()); + assertNull(put.getSseKmsKeyId()); + } + + @Test + void aDualLayerKmsDefaultIsAppliedWithItsKey() { + s3Service.putBucketEncryption(BUCKET, configuration("aws:kms:dsse", KMS_KEY)); + + S3Object put = put("dsse.txt", new PutObjectOptions()); + + assertEquals("aws:kms:dsse", put.getServerSideEncryption()); + assertEquals(KMS_KEY, put.getSseKmsKeyId()); + } + + @Test + void anExplicitHeaderTakesPrecedenceOverTheDefault() { + s3Service.putBucketEncryption(BUCKET, configuration("aws:kms", KMS_KEY)); + + S3Object put = put("explicit.txt", new PutObjectOptions().withServerSideEncryption("aws:kms")); + + assertEquals("aws:kms", put.getServerSideEncryption()); + assertNotEquals(KMS_KEY, put.getSseKmsKeyId()); + } + + @Test + void anSseCustomerKeyUploadGetsNoDefault() throws Exception { + s3Service.putBucketEncryption(BUCKET, configuration("aws:kms", KMS_KEY)); + + S3Object put = put("sse-c.txt", customerKey(new PutObjectOptions())); + + assertNull(put.getServerSideEncryption()); + assertNull(put.getSseKmsKeyId()); + assertEquals("AES256", put.getSseCustomerAlgorithm()); + } + + @Test + void objectsAlreadyStoredKeepTheirEncryption() { + put("before.txt", new PutObjectOptions()); + s3Service.putBucketEncryption(BUCKET, configuration("aws:kms", KMS_KEY)); + put("after.txt", new PutObjectOptions()); + + assertEquals("AES256", s3Service.getObject(BUCKET, "before.txt").getServerSideEncryption()); + assertEquals("aws:kms", s3Service.getObject(BUCKET, "after.txt").getServerSideEncryption()); + } + + @Test + void aMultipartUploadCompletesIntoAnObjectWithTheDefault() { + s3Service.putBucketEncryption(BUCKET, configuration("aws:kms", KMS_KEY)); + + MultipartUpload upload = s3Service.initiateMultipartUpload(BUCKET, "multipart.bin", + "application/octet-stream", Map.of(), null, new PutObjectOptions()); + s3Service.uploadPart(BUCKET, "multipart.bin", upload.getUploadId(), 1, DATA); + S3Object completed = s3Service.completeMultipartUpload(BUCKET, "multipart.bin", upload.getUploadId(), + List.of(1), null, null); + + assertEquals("aws:kms", completed.getServerSideEncryption()); + assertEquals(KMS_KEY, completed.getSseKmsKeyId()); + assertEquals("aws:kms", s3Service.getObject(BUCKET, "multipart.bin").getServerSideEncryption()); + } + + @Test + void anSseCustomerKeyMultipartUploadGetsNoDefault() throws Exception { + s3Service.putBucketEncryption(BUCKET, configuration("aws:kms", KMS_KEY)); + PutObjectOptions sseC = customerKey(new PutObjectOptions()); + MultipartUpload upload = s3Service.initiateMultipartUpload(BUCKET, "multipart-sse-c.bin", + "application/octet-stream", Map.of(), null, sseC); + s3Service.uploadPart(BUCKET, "multipart-sse-c.bin", upload.getUploadId(), 1, DATA, + sseC.getSseCustomerAlgorithm(), sseC.getSseCustomerKey(), sseC.getSseCustomerKeyMd5()); + S3Object completed = s3Service.completeMultipartUpload(BUCKET, "multipart-sse-c.bin", upload.getUploadId(), + List.of(1), null, null); + + assertNull(completed.getServerSideEncryption()); + assertNull(completed.getSseKmsKeyId()); + assertEquals("AES256", completed.getSseCustomerAlgorithm()); + assertNull(s3Service.getObject(BUCKET, "multipart-sse-c.bin").getServerSideEncryption()); + } + + @Test + void aConfigurationWithoutAnAlgorithmFallsBackToSseS3() { + s3Service.putBucketEncryption(BUCKET, ""); + assertEquals("AES256", put("empty-configuration.txt", new PutObjectOptions()).getServerSideEncryption()); + + s3Service.putBucketEncryption(BUCKET, configuration("aws:unknown", null)); + assertEquals("AES256", put("unsupported-algorithm.txt", new PutObjectOptions()).getServerSideEncryption()); + + s3Service.putBucketEncryption(BUCKET, "not xml"); + assertEquals("AES256", put("malformed-configuration.txt", new PutObjectOptions()).getServerSideEncryption()); + } + + @Test + void aCopyOfASourceWithNoStoredEncryptionTakesTheDestinationBucketsDefault() throws Exception { + s3Service.putObject(SOURCE, "old.txt", DATA, "text/plain", null, new PutObjectOptions()); + objectStore.scan(key -> true).forEach(object -> object.setServerSideEncryption(null)); + PutObjectOptions sseC = customerKey(new PutObjectOptions()); + s3Service.putObject(SOURCE, "sse-c.txt", DATA, "text/plain", null, sseC); + s3Service.putBucketEncryption(BUCKET, configuration("aws:kms", KMS_KEY)); + + S3Object fromOld = s3Service.copyObject(SOURCE, "old.txt", BUCKET, "old-copy.txt"); + S3Object fromSseC = s3Service.copyObject(SOURCE, "sse-c.txt", BUCKET, "sse-c-copy.txt", null, + new CopyObjectOptions() + .withCopySourceSseCustomerAlgorithm(sseC.getSseCustomerAlgorithm()) + .withCopySourceSseCustomerKey(sseC.getSseCustomerKey()) + .withCopySourceSseCustomerKeyMd5(sseC.getSseCustomerKeyMd5())); + + for (S3Object copy : List.of(fromOld, fromSseC)) { + assertEquals("aws:kms", copy.getServerSideEncryption()); + assertEquals(KMS_KEY, copy.getSseKmsKeyId()); + assertNull(copy.getSseCustomerAlgorithm()); + } + } + + private S3Object put(String key, PutObjectOptions options) { + return s3Service.putObject(BUCKET, key, DATA, "text/plain", null, options); + } + + private static String configuration(String algorithm, String kmsKeyId) { + return "" + + "" + algorithm + "" + + (kmsKeyId == null ? "" : "" + kmsKeyId + "") + + ""; + } + + private static PutObjectOptions customerKey(PutObjectOptions options) throws Exception { + byte[] key = new byte[32]; + for (int i = 0; i < key.length; i++) { + key[i] = (byte) i; + } + byte[] md5 = MessageDigest.getInstance("MD5").digest(key); + return options.withSseCustomerAlgorithm("AES256") + .withSseCustomerKey(Base64.getEncoder().encodeToString(key)) + .withSseCustomerKeyMd5(Base64.getEncoder().encodeToString(md5)); + } +} diff --git a/src/test/java/io/floci/aws/services/s3/S3ServiceTest.java b/src/test/java/io/floci/aws/services/s3/S3ServiceTest.java index 3a5741378a..a13409d361 100644 --- a/src/test/java/io/floci/aws/services/s3/S3ServiceTest.java +++ b/src/test/java/io/floci/aws/services/s3/S3ServiceTest.java @@ -295,7 +295,7 @@ class S3ServiceTest { } @Test - void putObjectTrimsBlankServerSideEncryptionToAbsent() { + void putObjectTreatsBlankServerSideEncryptionAsAbsentAndAppliesTheBucketDefault() { s3Service.createBucket("test-bucket", "us-east-1"); S3Object put = s3Service.putObject( @@ -307,7 +307,7 @@ class S3ServiceTest { new PutObjectOptions().withServerSideEncryption(" ") ); - assertNull(put.getServerSideEncryption()); + assertEquals("AES256", put.getServerSideEncryption()); } @Test