mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(s3): name the caller and the policy that refused it in S3's access denied message (#9281)
S3 answered a refused request with "User is not authorized to perform: s3:GetObject", while the CloudTrail data event recorded a message of its own that named the access key as the user (user/AKIA...) and always gave "no identity-based policy allows" as the reason, even for an explicit deny. A copy's source, a presigned POST and the other resources a service checks apart from the request were refused with that same message. S3's guide says a refusal within the bucket's account or organization names the caller, the resource and the type of policy that refused it, that CloudTrail logs the same context, and that a request from outside the organization gets "Access Denied" alone. Both refusals now build the message as the other refusals in IamEnforcementFilter do: the caller's ARN and the reason firstRefusal gives, or a bucket policy's explicit deny, through AccessDeniedMessages.notAuthorized. S3 answers with it and CloudTrail records it, and a caller from another organization is told "Access Denied", judged on the bucket's owner as the decision resolves it, since a presigned POST names none. S3 Control keeps its own envelope and wording. The resources Redshift, Secrets Manager and SSM check apart from the request name the caller the same way. CloudTrailLogFiles also reads through a signing filter, for a test where S3 checks signatures.
This commit is contained in:
1 parent
ac844769fb
commit
fad1093175
5 files changed
+246
-29
No files matched your search
@@ -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);
|
||||
|
||||
+28
@@ -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")
|
||||
|
||||
+4
-1
@@ -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
|
||||
|
||||
@@ -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<JsonNode> 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<JsonNode> 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<JsonNode> records(String bucket, Filter signer) throws IOException {
|
||||
return records(bucket, request -> request.filter(signer));
|
||||
}
|
||||
|
||||
private static List<JsonNode> records(String bucket, UnaryOperator<RequestSpecification> signing)
|
||||
throws IOException {
|
||||
List<JsonNode> 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<String> keys(String bucket, String authorization) {
|
||||
private static List<String> keys(String bucket, UnaryOperator<RequestSpecification> signing) {
|
||||
List<String> 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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user