diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java index 6017358fd7..5eee8a0eef 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService; import io.github.hectorvent.floci.services.iam.IamActionRegistry; import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator; import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision; +import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision; import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.iam.ResourceArnBuilder; import io.github.hectorvent.floci.services.iam.ScpProvider; @@ -44,7 +45,7 @@ import java.util.regex.Pattern; * *

Evaluates the caller's identity policies, optional session policy, and optional * permissions boundary. Resource-based policies (S3 bucket policy, Lambda resource - * policy, etc.) are not yet supplied to this filter. + * policy, etc.) are not yet supplied to the primary request-filter path. * *

Reads the signing credential from either the {@code Authorization} header or, for a * presigned URL, the {@code X-Amz-Credential} query parameter - both request shapes get the @@ -252,6 +253,20 @@ public class IamEnforcementFilter implements ContainerRequestFilter { * ambient account, resolve the credential's actual owner instead of the default account. */ public void authorizeAdditionalResource(String authorizationHeader, String action, String resource) { + authorizeAdditionalResource( + authorizationHeader, action, resource, ResourcePolicyDecision.NEUTRAL); + } + + /** + * Authorizes a secondary resource using an already principal-filtered resource-policy + * decision. This preserves explicit-deny precedence while allowing either the identity or + * resource policy to provide the base grant. + */ + public void authorizeAdditionalResource( + String authorizationHeader, + String action, + String resource, + ResourcePolicyDecision resourcePolicyDecision) { if (!config.services().iam().enforcementEnabled()) { return; } @@ -295,7 +310,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { conditionContext.put("aws:PrincipalArn", List.of(principalArn.get())); } - Decision decision = evaluator.evaluate(caller, null, action, resource, conditionContext); + Decision decision = evaluator.evaluateResolvedResourcePolicy( + caller, resourcePolicyDecision, action, resource, conditionContext); if (decision != Decision.DENY) { return; } diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java index a62d894586..1484b01858 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java @@ -40,6 +40,12 @@ public class IamPolicyEvaluator { public enum Decision { ALLOW, DENY } + public enum ResourcePolicyDecision { + ALLOW, + EXPLICIT_DENY, + NEUTRAL + } + public enum SimulationDecision { ALLOWED("allowed"), EXPLICIT_DENY("explicitDeny"), @@ -89,6 +95,49 @@ public class IamPolicyEvaluator { List boundaryStmts = caller.boundaryPolicyDocument() == null ? null : parseAll(List.of(caller.boundaryPolicyDocument())); + boolean resourceExplicitDeny = anyExplicitDeny(resourceStmts, action, resource, ctx); + boolean resourceAllow = anyExplicitAllow(resourceStmts, action, resource, ctx); + return evaluateParsed( + caller, identityStmts, sessionStmts, boundaryStmts, + resourceExplicitDeny, resourceAllow, action, resource, ctx); + } + + /** + * Evaluates an already principal-filtered resource-policy decision together with the + * caller's identity policies and permission ceilings. + */ + public Decision evaluateResolvedResourcePolicy( + CallerContext caller, + ResourcePolicyDecision resourcePolicyDecision, + String action, + String resource, + Map> conditionCtx) { + Map> ctx = normalizeConditionContext(conditionCtx); + List identityStmts = parseAll(caller.identityPolicies()); + List sessionStmts = caller.sessionPolicyDocument() == null + ? null : parseAll(List.of(caller.sessionPolicyDocument())); + List boundaryStmts = caller.boundaryPolicyDocument() == null + ? null : parseAll(List.of(caller.boundaryPolicyDocument())); + ResourcePolicyDecision resolvedDecision = resourcePolicyDecision == null + ? ResourcePolicyDecision.NEUTRAL : resourcePolicyDecision; + return evaluateParsed( + caller, identityStmts, sessionStmts, boundaryStmts, + resolvedDecision == ResourcePolicyDecision.EXPLICIT_DENY, + resolvedDecision == ResourcePolicyDecision.ALLOW, + action, resource, ctx); + } + + private Decision evaluateParsed( + CallerContext caller, + List identityStmts, + List sessionStmts, + List boundaryStmts, + boolean resourceExplicitDeny, + boolean resourceAllow, + String action, + String resource, + Map> ctx) { + // 0. Service control policies gate everything: the action must be allowed at EVERY // organization level and explicitly denied at none, before identity policies are // even consulted. An empty level means FullAWSAccess semantics and is skipped; @@ -99,7 +148,7 @@ public class IamPolicyEvaluator { // 1. Explicit deny in ANY policy → DENY immediately if (anyExplicitDeny(identityStmts, action, resource, ctx) - || anyExplicitDeny(resourceStmts, action, resource, ctx) + || resourceExplicitDeny || (sessionStmts != null && anyExplicitDeny(sessionStmts, action, resource, ctx)) || (boundaryStmts != null && anyExplicitDeny(boundaryStmts, action, resource, ctx))) { return Decision.DENY; @@ -107,7 +156,6 @@ public class IamPolicyEvaluator { // 2. Base grant: identity OR resource-based policy must allow boolean identityAllow = anyExplicitAllow(identityStmts, action, resource, ctx); - boolean resourceAllow = anyExplicitAllow(resourceStmts, action, resource, ctx); if (!identityAllow && !resourceAllow) { return Decision.DENY; } diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java index 89385d4fc9..f3d6331d35 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java @@ -2185,6 +2185,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return Optional.empty(); } String roleArn = session.getRoleArn(); + if (roleArn == null) { + return Optional.empty(); + } String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole"; String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId()); return Optional.of(AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/floci-session").toString()); diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java index 52b0e1c566..1c5ecf631b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java @@ -12,6 +12,7 @@ import io.github.hectorvent.floci.core.common.XmlParser; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService; +import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision; import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.sns.SnsQueryHandler; import io.github.hectorvent.floci.services.s3.model.Bucket; @@ -785,7 +786,8 @@ public class S3Controller { if (uploadId != null && partNumber != null) { s3Service.authorizeObjectWrite(bucket, key, "s3:PutObject", authorization); if (copySource != null && !copySource.isEmpty()) { - return handleUploadPartCopy(copySource, bucket, key, uploadId, partNumber, httpHeaders); + return handleUploadPartCopy( + copySource, bucket, key, uploadId, partNumber, httpHeaders, authorization); } byte[] partData = decodeAwsChunked(body, contentEncoding, contentSha256); validateChecksumHeaders(httpHeaders, partData, getChecksumAlgorithm(httpHeaders)); @@ -807,7 +809,7 @@ public class S3Controller { if (copySource != null && !copySource.isEmpty()) { s3Service.authorizeObjectWrite(bucket, key, "s3:PutObject", authorization); - return handleCopyObject(copySource, bucket, key, contentType, httpHeaders); + return handleCopyObject(copySource, bucket, key, contentType, httpHeaders, authorization); } Map inlineTags = parseInlineTaggingHeader(tagging); @@ -2588,10 +2590,11 @@ public class S3Controller { // --- Helpers --- private Response handleCopyObject(String copySource, String destBucket, String destKey, - String contentType, HttpHeaders httpHeaders) { + String contentType, HttpHeaders httpHeaders, + S3Service.RequestAuthorization authorization) { CopySourceRef sourceObject = parseCopySource(copySource); String sourceBucket = sourceObject.bucket(); - authorizeCopySourceRead(httpHeaders, sourceBucket, sourceObject.objectKey()); + authorizeCopySourceRead(httpHeaders, sourceObject, authorization); String copyContentEncoding = toPersistedContentEncoding(httpHeaders.getHeaderString("Content-Encoding")); String copyContentDisposition = httpHeaders.getHeaderString("Content-Disposition"); String copyCacheControl = httpHeaders.getHeaderString("Cache-Control"); @@ -2668,10 +2671,11 @@ public class S3Controller { } private Response handleUploadPartCopy(String copySource, String destBucket, String destKey, - String uploadId, int partNumber, HttpHeaders httpHeaders) { + String uploadId, int partNumber, HttpHeaders httpHeaders, + S3Service.RequestAuthorization authorization) { CopySourceRef sourceObject = parseCopySource(copySource); String sourceBucket = sourceObject.bucket(); - authorizeCopySourceRead(httpHeaders, sourceBucket, sourceObject.objectKey()); + authorizeCopySourceRead(httpHeaders, sourceObject, authorization); String copySourceRange = httpHeaders.getHeaderString("x-amz-copy-source-range"); String eTag = s3Service.uploadPartCopy(destBucket, destKey, uploadId, partNumber, sourceBucket, sourceObject.objectKey(), sourceObject.versionId(), copySourceRange, @@ -3776,10 +3780,18 @@ public class S3Controller { * allowed to write to the destination bucket must not be able to exfiltrate an object it cannot read. * A no-op when IAM enforcement is disabled, matching {@link IamEnforcementFilter}'s own bypass rules. */ - private void authorizeCopySourceRead(HttpHeaders httpHeaders, String sourceBucket, String sourceKey) { - String resource = S3PublicAccessEvaluator.objectArn(sourceBucket, sourceKey); + private void authorizeCopySourceRead(HttpHeaders httpHeaders, CopySourceRef source, + S3Service.RequestAuthorization authorization) { + String action = source.versionId() == null ? "s3:GetObject" : "s3:GetObjectVersion"; + String resource = S3PublicAccessEvaluator.objectArn(source.bucket(), source.objectKey()); + ResourcePolicyDecision resourcePolicyDecision = + s3Service.signedPrincipalResourcePolicyDecision( + source.bucket(), action, resource, authorization); iamEnforcementFilter.authorizeAdditionalResource( - httpHeaders.getHeaderString("Authorization"), "s3:GetObject", resource); + httpHeaders.getHeaderString("Authorization"), action, resource, + resourcePolicyDecision); + s3Service.authorizeGetObject( + source.bucket(), source.objectKey(), source.versionId(), authorization); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java index f565168ace..e18664457d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java @@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.Resettable; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision; import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambda.model.InvocationType; @@ -898,11 +899,13 @@ public class S3Service implements Resettable, ResourceProvider { : RequestAuthorization.unsigned(); if (requestAuthorization.signed()) { - if (isKnownAccessKey(requestAuthorization)) { - return; + if (!isKnownAccessKey(requestAuthorization)) { + throw new AwsException("InvalidAccessKeyId", + "The AWS Access Key Id you provided does not exist in our records.", 403); } - throw new AwsException("InvalidAccessKeyId", - "The AWS Access Key Id you provided does not exist in our records.", 403); + authorizeSignedPrincipalPolicyDeny( + bucketName, action, resourceArn, requestAuthorization); + return; } Bucket bucket = bucketStore.get(bucketName) @@ -926,6 +929,52 @@ public class S3Service implements Resettable, ResourceProvider { throw new AwsException("AccessDenied", "Access Denied", 403); } + private void authorizeSignedPrincipalPolicyDeny( + String bucketName, + String action, + String resourceArn, + RequestAuthorization authorization) { + if (signedPrincipalResourcePolicyDecision( + bucketName, action, resourceArn, authorization) + == ResourcePolicyDecision.EXPLICIT_DENY) { + throw new AwsException("AccessDenied", "Access Denied", 403); + } + } + + ResourcePolicyDecision signedPrincipalResourcePolicyDecision( + String bucketName, + String action, + String resourceArn, + RequestAuthorization authorization) { + if (authorization == null || !authorization.signed() + || LEGACY_ACCESS_KEY_ID.equals(authorization.accessKeyId()) || iamService == null) { + return ResourcePolicyDecision.NEUTRAL; + } + + Optional principalArn = iamService.resolveCallerArn(authorization.accessKeyId()); + if (principalArn.isEmpty()) { + return ResourcePolicyDecision.NEUTRAL; + } + + Bucket bucket = bucketStore.get(bucketName) + .orElseThrow(() -> new AwsException( + "NoSuchBucket", "The specified bucket does not exist.", 404)); + S3PublicAccessEvaluator.PublicAccessDecision policyDecision = + S3PublicAccessEvaluator.principalPolicyDecision( + objectMapper, + bucket.getPolicy(), + "AWS", + principalArn.get(), + action, + resourceArn, + Map.of("aws:PrincipalArn", principalArn.get())); + return switch (policyDecision) { + case ALLOW -> ResourcePolicyDecision.ALLOW; + case DENY -> ResourcePolicyDecision.EXPLICIT_DENY; + case NEUTRAL -> ResourcePolicyDecision.NEUTRAL; + }; + } + private boolean readableObjectExists(String bucketName, String key) { ensureBucketExists(bucketName); return resolveObject(objectKey(bucketName, key)) diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java index 63e5ee0ece..736b7f4313 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.iam; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision; +import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision; import io.github.hectorvent.floci.services.iam.model.CallerContext; import org.junit.jupiter.api.Test; @@ -43,6 +44,45 @@ class IamPolicyEvaluatorTest { evaluator.evaluate(caller, null, "s3:GetObject", "*", null)); } + @Test + void resolvedResourceAllowCompletesIdentityImplicitDeny() { + CallerContext caller = CallerContext.of(List.of()); + + assertEquals(Decision.ALLOW, evaluator.evaluateResolvedResourcePolicy( + caller, + ResourcePolicyDecision.ALLOW, + "s3:GetObject", + "arn:aws:s3:::bucket/key", + null)); + } + + @Test + void identityExplicitDenyOverridesResolvedResourceAllow() { + CallerContext caller = CallerContext.of(List.of(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Deny","Action":"s3:GetObject","Resource":"*"} + ]}""")); + + assertEquals(Decision.DENY, evaluator.evaluateResolvedResourcePolicy( + caller, + ResourcePolicyDecision.ALLOW, + "s3:GetObject", + "arn:aws:s3:::bucket/key", + null)); + } + + @Test + void resolvedResourceExplicitDenyOverridesIdentityAllow() { + CallerContext caller = CallerContext.of(List.of(ALLOW_ALL)); + + assertEquals(Decision.DENY, evaluator.evaluateResolvedResourcePolicy( + caller, + ResourcePolicyDecision.EXPLICIT_DENY, + "s3:GetObject", + "arn:aws:s3:::bucket/key", + null)); + } + @Test void scpDenyWinsOverIdentityAllow() { CallerContext caller = adminWithScps(List.of(List.of(DENY_S3))); @@ -282,4 +322,3 @@ class IamPolicyEvaluatorTest { Map.of("dynamodb:LeadingKeys", List.of("USER_alice")))); } } - diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3CopyObjectSourcePermissionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3CopyObjectSourcePermissionIntegrationTest.java index 0d6d879d0d..7910578487 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3CopyObjectSourcePermissionIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3CopyObjectSourcePermissionIntegrationTest.java @@ -78,6 +78,64 @@ class S3CopyObjectSourcePermissionIntegrationTest { .statusCode(200); } + @Test + void copyObjectSucceedsWhenSourceBucketPolicyAllowsCaller() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String sourceBucket = "copy-resource-allow-source-" + suffix; + String destBucket = "copy-resource-allow-dest-" + suffix; + String userName = "copy-resource-allow-user-" + suffix; + + createBucketAsRoot(sourceBucket); + createBucketAsRoot(destBucket); + putObjectAsRoot(sourceBucket, "allowed.txt", "resource policy grant"); + + String accessKeyId = createUser(userName); + putUserPolicy(userName, "DestWriteOnly", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/*"} + ]}""".formatted(destBucket)); + putBucketPolicyAsRoot( + sourceBucket, allowUserReadPolicy(sourceBucket, userName, "s3:GetObject")); + + given() + .header("Authorization", auth(accessKeyId, "s3")) + .header("x-amz-copy-source", "/" + sourceBucket + "/allowed.txt") + .when() + .put("/" + destBucket + "/copied.txt") + .then() + .statusCode(200); + } + + @Test + void versionedCopyUsesGetObjectVersionPermission() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String sourceBucket = "copy-version-source-" + suffix; + String destBucket = "copy-version-dest-" + suffix; + String userName = "copy-version-user-" + suffix; + + createBucketAsRoot(sourceBucket); + createBucketAsRoot(destBucket); + enableVersioningAsRoot(sourceBucket); + String versionId = putVersionedObjectAsRoot(sourceBucket, "versioned.txt", "versioned source"); + + String accessKeyId = createUser(userName); + putUserPolicy(userName, "DestWriteOnly", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/*"} + ]}""".formatted(destBucket)); + putBucketPolicyAsRoot( + sourceBucket, allowUserReadPolicy(sourceBucket, userName, "s3:GetObjectVersion")); + + given() + .header("Authorization", auth(accessKeyId, "s3")) + .header("x-amz-copy-source", + "/" + sourceBucket + "/versioned.txt?versionId=" + versionId) + .when() + .put("/" + destBucket + "/copied.txt") + .then() + .statusCode(200); + } + @Test void uploadPartCopyIsDeniedWhenCallerCannotReadTheSource() { String suffix = UUID.randomUUID().toString().substring(0, 8); @@ -109,6 +167,114 @@ class S3CopyObjectSourcePermissionIntegrationTest { .body(containsString("AccessDenied")); } + @Test + void copyObjectIsDeniedBySourceBucketPolicy() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String sourceBucket = "copy-policy-source-" + suffix; + String destBucket = "copy-policy-dest-" + suffix; + String userName = "copy-policy-user-" + suffix; + + createBucketAsRoot(sourceBucket); + createBucketAsRoot(destBucket); + putObjectAsRoot(sourceBucket, "denied.txt", "bucket policy protected"); + putBucketPolicyAsRoot(sourceBucket, denyGetObjectPolicy(sourceBucket)); + + String accessKeyId = createUser(userName); + putUserPolicy(userName, "SourceReadDestWrite", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::%1$s/*"}, + {"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::%2$s/*"} + ]}""".formatted(sourceBucket, destBucket)); + + given() + .header("Authorization", auth(accessKeyId, "s3")) + .when() + .get("/" + sourceBucket + "/denied.txt") + .then() + .statusCode(403) + .body(containsString("AccessDenied")); + + given() + .header("Authorization", auth(accessKeyId, "s3")) + .header("x-amz-copy-source", "/" + sourceBucket + "/denied.txt") + .when() + .put("/" + destBucket + "/copied.txt") + .then() + .statusCode(403) + .body(containsString("AccessDenied")); + } + + @Test + void anonymousCopyObjectSucceedsWhenSourceAclAllowsRead() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String sourceBucket = "copy-public-source-" + suffix; + String destBucket = "copy-public-dest-" + suffix; + + createBucketAsRoot(sourceBucket); + createBucketAsRoot(destBucket); + putPublicObjectAsRoot(sourceBucket, "public.txt", "public source"); + putBucketPolicyAsRoot(destBucket, allowPublicPutObjectPolicy(destBucket)); + + given() + .header("x-amz-copy-source", "/" + sourceBucket + "/public.txt") + .when() + .put("/" + destBucket + "/copied.txt") + .then() + .statusCode(200); + } + + @Test + void uploadPartCopyIsDeniedBySourceBucketPolicy() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String sourceBucket = "part-policy-source-" + suffix; + String destBucket = "part-policy-dest-" + suffix; + String userName = "part-policy-user-" + suffix; + + createBucketAsRoot(sourceBucket); + createBucketAsRoot(destBucket); + putObjectAsRoot(sourceBucket, "denied.txt", "bucket policy protected"); + putBucketPolicyAsRoot(sourceBucket, denyGetObjectPolicy(sourceBucket)); + + String accessKeyId = createUser(userName); + putUserPolicy(userName, "SourceReadDestWrite", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::%1$s/*"}, + {"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::%2$s/*"} + ]}""".formatted(sourceBucket, destBucket)); + String uploadId = initiateMultipartUploadAsRoot(destBucket, "copied.txt"); + + given() + .header("Authorization", auth(accessKeyId, "s3")) + .header("x-amz-copy-source", "/" + sourceBucket + "/denied.txt") + .queryParam("uploadId", uploadId) + .queryParam("partNumber", 1) + .when() + .put("/" + destBucket + "/copied.txt") + .then() + .statusCode(403) + .body(containsString("AccessDenied")); + } + + @Test + void anonymousCopyObjectIsDeniedWhenSourceIsPrivate() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String sourceBucket = "copy-private-source-" + suffix; + String destBucket = "copy-public-dest-" + suffix; + + createBucketAsRoot(sourceBucket); + createBucketAsRoot(destBucket); + putObjectAsRoot(sourceBucket, "private.txt", "private source"); + putBucketPolicyAsRoot(destBucket, allowPublicPutObjectPolicy(destBucket)); + + given() + .header("x-amz-copy-source", "/" + sourceBucket + "/private.txt") + .when() + .put("/" + destBucket + "/copied.txt") + .then() + .statusCode(403) + .body(containsString("AccessDenied")); + } + private static void createBucketAsRoot(String bucket) { given() .header("Authorization", auth("test", "s3")) @@ -129,6 +295,75 @@ class S3CopyObjectSourcePermissionIntegrationTest { .statusCode(200); } + private static void putPublicObjectAsRoot(String bucket, String key, String body) { + given() + .header("Authorization", auth("test", "s3")) + .header("x-amz-acl", "public-read") + .contentType("text/plain") + .body(body) + .when() + .put("/" + bucket + "/" + key) + .then() + .statusCode(200); + } + + private static void enableVersioningAsRoot(String bucket) { + given() + .header("Authorization", auth("test", "s3")) + .contentType("application/xml") + .body("Enabled") + .when() + .put("/" + bucket + "?versioning") + .then() + .statusCode(200); + } + + private static String putVersionedObjectAsRoot(String bucket, String key, String body) { + return given() + .header("Authorization", auth("test", "s3")) + .contentType("text/plain") + .body(body) + .when() + .put("/" + bucket + "/" + key) + .then() + .statusCode(200) + .extract() + .header("x-amz-version-id"); + } + + private static void putBucketPolicyAsRoot(String bucket, String policy) { + given() + .header("Authorization", auth("test", "s3")) + .contentType("application/json") + .body(policy) + .when() + .put("/" + bucket + "?policy") + .then() + .statusCode(200); + } + + private static String denyGetObjectPolicy(String bucket) { + return """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Deny","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::%s/*"} + ]}""".formatted(bucket); + } + + private static String allowUserReadPolicy(String bucket, String userName, String action) { + return """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::000000000000:user/%1$s"}, + "Action":"%2$s","Resource":"arn:aws:s3:::%3$s/*"} + ]}""".formatted(userName, action, bucket); + } + + private static String allowPublicPutObjectPolicy(String bucket) { + return """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Principal":"*","Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/*"} + ]}""".formatted(bucket); + } + private static String initiateMultipartUploadAsRoot(String bucket, String key) { return given() .header("Authorization", auth("test", "s3")) @@ -186,7 +421,9 @@ class S3CopyObjectSourcePermissionIntegrationTest { public static final class IamEnforcementProfile implements QuarkusTestProfile { @Override public Map getConfigOverrides() { - return Map.of("floci.services.iam.enforcement-enabled", "true"); + return Map.of( + "floci.services.iam.enforcement-enabled", "true", + "floci.services.s3.enforce-auth", "true"); } } }