fix(s3): preserve encryption fields on browser POST uploads (#7646)

fix(s3): authorize POST encryption settings and report them

fix(s3): reject incompatible POST encryption fields

fix(s3): normalize POST encryption before authorization
This commit is contained in:
Joe Ebmeier authored and GitHub committed 2026-11-06 19:47:59 -04:00
1 parent 8bc134cc84
commit d9f0bab177
7 files changed
+343 -10

No files matched your search

+2 -2
View File
@@ -771,8 +771,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, replayed on `GetObject` and `HeadObject`
- SSE-KMS key IDs from `x-amz-server-side-encryption-aws-kms-key-id` on `PutObject` 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
- 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
Current limitations:
@@ -1456,8 +1456,13 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
* query credential names.
*/
public void authorizePostObject(String authorizationHeader, String resource, String region) {
authorizePostObject(authorizationHeader, resource, region, null);
}
public void authorizePostObject(String authorizationHeader, String resource, String region,
Map<String, List<String>> requestConditions) {
authorizeAdditionalResource(authorizationHeader, "s3:PutObject", resource, null, null,
new DeniedEvent("PostObject", region), null);
new DeniedEvent("PostObject", region), requestConditions);
}
/** A CloudTrail record to write when IAM refuses a request: its event name and its Region. */
@@ -4118,6 +4118,14 @@ public class S3Controller {
for (Map.Entry<String, String> e : fields.entrySet()) {
lcFields.put(e.getKey().toLowerCase(Locale.ROOT), e.getValue());
}
String encryption = S3Service.normalizeServerSideEncryption(
lcFields.get("x-amz-server-side-encryption"));
String kmsKeyId = lcFields.get("x-amz-server-side-encryption-aws-kms-key-id");
if (kmsKeyId != null && !"aws:kms".equals(encryption) && !"aws:kms:dsse".equals(encryption)) {
throw new AwsException("InvalidArgument",
"KMS key ID requires aws:kms or aws:kms:dsse server-side encryption.", 400);
}
Map<String, List<String>> requestConditions = S3ObjectActions.encryptionConditions(encryption, kmsKeyId);
/*
* IamEnforcementFilter's own filter() method only ever sees the Authorization header or,
@@ -4134,11 +4142,11 @@ public class S3Controller {
if (credential != null && !credential.isEmpty()) {
iamEnforcementFilter.authorizePostObject(AccountResolver.SIGV4_SCHEME + " Credential=" + credential,
S3PublicAccessEvaluator.objectArn(s3Service.bucketPartition(bucket), bucket, key),
regionResolver.resolveRegionFromPresignedCredential(credential));
regionResolver.resolveRegionFromPresignedCredential(credential), requestConditions);
}
if (s3Service.isAuthEnforced() || (config.auth().validateSignatures() && isSignedPost(lcFields))) {
validatePresignedPostAuth(lcFields, bucket, key, fileData.length);
validatePresignedPostAuth(lcFields, bucket, key, fileData.length, requestConditions);
} else {
// Validate policy conditions if present
String policy = lcFields.get("policy");
@@ -4168,7 +4176,9 @@ public class S3Controller {
}
S3Object obj = s3Service.postObject(bucket, key, fileData, objectContentType,
metadata.isEmpty() ? null : metadata);
metadata.isEmpty() ? null : metadata, new PutObjectOptions()
.withServerSideEncryption(encryption)
.withSseKmsKeyId(kmsKeyId));
LOG.infov("Presigned POST upload: {0}/{1} ({2} bytes)", bucket, key, fileData.length);
String xml = new XmlBuilder()
@@ -4183,6 +4193,12 @@ public class S3Controller {
var response = Response.status(204)
.header("ETag", obj.getETag())
.header("Location", bucket + "/" + key);
if (obj.getServerSideEncryption() != null) {
response.header("x-amz-server-side-encryption", obj.getServerSideEncryption());
}
if (obj.getSseKmsKeyId() != null) {
response.header("x-amz-server-side-encryption-aws-kms-key-id", obj.getSseKmsKeyId());
}
if (obj.getVersionId() != null) {
response.header("x-amz-version-id", obj.getVersionId());
}
@@ -4225,7 +4241,8 @@ public class S3Controller {
* SigV4-signed by a known secret key referenced through {@code x-amz-credential}, matching
* real S3's behavior of rejecting fabricated or absent credentials with 403 AccessDenied.
*/
private void validatePresignedPostAuth(Map<String, String> fields, String bucket, String key, int contentLength) {
private void validatePresignedPostAuth(Map<String, String> fields, String bucket, String key, int contentLength,
Map<String, List<String>> requestConditions) {
String policy = fields.get("policy");
String credential = fields.get("x-amz-credential");
String signature = fields.get("x-amz-signature");
@@ -4263,8 +4280,8 @@ public class S3Controller {
// Route through the same bucket-policy/ACL check every other S3 write path uses, so this
// path automatically inherits any future strengthening there too.
s3Service.authorizeObjectWrite(bucket, key, "s3:PutObject",
new S3Service.RequestAuthorization(true, accessKeyId, sessionToken));
s3Service.authorizeObjectWrite(bucket, key, null, "s3:PutObject",
new S3Service.RequestAuthorization(true, accessKeyId, sessionToken), requestConditions);
validatePolicyExpiration(policy);
validatePolicyConditions(policy, bucket, fields, contentLength);
@@ -944,6 +944,7 @@ public class S3Service implements Resettable, ResourceProvider {
object.setCacheControl(effectiveOptions.getCacheControl());
object.setServerSideEncryption(normalizedServerSideEncryption);
object.setSseKmsKeyId("aws:kms".equals(normalizedServerSideEncryption)
|| "aws:kms:dsse".equals(normalizedServerSideEncryption)
? effectiveOptions.getSseKmsKeyId()
: null);
if (sseCustomerKey != null) {
@@ -7,12 +7,17 @@ import io.floci.aws.testutil.S3RequestSigner;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.specification.RequestSpecification;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
@@ -539,7 +544,110 @@ class S3PresignedPostAuthEnforcementIntegrationTest {
.body("Error.Code", equalTo("AccessDenied"));
}
/** Removes {@link #BUCKET}, which the tests from {@code createBucket} on share, with the objects they uploaded. */
@ParameterizedTest
@CsvSource({
"x-amz-server-side-encryption,StringNotEquals,204",
"x-amz-server-side-encryption,StringEquals,403",
"x-amz-server-side-encryption-aws-kms-key-id,StringNotEquals,204",
"x-amz-server-side-encryption-aws-kms-key-id,StringEquals,403"
})
@Order(35)
void presignedPostUsesBucketEncryptionConditionsFromForm(String field, String operator, int expectedStatus) {
String bucket = "presigned-post-encryption-" + expectedStatus + "-"
+ (field.endsWith("key-id") ? "key" : "method");
String key = "uploads/encrypted.txt";
String value = field.endsWith("key-id") ? "approved-key" : "aws:kms";
createBucket(bucket);
putBucketPolicy(bucket, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Principal":"*","Action":"s3:PutObject",
"Resource":"arn:aws:s3:::%s/*","Condition":{"%s":{"s3:%s":"%s"}}}
]}""".formatted(bucket, operator, field, value));
String policy = """
{"expiration":"%s","conditions":[
{"bucket":"%s"},{"key":"%s"},
{"x-amz-server-side-encryption":"aws:kms"},
{"x-amz-server-side-encryption-aws-kms-key-id":"approved-key"}
]}""".formatted(Instant.now().plusSeconds(3600), bucket, key);
String policyBase64 = Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));
String credential = LEGACY_ACCESS_KEY_ID + "/20260101/us-east-1/s3/aws4_request";
given()
.header(field, "header-only-value")
.multiPart("key", key)
.multiPart("policy", policyBase64)
.multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")
.multiPart("x-amz-credential", credential)
.multiPart("x-amz-date", AMZ_DATE)
.multiPart("x-amz-signature", signPolicy(policyBase64, credential, LEGACY_SECRET_KEY))
.multiPart("X-Amz-Server-Side-Encryption", "aws:kms")
.multiPart("X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id", "approved-key")
.multiPart("file", "encrypted.txt", "encrypted".getBytes(StandardCharsets.UTF_8), "text/plain")
.when()
.post("/" + bucket)
.then()
.statusCode(expectedStatus);
given()
.filter(S3RequestSigner.signedAs(LEGACY_ACCESS_KEY_ID, LEGACY_SECRET_KEY))
.when()
.get("/" + bucket + "/" + key)
.then()
.statusCode(expectedStatus == 403 ? 404 : 200);
}
@ParameterizedTest
@NullSource
@ValueSource(strings = "AES256")
@Order(36)
void presignedPostRejectsKmsKeyWithoutKmsEncryption(String encryption) {
String bucket = "presigned-post-invalid-kms-" + (encryption == null ? "missing" : "aes256");
String key = "uploads/invalid.txt";
createBucket(bucket);
putBucketPolicy(bucket, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Principal":"*","Action":"s3:PutObject",
"Resource":"arn:aws:s3:::%s/*",
"Condition":{"StringNotEquals":{"s3:x-amz-server-side-encryption-aws-kms-key-id":"approved-key"}}}
]}""".formatted(bucket));
String encryptionCondition = encryption == null ? ""
: "{\"x-amz-server-side-encryption\":\"%s\"},".formatted(encryption);
String policy = """
{"expiration":"%s","conditions":[
{"bucket":"%s"},{"key":"%s"},%s
{"x-amz-server-side-encryption-aws-kms-key-id":"approved-key"}
]}""".formatted(Instant.now().plusSeconds(3600), bucket, key, encryptionCondition);
String policyBase64 = Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));
String credential = LEGACY_ACCESS_KEY_ID + "/20260101/us-east-1/s3/aws4_request";
RequestSpecification upload = given()
.header("x-amz-server-side-encryption", "aws:kms")
.multiPart("key", key)
.multiPart("policy", policyBase64)
.multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")
.multiPart("x-amz-credential", credential)
.multiPart("x-amz-date", AMZ_DATE)
.multiPart("x-amz-signature", signPolicy(policyBase64, credential, LEGACY_SECRET_KEY))
.multiPart("X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id", "approved-key")
.multiPart("file", "invalid.txt", "invalid".getBytes(StandardCharsets.UTF_8), "text/plain");
if (encryption != null) {
upload.multiPart("X-Amz-Server-Side-Encryption", encryption);
}
upload.when()
.post("/" + bucket)
.then()
.statusCode(400)
.body("Error.Code", equalTo("InvalidArgument"));
given()
.filter(S3RequestSigner.signedAs(LEGACY_ACCESS_KEY_ID, LEGACY_SECRET_KEY))
.when()
.get("/" + bucket + "/" + key)
.then()
.statusCode(404);
}
/** Removes {@link #BUCKET}, which the tests from {@code createBucket} on share, with the objects they uploaded. */
@Test
@Order(99)
void cleanup_removeTheSharedBucket() {
@@ -7,9 +7,12 @@ import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -260,6 +263,103 @@ class S3PresignedPostIamOnlyEnforcementIntegrationTest {
}
}
@ParameterizedTest
@CsvSource({
"x-amz-server-side-encryption,Allow,aws:kms",
"x-amz-server-side-encryption,Deny,aws:kms",
"x-amz-server-side-encryption-aws-kms-key-id,Allow,aws:kms",
"x-amz-server-side-encryption-aws-kms-key-id,Deny,aws:kms",
"x-amz-server-side-encryption,Allow,' aws:kms '",
"x-amz-server-side-encryption,Deny,' aws:kms '"
})
void presignedPostUsesEncryptionConditionsFromForm(String field, String effect, String encryption) {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "presigned-post-encryption-" + suffix;
String userName = "presigned-post-encryption-user-" + suffix;
String value = field.endsWith("key-id") ? "approved-key" : "aws:kms";
boolean isDenied = "Deny".equals(effect);
createBucketAsRoot(bucket);
String accessKeyId = createUser(userName);
if (isDenied) {
putUserPolicy(userName, "AllowPutObject", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:PutObject","Resource":"*"}
]}""");
}
putUserPolicy(userName, "EncryptionCondition", """
{"Version":"2012-10-17","Statement":[
{"Effect":"%s","Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/*",
"Condition":{"StringEquals":{"s3:%s":"%s"}}}
]}""".formatted(effect, bucket, field, value));
given()
.header(field, "header-only-value")
.multiPart("key", "encrypted.txt")
.multiPart("x-amz-credential", presignedCredential(accessKeyId))
.multiPart("X-Amz-Server-Side-Encryption", encryption)
.multiPart("X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id", "approved-key")
.multiPart("file", "encrypted.txt", "encrypted".getBytes(StandardCharsets.UTF_8), "text/plain")
.when()
.post("/" + bucket)
.then()
.statusCode(isDenied ? 403 : 204);
given()
.header("Authorization", auth("test", "s3"))
.when()
.get("/" + bucket + "/encrypted.txt")
.then()
.statusCode(isDenied ? 404 : 200);
}
@ParameterizedTest
@CsvSource({
",Allow,StringEquals",
"AES256,Allow,StringEquals",
",Deny,StringNotEquals",
"AES256,Deny,StringNotEquals"
})
void presignedPostRejectsKmsKeyWithoutKmsEncryption(String encryption, String effect, String operator) {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "presigned-post-invalid-kms-" + suffix;
String userName = "presigned-post-invalid-kms-user-" + suffix;
createBucketAsRoot(bucket);
String accessKeyId = createUser(userName);
if ("Deny".equals(effect)) {
putUserPolicy(userName, "AllowPutObject", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:PutObject","Resource":"*"}
]}""");
}
putUserPolicy(userName, "EncryptionCondition", """
{"Version":"2012-10-17","Statement":[
{"Effect":"%s","Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/*",
"Condition":{"%s":{"s3:x-amz-server-side-encryption-aws-kms-key-id":"approved-key"}}}
]}""".formatted(effect, bucket, operator));
RequestSpecification upload = given()
.header("x-amz-server-side-encryption", "aws:kms")
.multiPart("key", "invalid.txt")
.multiPart("x-amz-credential", presignedCredential(accessKeyId))
.multiPart("X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id", "approved-key")
.multiPart("file", "invalid.txt", "invalid".getBytes(StandardCharsets.UTF_8), "text/plain");
if (encryption != null) {
upload.multiPart("X-Amz-Server-Side-Encryption", encryption);
}
upload.when()
.post("/" + bucket)
.then()
.statusCode(400)
.body("Error.Code", equalTo("InvalidArgument"));
given()
.header("Authorization", auth("test", "s3"))
.when()
.get("/" + bucket + "/invalid.txt")
.then()
.statusCode(404);
}
private static void cloudTrail(String region, String operation, String body) {
given()
.header("Authorization", auth("test", "cloudtrail", region))
@@ -7,6 +7,8 @@ import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
@@ -790,6 +792,106 @@ class S3PresignedPostIntegrationTest {
""".formatted(expiration, bucket, keyPrefix, contentTypePrefix, minSize, maxSize);
}
@Test
@Order(104)
void presignedPostAcceptsAes256WithoutKmsKey() {
String bucket = "presigned-post-aes256-bucket";
String key = "uploads/aes256.txt";
String content = "valid AES256 form";
given().put("/" + bucket).then().statusCode(200);
given()
.multiPart("key", key)
.multiPart("x-amz-server-side-encryption", "AES256")
.multiPart("file", "aes256.txt", content.getBytes(StandardCharsets.UTF_8), "text/plain")
.when()
.post("/" + bucket)
.then()
.statusCode(204)
.header("x-amz-server-side-encryption", equalTo("AES256"))
.header("x-amz-server-side-encryption-aws-kms-key-id", nullValue());
given()
.when()
.head("/" + bucket + "/" + key)
.then()
.statusCode(200)
.header("x-amz-server-side-encryption", equalTo("AES256"))
.header("x-amz-server-side-encryption-aws-kms-key-id", nullValue());
given()
.when()
.get("/" + bucket + "/" + key)
.then()
.statusCode(200)
.header("x-amz-server-side-encryption", equalTo("AES256"))
.header("x-amz-server-side-encryption-aws-kms-key-id", nullValue())
.body(equalTo(content));
}
@ParameterizedTest
@ValueSource(strings = {"aws:kms", "aws:kms:dsse"})
@Order(105)
void presignedPostPreservesKmsEncryptionOnEachVersion(String encryption) {
String bucket = "presigned-post-kms-bucket-" + encryption.replace(':', '-');
String key = "uploads/encrypted.txt";
String[] kmsKeys = {
"arn:aws:kms:us-east-1:000000000000:key/11111111-1111-1111-1111-111111111111",
"arn:aws:kms:us-east-1:000000000000:key/22222222-2222-2222-2222-222222222222"
};
String[] versionIds = new String[kmsKeys.length];
given().put("/" + bucket).then().statusCode(200);
given()
.body("<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>")
.when()
.put("/" + bucket + "?versioning")
.then()
.statusCode(200);
for (int index = 0; index < kmsKeys.length; index++) {
versionIds[index] = given()
.multiPart("key", key)
.multiPart("x-amz-server-side-encryption", encryption)
.multiPart("x-amz-server-side-encryption-aws-kms-key-id", kmsKeys[index])
.multiPart("file", "encrypted.txt",
("version-" + index).getBytes(StandardCharsets.UTF_8), "text/plain")
.when()
.post("/" + bucket)
.then()
.statusCode(204)
.header("x-amz-server-side-encryption", equalTo(encryption))
.header("x-amz-server-side-encryption-aws-kms-key-id", equalTo(kmsKeys[index]))
.extract().header("x-amz-version-id");
assertThat(versionIds[index], notNullValue());
}
assertThat(versionIds[0], not(equalTo(versionIds[1])));
for (int index = 0; index < kmsKeys.length; index++) {
given()
.queryParam("versionId", versionIds[index])
.header("x-amz-checksum-mode", "ENABLED")
.when()
.head("/" + bucket + "/" + key)
.then()
.statusCode(200)
.header("x-amz-version-id", equalTo(versionIds[index]))
.header("x-amz-server-side-encryption", equalTo(encryption))
.header("x-amz-server-side-encryption-aws-kms-key-id", equalTo(kmsKeys[index]))
.header("x-amz-checksum-crc64nvme", notNullValue());
given()
.queryParam("versionId", versionIds[index])
.when()
.get("/" + bucket + "/" + key)
.then()
.statusCode(200)
.header("x-amz-server-side-encryption", equalTo(encryption))
.header("x-amz-server-side-encryption-aws-kms-key-id", equalTo(kmsKeys[index]))
.body(equalTo("version-" + index));
}
}
@Test
@Order(110)
void presignedPostReturnsVersionIdOnAVersionedBucket() {