diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index 9034351e56..4bfe29d733 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -17,6 +17,7 @@ import io.floci.aws.services.iam.IamService; import io.floci.aws.services.iam.IamService.CallerArns; import io.floci.aws.services.iam.IamService.PresignedScope; import io.floci.aws.services.iam.PassedRoleLookup; +import io.floci.aws.services.iam.PrincipalOrganization; import io.floci.aws.services.iam.RequestPrincipal; import io.floci.aws.services.iam.ResourceArnBuilder; import io.floci.aws.services.iam.ResourcePolicyProvider; @@ -1007,7 +1008,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { } LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, connector); String user = callerArns != null ? callerArns.callerArn() - : AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "user/" + akid).toString(); + : keyUserArn(accountId, akid); String reason = AccessDeniedMessages.firstRefusal(evaluator, caller, iamService.heldPolicies(akid).orElse(null), action, connector, effectiveContext); ctx.abortWith(Response.status(403).type(MediaType.APPLICATION_JSON) @@ -1274,13 +1275,20 @@ public class IamEnforcementFilter implements ContainerRequestFilter { continue; } LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource); - String denyMessage = "User: " + AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "user/" + akid) - + " is not authorized to perform: " + action - + " on resource: \"" + resource + "\"" - + " " + PolicyType.IDENTITY_BASED_POLICY.noAllow(action); - emitS3DenialIfApplicable(akid, operationAction, resource, ctx, region, denyMessage); - abortIamAware(ctx, accessDeniedForRequest(action, credentialScope, ctx, resource), akid, action, - credentialScope, region); + // S3 answers the refusal with the caller, the resource and the policy that refused it, and + // CloudTrail records the message S3 answered; S3 Control keeps its own envelope and wording. + boolean s3Request = "s3".equals(credentialScope) + && !IamActionRegistry.isS3ControlRequest(credentialScope, ctx); + String s3Message = s3Request + ? refusalMessage(caller, caller.principalArn(), akid, accountId, resourceOwnerAccountId, action, + resource, resourcePolicyDecision, effectiveContext) + : null; + emitS3DenialIfApplicable(akid, operationAction, resource, ctx, region, + s3Message != null ? s3Message : accessDeniedMessage(action)); + abortIamAware(ctx, s3Message != null + ? s3XmlAccessDenied(s3Message, formatS3ResourcePath(resource)) + : accessDeniedForRequest(action, credentialScope, ctx, resource), + akid, action, credentialScope, region); return true; } } @@ -1511,16 +1519,17 @@ public class IamEnforcementFilter implements ContainerRequestFilter { String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion(); - Decision decision = decideAs(caller, accountId, region, action, resource, conditionContext, - resourcePolicyDecision, resourceOwnerAccountId).decision(); - if (decision != Decision.DENY) { + Decided decided = decideAs(caller, accountId, region, action, resource, conditionContext, + resourcePolicyDecision, resourceOwnerAccountId); + if (decided.decision() != Decision.DENY) { return; } LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource); - String denyMessage = "User: " + AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "user/" + akid) - + " is not authorized to perform: " + action - + " on resource: \"" + resource + "\"" - + " " + PolicyType.IDENTITY_BASED_POLICY.noAllow(action); + // The owner and the resource policy decision as the decision resolved them: a presigned POST names + // neither, and a caller outside the owner's organization is told Access Denied alone. + String denyMessage = refusalMessage(caller.context(), caller.arns().map(CallerArns::callerArn).orElse(null), + akid, accountId, decided.resourceOwnerAccountId(), action, resource, + decided.resourcePolicyDecision(), decided.context()); if (deniedEvent != null) { emitS3Denial(akid, deniedEvent.name(), resource, deniedEvent.region(), denyMessage); } @@ -1567,7 +1576,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}, which its service makes as the caller", akid, request.action(), request.resource()); String user = caller.arns().map(CallerArns::callerArn).orElseGet(() -> - AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "user/" + akid).toString()); + keyUserArn(accountId, akid)); String reason = AccessDeniedMessages.firstRefusal(evaluator, caller.context(), iamService.heldPolicies(akid).orElse(null), request.action(), request.resource(), decided.context()); @@ -1581,7 +1590,50 @@ public class IamEnforcementFilter implements ContainerRequestFilter { } /** A decision and the condition context it was made in. */ - private record Decided(Decision decision, Map> context) { + /** + * A decision, the context it was made in, and the resource's owner and resource policy decision as the decision + * resolved them, which a refusal names. + */ + private record Decided(Decision decision, Map> context, String resourceOwnerAccountId, + ResourcePolicyDecision resourcePolicyDecision) { + } + + /** + * The access denied message for {@code action} on {@code resource}: the caller, the action, the resource and + * the policy that refused it, as S3's guide gives them for a caller in the resource's account or organization + * ("This context includes the type of policy that denied access, the reason for denial, and information about + * the IAM user or role that requested access to the resource", S3 User Guide, "Troubleshoot access denied (403 + * Forbidden) errors"). Across organizations S3 answers {@code Access Denied} alone: "Cross-account requests + * outside of the same organization return a generic Access Denied message". A bucket policy's explicit deny is + * named as a resource-based policy's; otherwise the caller's own policies name the refusal, and a refusal none + * of them makes is the resource-based policy's missing allow. + */ + private String refusalMessage(CallerContext caller, String callerArn, String akid, String accountId, + String resourceOwnerAccountId, String action, String resource, + ResourcePolicyDecision resourcePolicyDecision, Map> context) { + if (action.startsWith("s3:") && resourceOwnerAccountId != null && !resourceOwnerAccountId.equals(accountId) + && !sameOrganization(accountId, resourceOwnerAccountId)) { + return "Access Denied"; + } + String reason = resourcePolicyDecision == ResourcePolicyDecision.EXPLICIT_DENY + ? PolicyType.RESOURCE_BASED_POLICY.explicitDeny() + : AccessDeniedMessages.firstRefusal(evaluator, caller, iamService.heldPolicies(akid).orElse(null), + action, resource, context); + return AccessDeniedMessages.notAuthorized(callerArn != null ? callerArn : keyUserArn(accountId, akid), action, + "\"" + resource + "\"", reason != null ? reason : PolicyType.RESOURCE_BASED_POLICY.noAllow(action)); + } + + /** Whether both accounts belong to one organization. */ + private boolean sameOrganization(String accountId, String otherAccountId) { + Optional organization = iamService.organizationContextOf(accountId) + .map(PrincipalOrganization.OrganizationContext::organizationId); + return organization.isPresent() && organization.equals(iamService.organizationContextOf(otherAccountId) + .map(PrincipalOrganization.OrganizationContext::organizationId)); + } + + /** The user ARN a message names a caller by when IAM resolves no ARN for its key: the key in the user's place. */ + private String keyUserArn(String accountId, String akid) { + return AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "user/" + akid).toString(); } /** @@ -1655,7 +1707,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { Decision decision = evaluator.evaluateResolvedResourcePolicy( caller.context(), effectiveDecision, accountRelationship, action, resource, effectiveContext); - return new Decided(decision, effectiveContext); + return new Decided(decision, effectiveContext, effectiveOwnerAccountId, effectiveDecision); } /** diff --git a/src/test/java/io/floci/aws/services/s3/S3BucketPolicyEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/s3/S3BucketPolicyEnforcementIntegrationTest.java index 4fe11019ac..72c96ed41e 100644 --- a/src/test/java/io/floci/aws/services/s3/S3BucketPolicyEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/s3/S3BucketPolicyEnforcementIntegrationTest.java @@ -1,8 +1,12 @@ package io.floci.aws.services.s3; +import com.fasterxml.jackson.databind.JsonNode; import io.floci.aws.core.common.AwsCanonicalUserId; +import io.floci.aws.services.cloudtrail.CloudTrailLogWriter; +import io.floci.aws.testing.CloudTrailLogFiles; import io.floci.aws.testing.EnforcementFixtures; import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; import io.floci.aws.testing.S3IamEnforcementProfile; import io.floci.aws.testutil.S3RequestSigner; import io.quarkus.test.common.http.TestHTTPResource; @@ -11,15 +15,20 @@ import io.quarkus.test.junit.TestProfile; import io.restassured.response.ExtractableResponse; import io.restassured.response.Response; 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.api.extension.RegisterExtension; +import java.io.IOException; import java.net.URI; import java.util.UUID; +import static io.floci.aws.testing.CloudTrailRequests.invokeCloudTrail; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @QuarkusTest @@ -34,6 +43,14 @@ class S3BucketPolicyEnforcementIntegrationTest { @TestHTTPResource("/") URI endpoint; + @Inject + CloudTrailLogWriter writer; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + @RegisterExtension final PartitionCleanup cleanup = new PartitionCleanup(); @@ -75,6 +92,115 @@ class S3BucketPolicyEnforcementIntegrationTest { } } + /** + * Within the bucket's account S3 refuses with the caller, the resource and the policy that refused it, and + * CloudTrail records the message S3 answered. + */ + @Test + void aRefusalNamesTheCallerTheResourceAndThePolicyThatRefusedIt() throws IOException { + String suffix = UUID.randomUUID().toString().substring(0, 8); + Credentials owner = adminOf("message-owner-" + suffix, ACCOUNT_A); + Credentials reader = userOf("message-reader-" + suffix, ACCOUNT_A); + String bucket = bucketWithObject("denied-message-" + suffix, owner); + String logs = "denied-message-logs-" + suffix; + cleanup.register(() -> EnforcementFixtures.removeBucket(endpoint.getPort(), owner.signer(), logs)); + createBucketAs(logs, owner.signer()); + String trail = "denied-message-" + suffix; + cloudTrail("CreateTrail", "{\"Name\":\"" + trail + "\",\"S3BucketName\":\"" + logs + "\"}"); + cleanup.register(() -> cloudTrail("DeleteTrail", "{\"Name\":\"" + trail + "\"}")); + cloudTrail("PutEventSelectors", "{\"TrailName\":\"" + trail + "\",\"EventSelectors\":[{\"ReadWriteType\":" + + "\"All\",\"IncludeManagementEvents\":false,\"DataResources\":[{\"Type\":\"AWS::S3::Object\"," + + "\"Values\":[\"arn:aws:s3:::" + bucket + "/\"]}]}]}"); + cloudTrail("StartLogging", "{\"Name\":\"" + trail + "\"}"); + + String message = deniedMessage(reader, bucket); + + assertEquals("User: " + reader.userArn() + " is not authorized to perform: s3:GetObject on resource: " + + "\"arn:aws:s3:::" + bucket + "/object.txt\" because no identity-based policy allows the s3:GetObject " + + "action", message); + writer.flushNow(); + JsonNode record = CloudTrailLogFiles.records(logs, owner.signer()).stream() + .filter(r -> "GetObject".equals(r.path("eventName").asText())) + .filter(r -> "AccessDenied".equals(r.path("errorCode").asText())) + .findFirst().orElseThrow(); + assertEquals(message, record.path("errorMessage").asText()); + } + + @Test + void aBucketPolicysExplicitDenyIsNamedAsAResourceBasedPolicys() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + Credentials owner = adminOf("deny-owner-" + suffix, ACCOUNT_A); + String bucket = bucketWithObject("bucket-deny-" + suffix, owner); + putBucketPolicyAs(bucket, """ + {"Version":"2012-10-17","Statement":[{"Effect":"Deny","Principal":{"AWS":"%s"}, + "Action":"s3:GetObject","Resource":"arn:aws:s3:::%s/*"}]} + """.formatted(owner.userArn(), bucket), owner.signer()); + + assertEquals("User: " + owner.userArn() + " is not authorized to perform: s3:GetObject on resource: " + + "\"arn:aws:s3:::" + bucket + "/object.txt\" with an explicit deny in a resource-based policy", + deniedMessage(owner, bucket)); + } + + @Test + void anIdentityPolicysExplicitDenyIsNamedAsAnIdentityBasedPolicys() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + Credentials owner = adminOf("identity-owner-" + suffix, ACCOUNT_A); + String callerName = "identity-denied-" + suffix; + Credentials caller = adminOf(callerName, ACCOUNT_A); + putUserPolicy(callerName, "DenyRead", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Deny","Action":"s3:GetObject","Resource":"*"}]}""", + ACCOUNT_A); + String bucket = bucketWithObject("identity-deny-" + suffix, owner); + String refusal = "User: " + caller.userArn() + " is not authorized to perform: s3:GetObject on resource: " + + "\"arn:aws:s3:::" + bucket + "/object.txt\" with an explicit deny in an identity-based policy"; + + assertEquals(refusal, deniedMessage(caller, bucket)); + // A copy's source is checked apart from the request, and refused with the same message. + assertEquals(refusal, given().filter(caller.signer()).header("x-amz-copy-source", "/" + bucket + "/object.txt") + .put("/" + bucket + "/copy.txt").then().statusCode(403).extract().xmlPath().getString("Error.Message")); + } + + /** "Cross-account requests outside of the same organization return a generic Access Denied message." */ + @Test + void aCallerFromAnotherAccountIsToldAccessDeniedAlone() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + Credentials owner = adminOf("cross-owner-" + suffix, ACCOUNT_A); + Credentials reader = adminOf("cross-reader-" + suffix, ACCOUNT_B); + String bucket = bucketWithObject("cross-denied-" + suffix, owner); + + assertEquals("Access Denied", deniedMessage(reader, bucket)); + } + + /** An account administrator for S3, removed after the test. */ + private Credentials adminOf(String userName, String accountId) { + cleanup.register(() -> EnforcementFixtures.removeUser(endpoint.getPort(), auth(accountId, "iam"), userName)); + return createAccountAdmin(userName, accountId); + } + + /** A user with no policy, removed after the test. */ + private Credentials userOf(String userName, String accountId) { + cleanup.register(() -> EnforcementFixtures.removeUser(endpoint.getPort(), auth(accountId, "iam"), userName)); + return createUser(userName, accountId); + } + + /** {@code bucket}, owned by {@code owner} and holding {@code object.txt}, removed after the test. */ + private String bucketWithObject(String bucket, Credentials owner) { + cleanup.register(() -> EnforcementFixtures.removeBucket(endpoint.getPort(), owner.signer(), bucket)); + createBucketAs(bucket, owner.signer()); + putObjectAs(bucket, "object.txt", "data", owner.signer()); + return bucket; + } + + /** The message S3 refuses {@code caller}'s read of {@code object.txt} with. */ + private static String deniedMessage(Credentials caller, String bucket) { + return given().filter(caller.signer()).get("/" + bucket + "/object.txt") + .then().statusCode(403).extract().xmlPath().getString("Error.Message"); + } + + private static void cloudTrail(String action, String body) { + invokeCloudTrail(auth(ACCOUNT_A, "cloudtrail"), action, body).then().statusCode(200); + } + record Credentials(String accessKeyId, String secretAccessKey, String userArn) { S3RequestSigner signer() { return S3RequestSigner.signedAs(accessKeyId, secretAccessKey); diff --git a/src/test/java/io/floci/aws/services/s3/S3PresignedPostAuthEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/s3/S3PresignedPostAuthEnforcementIntegrationTest.java index 51f6b066da..b24c0b9a3f 100644 --- a/src/test/java/io/floci/aws/services/s3/S3PresignedPostAuthEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/s3/S3PresignedPostAuthEnforcementIntegrationTest.java @@ -648,6 +648,30 @@ class S3PresignedPostAuthEnforcementIntegrationTest { } /** Removes {@link #BUCKET}, which the tests from {@code createBucket} on share, with the objects they uploaded. */ + /** + * A caller from another account, outside the bucket owner's organization, is refused with "Access Denied" alone: + * "Cross-account requests outside of the same organization return a generic Access Denied message". IAM refuses + * the POST before its signature is read, on the bucket's owner as the decision resolves it. + */ + @Test + @Order(37) + void anotherAccountsCallerIsToldAccessDeniedAlone() { + UserCredentials credentials = createUser(cleanup, endpoint.getPort(), OTHER_ACCOUNT_IAM_AUTH, + "presigned-post-other-account"); + + given() + .multiPart("key", "uploads/other-account.txt") + .multiPart("x-amz-credential", credentials.accessKeyId() + "/20260101/us-east-1/s3/aws4_request") + .multiPart("file", "other-account.txt", + "should not be stored".getBytes(StandardCharsets.UTF_8), "text/plain") + .when() + .post("/" + BUCKET) + .then() + .statusCode(403) + .body("Error.Code", Matchers.equalTo("AccessDenied")) + .body("Error.Message", Matchers.equalTo("Access Denied")); + } + @Test @Order(99) void cleanup_removeTheSharedBucket() { @@ -682,6 +706,10 @@ class S3PresignedPostAuthEnforcementIntegrationTest { "AWS4-HMAC-SHA256 Credential=" + LEGACY_ACCESS_KEY_ID + "/20260101/us-east-1/iam/aws4_request" + ", SignedHeaders=host, Signature=abc"; + private static final String OTHER_ACCOUNT_IAM_AUTH = + "AWS4-HMAC-SHA256 Credential=222233334444/20260101/us-east-1/iam/aws4_request" + + ", SignedHeaders=host, Signature=abc"; + private static void putUserPolicy(String userName, String policyName, String policyDocument) { given() .formParam("Action", "PutUserPolicy") diff --git a/src/test/java/io/floci/aws/services/s3/S3PresignedPostIamOnlyEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/s3/S3PresignedPostIamOnlyEnforcementIntegrationTest.java index 392392e085..a6683a4075 100644 --- a/src/test/java/io/floci/aws/services/s3/S3PresignedPostIamOnlyEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/s3/S3PresignedPostIamOnlyEnforcementIntegrationTest.java @@ -82,7 +82,10 @@ class S3PresignedPostIamOnlyEnforcementIntegrationTest { .post("/" + bucket) .then() .statusCode(403) - .body("Error.Code", equalTo("AccessDenied")); + .body("Error.Code", equalTo("AccessDenied")) + .body("Error.Message", equalTo("User: arn:aws:iam::000000000000:user/" + userName + + " is not authorized to perform: s3:PutObject on resource: \"arn:aws:s3:::" + bucket + + "/denied.txt\" with an explicit deny in an identity-based policy")); } @Test diff --git a/src/test/java/io/floci/aws/testing/CloudTrailLogFiles.java b/src/test/java/io/floci/aws/testing/CloudTrailLogFiles.java index ad4ffd02e0..cfdc3c28a9 100644 --- a/src/test/java/io/floci/aws/testing/CloudTrailLogFiles.java +++ b/src/test/java/io/floci/aws/testing/CloudTrailLogFiles.java @@ -2,6 +2,7 @@ package io.floci.aws.testing; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.restassured.filter.Filter; import io.restassured.path.xml.XmlPath; import io.restassured.specification.RequestSpecification; @@ -9,6 +10,7 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.function.UnaryOperator; import java.util.zip.GZIPInputStream; import static io.restassured.RestAssured.given; @@ -23,7 +25,7 @@ public final class CloudTrailLogFiles { /** Every record of every log file in {@code bucket}, in key order, across every page of the listing. */ public static List records(String bucket) throws IOException { - return records(bucket, null); + return records(bucket, (String) null); } /** @@ -31,12 +33,23 @@ public final class CloudTrailLogFiles { * null, as a test under IAM enforcement needs. */ public static List records(String bucket, String authorization) throws IOException { + return records(bucket, + request -> authorization == null ? request : request.header("Authorization", authorization)); + } + + /** As {@link #records(String)}, with each S3 request signed by {@code signer}, where S3 checks signatures. */ + public static List records(String bucket, Filter signer) throws IOException { + return records(bucket, request -> request.filter(signer)); + } + + private static List records(String bucket, UnaryOperator signing) + throws IOException { List records = new ArrayList<>(); - for (String key : keys(bucket, authorization)) { + for (String key : keys(bucket, signing)) { if (!key.endsWith(".json.gz")) { continue; } - byte[] gz = request(authorization).when().get("/" + bucket + "/" + key) + byte[] gz = signing.apply(given()).when().get("/" + bucket + "/" + key) .then().statusCode(200).extract().asByteArray(); try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(gz))) { MAPPER.readTree(in).path("Records").forEach(records::add); @@ -45,11 +58,11 @@ public final class CloudTrailLogFiles { return records; } - private static List keys(String bucket, String authorization) { + private static List keys(String bucket, UnaryOperator signing) { List keys = new ArrayList<>(); String token = null; do { - RequestSpecification listing = request(authorization).queryParam("list-type", "2"); + RequestSpecification listing = signing.apply(given()).queryParam("list-type", "2"); if (token != null) { listing = listing.queryParam("continuation-token", token); } @@ -60,9 +73,4 @@ public final class CloudTrailLogFiles { } while (token != null); return keys; } - - private static RequestSpecification request(String authorization) { - RequestSpecification request = given(); - return authorization == null ? request : request.header("Authorization", authorization); - } }