mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(s3): place the encryption condition keys on a put, and on a part from its upload (#7050)
* fix(s3): place the encryption condition keys on a put, and on a part from its upload A policy on s3:x-amz-server-side-encryption or s3:x-amz-server-side-encryption-aws-kms-key-id read neither key, so a Deny under a negated operator refused every put, encrypted or not. A PutObject, CopyObject or CreateMultipartUpload now carries both from its headers, each value as sent, in the enforcement filter and in S3's own bucket policy check. A part or a completion sends neither header and carries what its upload recorded when it was created. A part naming an upload not held answers NoSuchUpload, as S3 does under such a policy. * fix(s3): check as an object write a PUT or POST naming an upload but not routed as a part The enforcement filter let through a request naming an upload not held, and judged one naming a held upload by that upload's encryption, on uploadId alone. A PUT with no partNumber, or a POST asking for a new upload, creates an object or an upload whatever that parameter says, so it skipped IAM or read the wrong encryption. Both now match the routes S3Controller takes as a part or a completion. A part copy naming an upload not held stays checked, since it names a source. * test(s3): put the multipart encryption cases beside kmsOnlyBucket The multipart cases copied S3BucketPolicyEnforcementIntegrationTest's two-statement KMS-only policy and BUCKET_KEY. They now sit beside kmsOnlyBucket and reuse it, with the policy written once (putKmsOnlyPolicy). The two cases whose upload is opened before the policy stands use a bucket with no default encryption, as before: S3 records the bucket's default on an upload that asks for none, where Floci records only what the request asks for.
This commit is contained in:
1 parent
1b4f99cb8a
commit
fccc81b61d
8 files changed
+376
-7
No files matched your search
@@ -2521,6 +2521,16 @@ floci populates:
|
||||
body). AWS does not document how it counts the remaining retention days; floci counts a part
|
||||
day as a whole one, so a Deny on retention longer than N days refuses a date a few hours past
|
||||
N days.
|
||||
- `s3:x-amz-server-side-encryption` and `s3:x-amz-server-side-encryption-aws-kms-key-id`: the
|
||||
encryption a request asks for, for `s3:PutObject`, from the `x-amz-server-side-encryption` and
|
||||
`x-amz-server-side-encryption-aws-kms-key-id` headers of a `PutObject`, `CopyObject` or
|
||||
`CreateMultipartUpload`. The value is the header's text: an alias or a bare key id is not resolved
|
||||
to an ARN, and a bucket's default encryption fills neither key. A part or a
|
||||
`CompleteMultipartUpload` sends neither header and carries what its upload recorded when it was
|
||||
created. An upload holds only what its creation asked for, so one created with no encryption
|
||||
carries neither key, where S3 gives it the bucket's default. A part naming an upload floci does
|
||||
not hold answers `NoSuchUpload`, as on AWS, whatever the policy says, unless it copies from a
|
||||
source.
|
||||
- An object creation offers its tag and Object Lock keys to each action it is checked as: its
|
||||
`s3:PutObject` and the extra actions its settings need.
|
||||
- `iam:PassedToService`: the service principal a request passes a role to, for the
|
||||
|
||||
+1
-1
@@ -428,7 +428,7 @@ When `FLOCI_SERVICES_S3_ENFORCE_AUTH` or `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED
|
||||
- The bucket's attached policy document (configured via `PutBucketPolicy`) is retrieved.
|
||||
- The caller's authenticated principal ARN is resolved from the signing credentials (for example, `arn:aws:iam::<account>:user/<name>`, `arn:aws:iam::<account>:role/<name>`, or `arn:aws:iam::<account>:root`).
|
||||
- Policy statements are evaluated for the requested S3 action (e.g. `s3:GetObject`, `s3:PutObject`, `s3:PutBucketPolicy`) and resource ARN (`arn:aws:s3:::bucket` or `arn:aws:s3:::bucket/key`).
|
||||
- An object request is checked as the actions IAM checks for it (see [IAM](iam.md)): the version action when it names a `versionId`, and the actions it needs besides its own, such as `s3:PutObjectTagging` for an object created with tags. The policy is offered the tags and Object Lock settings the request sets (`s3:RequestObjectTag/<key>`, `s3:RequestObjectTagKeys` and the `s3:object-lock-*` keys) besides the keys that say who is calling, but not the other S3 keys, such as `s3:ExistingObjectTag` or `s3:versionid`. An anonymous request's public-policy check is offered none. An anonymous object creation that a public bucket ACL's `WRITE` grant admits may also apply its ACL, tags and Object Lock settings, since an ACL grant names no actions, unless a public bucket policy decides the setting's action.
|
||||
- An object request is checked as the actions IAM checks for it (see [IAM](iam.md)): the version action when it names a `versionId`, and the actions it needs besides its own, such as `s3:PutObjectTagging` for an object created with tags. The policy is offered the tags and Object Lock settings the request sets (`s3:RequestObjectTag/<key>`, `s3:RequestObjectTagKeys` and the `s3:object-lock-*` keys) and the encryption it asks for (`s3:x-amz-server-side-encryption` and `s3:x-amz-server-side-encryption-aws-kms-key-id`, from its headers, or for a part or a completion from what its upload recorded; see [IAM](iam.md)) besides the keys that say who is calling, but not the other S3 keys, such as `s3:ExistingObjectTag` or `s3:versionid`. An anonymous request's public-policy check is offered none. An anonymous object creation that a public bucket ACL's `WRITE` grant admits may also apply its ACL, tags and Object Lock settings, since an ACL grant names no actions, unless a public bucket policy decides the setting's action.
|
||||
|
||||
### Supported Principal Types
|
||||
|
||||
|
||||
+53
-4
@@ -87,6 +87,8 @@ public class IamConditionContextResolver {
|
||||
public static final String OBJECT_LOCK_RETAIN_UNTIL_DATE = "s3:object-lock-retain-until-date";
|
||||
public static final String OBJECT_LOCK_REMAINING_RETENTION_DAYS = "s3:object-lock-remaining-retention-days";
|
||||
public static final String OBJECT_LOCK_LEGAL_HOLD = "s3:object-lock-legal-hold";
|
||||
public static final String SERVER_SIDE_ENCRYPTION = "s3:x-amz-server-side-encryption";
|
||||
public static final String SERVER_SIDE_ENCRYPTION_KMS_KEY_ID = "s3:x-amz-server-side-encryption-aws-kms-key-id";
|
||||
static final String REQUEST_AUTH_TYPE = "lambda:Request/WebFunctionAuthType";
|
||||
static final String RESOURCE_AUTH_TYPE = "lambda:Resource/WebFunctionAuthType";
|
||||
|
||||
@@ -403,10 +405,13 @@ public class IamConditionContextResolver {
|
||||
"s3:PutObjectVersionAnnotation", "s3:DeleteObjectAnnotation",
|
||||
"s3:DeleteObjectVersionAnnotation" -> s3ExistingObjectTagConditionContext(ctx);
|
||||
// The Object Lock keys come from what the request sets: an object creation's headers, the
|
||||
// retention and legal-hold bodies.
|
||||
case "s3:PutObject" -> S3ObjectActions.objectCreationConditions(ctx::getHeaderString,
|
||||
s3RequestTagging(ctx), S3ObjectActions.isCopy(ctx.getMethod(), ctx::getHeaderString),
|
||||
clock.instant());
|
||||
// retention and legal-hold bodies. A part or a completion creates nothing from its own
|
||||
// headers, and is judged by the encryption its upload recorded.
|
||||
case "s3:PutObject" -> isPartOrCompletion(ctx)
|
||||
? s3UploadEncryptionConditionContext(ctx)
|
||||
: S3ObjectActions.objectCreationConditions(ctx::getHeaderString,
|
||||
s3RequestTagging(ctx), S3ObjectActions.isCopy(ctx.getMethod(), ctx::getHeaderString),
|
||||
clock.instant());
|
||||
case "s3:PutObjectRetention" -> S3ObjectActions.retentionBodyConditions(bodyText(ctx), clock.instant());
|
||||
case "s3:PutObjectLegalHold" -> S3ObjectActions.legalHoldBodyConditions(bodyText(ctx), clock.instant());
|
||||
case "s3:PutObjectTagging", "s3:PutObjectVersionTagging" -> merge(
|
||||
@@ -415,6 +420,50 @@ public class IamConditionContextResolver {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The encryption keys of a part or a completion: what its upload recorded when it was created, as
|
||||
* measured on S3, since a part sends neither header. An upload not held offers neither.
|
||||
*/
|
||||
private Map<String, List<String>> s3UploadEncryptionConditionContext(ContainerRequestContext ctx) {
|
||||
if (!s3Service.isResolvable()) {
|
||||
return null;
|
||||
}
|
||||
String bucket = s3BucketName(ctx.getUriInfo().getPath());
|
||||
try {
|
||||
return s3Service.get().multipartEncryptionConditions(bucket, s3RequestObjectKey(ctx, bucket),
|
||||
ctx.getUriInfo().getQueryParameters().getFirst("uploadId"));
|
||||
} catch (AwsException expected) {
|
||||
// The handler answers an upload not held as NoSuchUpload; here it offers no keys.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A part or a completion as S3Controller routes them: a PUT naming an upload and a part number, or a
|
||||
* POST naming an upload and not asking for a new one. Any other PUT or POST naming an {@code uploadId}
|
||||
* creates an object or an upload, whatever that parameter says, and is judged by its own headers.
|
||||
*/
|
||||
private static boolean isPartOrCompletion(ContainerRequestContext ctx) {
|
||||
MultivaluedMap<String, String> params = ctx.getUriInfo().getQueryParameters();
|
||||
if (!params.containsKey("uploadId")) {
|
||||
return false;
|
||||
}
|
||||
return "PUT".equalsIgnoreCase(ctx.getMethod())
|
||||
? params.containsKey("partNumber")
|
||||
: "POST".equalsIgnoreCase(ctx.getMethod()) && !params.containsKey("uploads");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a request checked as {@code s3:PutObject} is a part or a completion of an upload S3 does
|
||||
* not hold. There is no encryption to judge it by, and S3 answers it {@code NoSuchUpload} under a
|
||||
* policy on the encryption keys, as measured.
|
||||
*/
|
||||
boolean namesUploadNotHeld(String action, ContainerRequestContext ctx) {
|
||||
return "s3:PutObject".equals(action) && isPartOrCompletion(ctx)
|
||||
&& ctx.getHeaderString("x-amz-copy-source") == null
|
||||
&& s3UploadEncryptionConditionContext(ctx) == null && s3Service.isResolvable();
|
||||
}
|
||||
|
||||
private static String bodyText(ContainerRequestContext ctx) {
|
||||
byte[] body = bufferEntity(ctx);
|
||||
return body == null ? null : new String(body, StandardCharsets.UTF_8);
|
||||
|
||||
@@ -535,6 +535,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
}
|
||||
}
|
||||
|
||||
// A policy on the encryption keys would refuse this for keys it cannot have: the handler answers it.
|
||||
if (conditionContextResolver.namesUploadNotHeld(action, ctx)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, List<String>> conditionContext = conditionContextResolver.resolve(credentialScope, action, ctx);
|
||||
// A request naming several resources is authorized once per resource, as on AWS, so a
|
||||
// permitted first target cannot carry later targets that the policy does not allow.
|
||||
|
||||
@@ -911,7 +911,7 @@ public class S3Controller {
|
||||
}
|
||||
|
||||
if (uploadId != null && partNumber != null) {
|
||||
s3Service.authorizeObjectWrite(bucket, key, "s3:PutObject", authorization);
|
||||
s3Service.authorizeMultipartWrite(bucket, key, uploadId, authorization);
|
||||
int parsedPartNumber = PartRange.parseUploadPartNumber(partNumber);
|
||||
if (copySource != null && !copySource.isEmpty()) {
|
||||
return handleUploadPartCopy(copySource, bucket, key, uploadId, parsedPartNumber,
|
||||
@@ -1728,7 +1728,7 @@ public class S3Controller {
|
||||
}
|
||||
|
||||
if (uploadId != null) {
|
||||
s3Service.authorizeObjectWrite(bucket, key, "s3:PutObject", authorization);
|
||||
s3Service.authorizeMultipartWrite(bucket, key, uploadId, authorization);
|
||||
authorizeConditionalWriteRead(bucket, key, ifMatch, authorization);
|
||||
List<CompletedPart> completedParts = parseCompleteMultipartBody(new String(body, StandardCharsets.UTF_8));
|
||||
List<Integer> partNumbers = completedParts.stream().map(CompletedPart::partNumber).toList();
|
||||
|
||||
@@ -156,9 +156,27 @@ public final class S3ObjectActions {
|
||||
if (lock != null) {
|
||||
conditions.putAll(lock);
|
||||
}
|
||||
conditions.putAll(encryptionConditions(header.apply("x-amz-server-side-encryption"),
|
||||
header.apply("x-amz-server-side-encryption-aws-kms-key-id")));
|
||||
return conditions.isEmpty() ? null : conditions;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code s3:x-amz-server-side-encryption} and {@code s3:x-amz-server-side-encryption-aws-kms-key-id}
|
||||
* as the request asks for them, each value as sent: an alias or a bare key id is not resolved to an
|
||||
* ARN, and a bucket's default encryption fills neither.
|
||||
*/
|
||||
public static Map<String, List<String>> encryptionConditions(String encryption, String kmsKeyId) {
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
if (encryption != null && !encryption.isBlank()) {
|
||||
conditions.put(IamConditionContextResolver.SERVER_SIDE_ENCRYPTION, List.of(encryption));
|
||||
}
|
||||
if (kmsKeyId != null && !kmsKeyId.isBlank()) {
|
||||
conditions.put(IamConditionContextResolver.SERVER_SIDE_ENCRYPTION_KMS_KEY_ID, List.of(kmsKeyId));
|
||||
}
|
||||
return conditions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the new object gets the request's {@code x-amz-tagging}: a PutObject's and a
|
||||
* CreateMultipartUpload's always, a CopyObject's only under {@code x-amz-tagging-directive:
|
||||
|
||||
@@ -5425,6 +5425,22 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
return getMultipartUpload(bucket, key, uploadId);
|
||||
}
|
||||
|
||||
/** The encryption condition keys of an upload's parts and completion: what it recorded when created. */
|
||||
public Map<String, List<String>> multipartEncryptionConditions(String bucket, String key, String uploadId) {
|
||||
MultipartUpload upload = getMultipartUpload(bucket, key, uploadId);
|
||||
return S3ObjectActions.encryptionConditions(upload.getServerSideEncryption(), upload.getSseKmsKeyId());
|
||||
}
|
||||
|
||||
/** Checks a part or a completion against the bucket policy by the encryption its upload recorded. */
|
||||
void authorizeMultipartWrite(String bucket, String key, String uploadId, RequestAuthorization authorization) {
|
||||
if (!enforceAuth) {
|
||||
return;
|
||||
}
|
||||
authorizeSignedRequest(authorization);
|
||||
authorizeObjectWrite(bucket, key, null, "s3:PutObject", authorization,
|
||||
multipartEncryptionConditions(bucket, key, uploadId));
|
||||
}
|
||||
|
||||
public MultipartUpload getMultipartUpload(String bucket, String key, String uploadId) {
|
||||
MultipartUpload upload = multipartUploads.get(uploadId);
|
||||
if (upload == null || !upload.getBucket().equals(bucket) || !upload.getKey().equals(key)
|
||||
|
||||
+271
@@ -10,6 +10,7 @@ import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
@@ -842,4 +843,274 @@ class S3BucketPolicyEnforcementIntegrationTest {
|
||||
.statusCode(403)
|
||||
.body(containsString("<Code>AccessDenied</Code>"));
|
||||
}
|
||||
|
||||
private static final String BUCKET_KEY = "arn:aws:kms:us-east-1:111122223333:key/11111111-1111-1111-1111-111111111111";
|
||||
private static final String OTHER_KEY = "arn:aws:kms:us-east-1:111122223333:key/22222222-2222-2222-2222-222222222222";
|
||||
|
||||
/** The refusals and the admission are what S3 answered under these two statements, measured 2026-10-30. */
|
||||
@Test
|
||||
void aPutIsJudgedByItsOwnEncryptionHeadersNotTheBucketsDefault() {
|
||||
EncryptionFixture fixture = kmsOnlyBucket();
|
||||
|
||||
assertEncryptedPut(fixture, "none.txt", null, null, 403);
|
||||
assertEncryptedPut(fixture, "aes.txt", "AES256", null, 403);
|
||||
assertEncryptedPut(fixture, "bucket-key.txt", "aws:kms", BUCKET_KEY, 200);
|
||||
assertEncryptedPut(fixture, "other-key.txt", "aws:kms", OTHER_KEY, 403);
|
||||
assertEncryptedPut(fixture, "no-key.txt", "aws:kms", null, 403);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCopyIsJudgedByItsOwnEncryptionHeaders() {
|
||||
EncryptionFixture fixture = kmsOnlyBucket();
|
||||
assertEncryptedPut(fixture, "source.txt", "aws:kms", BUCKET_KEY, 200);
|
||||
String source = "/" + fixture.bucket() + "/source.txt";
|
||||
|
||||
given().filter(fixture.user().signer()).header("x-amz-copy-source", source)
|
||||
.put("/" + fixture.bucket() + "/plain-copy.txt")
|
||||
.then().statusCode(403).body(containsString("<Code>AccessDenied</Code>"));
|
||||
given().filter(fixture.user().signer()).header("x-amz-copy-source", source)
|
||||
.header(SSE, "aws:kms")
|
||||
.header(SSE_KEY, BUCKET_KEY)
|
||||
.put("/" + fixture.bucket() + "/encrypted-copy.txt")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAllowOnTheEncryptionKeyAdmitsOnlyTheMatchingPut() {
|
||||
EncryptionFixture fixture = allowOnlyBucket("s3:x-amz-server-side-encryption", "aws:kms");
|
||||
|
||||
assertEncryptedPut(fixture, "kms.txt", "aws:kms", null, 200);
|
||||
assertEncryptedPut(fixture, "aes.txt", "AES256", null, 403);
|
||||
assertEncryptedPut(fixture, "none.txt", null, null, 403);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAllowOnTheKmsKeyIdKeyAdmitsOnlyTheMatchingPut() {
|
||||
EncryptionFixture fixture = allowOnlyBucket("s3:x-amz-server-side-encryption-aws-kms-key-id", BUCKET_KEY);
|
||||
|
||||
assertEncryptedPut(fixture, "bucket-key.txt", "aws:kms", BUCKET_KEY, 200);
|
||||
assertEncryptedPut(fixture, "other-key.txt", "aws:kms", OTHER_KEY, 403);
|
||||
assertEncryptedPut(fixture, "no-key.txt", "aws:kms", null, 403);
|
||||
}
|
||||
|
||||
/**
|
||||
* A multipart upload under the same two statements. A part sends neither header, so it is judged
|
||||
* by what its upload recorded. AWS does not document this; it was measured on S3 on 2026-10-30,
|
||||
* each case here as S3 answered it. A case whose upload is opened before the policy stands uses a
|
||||
* bucket with no default encryption: S3 records the bucket's default on an upload that asks for
|
||||
* none, where Floci records only what the request asks for, so on a bucket defaulting to
|
||||
* {@code aws:kms} such a part is admitted on S3 and refused here.
|
||||
*/
|
||||
@Test
|
||||
void anUploadOpenedWithTheBucketsKeyHasItsPartsAdmittedAndStandsUnderThatKey() {
|
||||
EncryptionFixture fixture = kmsOnlyBucket();
|
||||
S3RequestSigner user = fixture.user().signer();
|
||||
|
||||
String uploadId = given().filter(user).header(SSE, "aws:kms").header(SSE_KEY, BUCKET_KEY)
|
||||
.post("/" + fixture.bucket() + "/large.bin?uploads")
|
||||
.then().statusCode(200)
|
||||
.extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId");
|
||||
String etag = uploadPart(user, fixture, "large.bin", uploadId)
|
||||
.then().statusCode(200).extract().header("ETag");
|
||||
given().filter(user).contentType("application/xml")
|
||||
.body("<CompleteMultipartUpload><Part><PartNumber>1</PartNumber><ETag>" + etag
|
||||
+ "</ETag></Part></CompleteMultipartUpload>")
|
||||
.post("/" + fixture.bucket() + "/large.bin?uploadId=" + uploadId)
|
||||
.then().statusCode(200);
|
||||
|
||||
given().filter(user).head("/" + fixture.bucket() + "/large.bin")
|
||||
.then().statusCode(200)
|
||||
.header(SSE, equalTo("aws:kms"))
|
||||
.header(SSE_KEY, equalTo(BUCKET_KEY));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUploadOpenedWithNoEncryptionUnderThePolicyIsRefusedAndNoObjectStands() {
|
||||
EncryptionFixture fixture = kmsOnlyBucket();
|
||||
|
||||
given().filter(fixture.user().signer()).post("/" + fixture.bucket() + "/plain.bin?uploads")
|
||||
.then().statusCode(403).body(containsString("AccessDenied"));
|
||||
|
||||
given().filter(fixture.owner()).head("/" + fixture.bucket() + "/plain.bin").then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPartOfAnUploadThatRecordedNoEncryptionIsRefusedAndNoObjectStands() {
|
||||
EncryptionFixture fixture = bucketWithoutDefaultEncryption();
|
||||
String uploadId = given().filter(fixture.user().signer()).post("/" + fixture.bucket() + "/plain.bin?uploads")
|
||||
.then().statusCode(200)
|
||||
.extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId");
|
||||
putKmsOnlyPolicy(fixture);
|
||||
|
||||
uploadPart(fixture.user().signer(), fixture, "plain.bin", uploadId)
|
||||
.then().statusCode(403).body(containsString("AccessDenied"));
|
||||
|
||||
given().filter(fixture.owner()).head("/" + fixture.bucket() + "/plain.bin").then().statusCode(404);
|
||||
given().filter(fixture.owner()).delete("/" + fixture.bucket() + "/plain.bin?uploadId=" + uploadId)
|
||||
.then().statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPartOfAnUploadThatRecordedAnotherEncryptionIsRefused() {
|
||||
EncryptionFixture fixture = bucketWithoutDefaultEncryption();
|
||||
String uploadId = given().filter(fixture.user().signer()).header(SSE, "AES256")
|
||||
.post("/" + fixture.bucket() + "/aes.bin?uploads")
|
||||
.then().statusCode(200)
|
||||
.extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId");
|
||||
putKmsOnlyPolicy(fixture);
|
||||
|
||||
uploadPart(fixture.user().signer(), fixture, "aes.bin", uploadId)
|
||||
.then().statusCode(403).body(containsString("AccessDenied"));
|
||||
|
||||
given().filter(fixture.owner()).delete("/" + fixture.bucket() + "/aes.bin?uploadId=" + uploadId)
|
||||
.then().statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPartNamingAnUploadNotHeldAnswersNoSuchUpload() {
|
||||
EncryptionFixture fixture = kmsOnlyBucket();
|
||||
|
||||
uploadPart(fixture.user().signer(), fixture, "unknown.bin", "no-such-upload")
|
||||
.then().statusCode(404).body(containsString("NoSuchUpload"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPutNamingAnUploadButNoPartIsAnObjectWriteAndIsChecked() {
|
||||
EncryptionFixture fixture = kmsOnlyBucket();
|
||||
S3RequestSigner unpermitted = encryptionUser("unpermitted-" + suffix(), null).signer();
|
||||
|
||||
given().filter(unpermitted).contentType("text/plain").body("a write")
|
||||
.put("/" + fixture.bucket() + "/written.txt?uploadId=no-such-upload")
|
||||
.then().statusCode(403).body(containsString("AccessDenied"));
|
||||
|
||||
given().filter(fixture.owner()).head("/" + fixture.bucket() + "/written.txt").then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPutNamingAHeldUploadButNoPartIsJudgedByItsOwnHeaders() {
|
||||
EncryptionFixture fixture = kmsOnlyBucket();
|
||||
S3RequestSigner kmsOnly = encryptionUser("kms-only-identity-" + suffix(), """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:*","Resource":"*",
|
||||
"Condition":{"StringEquals":{"s3:x-amz-server-side-encryption":"aws:kms"}}}]}""").signer();
|
||||
String uploadId = given().filter(kmsOnly).header(SSE, "aws:kms").header(SSE_KEY, BUCKET_KEY)
|
||||
.post("/" + fixture.bucket() + "/held.bin?uploads")
|
||||
.then().statusCode(200)
|
||||
.extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId");
|
||||
|
||||
given().filter(kmsOnly).contentType("text/plain").body("a write")
|
||||
.put("/" + fixture.bucket() + "/written.txt?uploadId=" + uploadId)
|
||||
.then().statusCode(403).body(containsString("AccessDenied"));
|
||||
|
||||
given().filter(fixture.owner()).delete("/" + fixture.bucket() + "/held.bin?uploadId=" + uploadId)
|
||||
.then().statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPartCopyNamingAnUploadNotHeldIsChecked() {
|
||||
EncryptionFixture fixture = kmsOnlyBucket();
|
||||
S3RequestSigner unpermitted = encryptionUser("unpermitted-" + suffix(), null).signer();
|
||||
|
||||
given().filter(unpermitted).header("x-amz-copy-source", "/" + fixture.bucket() + "/source.txt")
|
||||
.put("/" + fixture.bucket() + "/copied.bin?partNumber=1&uploadId=no-such-upload")
|
||||
.then().statusCode(403).body(containsString("AccessDenied"));
|
||||
}
|
||||
|
||||
private record EncryptionFixture(String bucket, S3RequestSigner owner, Credentials user) {
|
||||
}
|
||||
|
||||
private static final String SSE = "x-amz-server-side-encryption";
|
||||
private static final String SSE_KEY = "x-amz-server-side-encryption-aws-kms-key-id";
|
||||
private static final String ALLOW_S3_AND_KMS = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:*","kms:*"],"Resource":"*"}]}""";
|
||||
|
||||
private static void assertEncryptedPut(EncryptionFixture fixture, String key, String encryption, String kmsKeyId,
|
||||
int status) {
|
||||
RequestSpecification request = given().filter(fixture.user().signer()).contentType("text/plain").body(key);
|
||||
if (encryption != null) {
|
||||
request.header(SSE, encryption);
|
||||
}
|
||||
if (kmsKeyId != null) {
|
||||
request.header(SSE_KEY, kmsKeyId);
|
||||
}
|
||||
request.put("/" + fixture.bucket() + "/" + key).then().statusCode(status);
|
||||
}
|
||||
|
||||
private static Response uploadPart(S3RequestSigner signer, EncryptionFixture fixture, String key, String uploadId) {
|
||||
return given().filter(signer).contentType("application/octet-stream").body("a part".getBytes())
|
||||
.put("/" + fixture.bucket() + "/" + key + "?partNumber=1&uploadId=" + uploadId);
|
||||
}
|
||||
|
||||
/** A bucket defaulting to {@code aws:kms} that denies any other put, and a user allowed {@code s3:*} and {@code kms:*}. */
|
||||
private EncryptionFixture kmsOnlyBucket() {
|
||||
String suffix = suffix();
|
||||
EncryptionFixture fixture = encryptionBucket("kms-only-" + suffix,
|
||||
encryptionUser("kms-only-user-" + suffix, ALLOW_S3_AND_KMS), suffix, true);
|
||||
putKmsOnlyPolicy(fixture);
|
||||
return fixture;
|
||||
}
|
||||
|
||||
/** A bucket with no default encryption and no policy yet, and a user allowed {@code s3:*} and {@code kms:*}. */
|
||||
private EncryptionFixture bucketWithoutDefaultEncryption() {
|
||||
String suffix = suffix();
|
||||
return encryptionBucket("multipart-" + suffix,
|
||||
encryptionUser("multipart-user-" + suffix, ALLOW_S3_AND_KMS), suffix, false);
|
||||
}
|
||||
|
||||
/** Denies a put that does not name {@code aws:kms}, or names a key other than the bucket's. */
|
||||
private static void putKmsOnlyPolicy(EncryptionFixture fixture) {
|
||||
putBucketPolicyAs(fixture.bucket(), """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Sid":"DenyUnencryptedPuts","Effect":"Deny","Principal":"*","Action":"s3:PutObject",
|
||||
"Resource":"arn:aws:s3:::%1$s/*",
|
||||
"Condition":{"StringNotEquals":{"s3:x-amz-server-side-encryption":"aws:kms"}}},
|
||||
{"Sid":"DenyWrongKmsKey","Effect":"Deny","Principal":"*","Action":"s3:PutObject",
|
||||
"Resource":"arn:aws:s3:::%1$s/*",
|
||||
"Condition":{"StringNotEqualsIfExists":{"s3:x-amz-server-side-encryption-aws-kms-key-id":"%2$s"}}}]}
|
||||
""".formatted(fixture.bucket(), BUCKET_KEY), fixture.owner());
|
||||
}
|
||||
|
||||
/** A bucket whose policy alone allows a user with no identity policy, on {@code key} being {@code value}. */
|
||||
private EncryptionFixture allowOnlyBucket(String key, String value) {
|
||||
String suffix = suffix();
|
||||
EncryptionFixture fixture = encryptionBucket("allow-only-" + suffix,
|
||||
encryptionUser("allow-only-user-" + suffix, null), suffix, true);
|
||||
putBucketPolicyAs(fixture.bucket(), """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Principal":{"AWS":"%s"},"Action":"s3:PutObject",
|
||||
"Resource":"arn:aws:s3:::%s/*",
|
||||
"Condition":{"StringEquals":{"%s":"%s"}}}]}
|
||||
""".formatted(fixture.user().userArn(), fixture.bucket(), key, value), fixture.owner());
|
||||
return fixture;
|
||||
}
|
||||
|
||||
private static String suffix() {
|
||||
return UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
private Credentials encryptionUser(String userName, String policy) {
|
||||
cleanup.register(() -> EnforcementFixtures.removeUser(endpoint.getPort(), auth(ACCOUNT_A, "iam"), userName));
|
||||
Credentials user = createUser(userName, ACCOUNT_A);
|
||||
if (policy != null) {
|
||||
putUserPolicy(userName, "AllowEncryptedPuts", policy, ACCOUNT_A);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
private EncryptionFixture encryptionBucket(String bucket, Credentials user, String suffix, boolean kmsDefault) {
|
||||
String ownerName = "encryption-owner-" + suffix;
|
||||
cleanup.register(() -> EnforcementFixtures.removeUser(endpoint.getPort(), auth(ACCOUNT_A, "iam"), ownerName));
|
||||
Credentials owner = createAccountAdmin(ownerName, ACCOUNT_A);
|
||||
cleanup.register(() -> EnforcementFixtures.removeBucket(endpoint.getPort(), owner.signer(), bucket));
|
||||
createBucketAs(bucket, owner.signer());
|
||||
if (kmsDefault) {
|
||||
given().filter(owner.signer()).contentType("application/xml").body("""
|
||||
<ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Rule>
|
||||
<ApplyServerSideEncryptionByDefault><SSEAlgorithm>aws:kms</SSEAlgorithm>
|
||||
<KMSMasterKeyID>%s</KMSMasterKeyID></ApplyServerSideEncryptionByDefault>
|
||||
</Rule></ServerSideEncryptionConfiguration>""".formatted(BUCKET_KEY))
|
||||
.put("/" + bucket + "?encryption").then().statusCode(200);
|
||||
}
|
||||
return new EncryptionFixture(bucket, owner.signer(), user);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user