mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(core): mint every ARN in the request's partition (#4444)
* fix(core): mint every ARN in the request's partition
The build side of the multi-partition plan. 123 of the 126 gated arn:aws: literals in src/main now go through AwsArnUtils.Arn.of for regional resources, RegionResolver.buildGlobalArn for regionless ones minted under a request, and Arn.global with the region's partition where only a region is in scope, so a resource created in cn-north-1 or us-gov-west-1 carries arn:aws-cn: or arn:aws-us-gov:. CloudFormation's AWS::Partition and AWS::URLSuffix pseudo-parameters follow the stack region instead of a literal aws and amazonaws.com, and the SAM transform emits arn:${AWS::Partition}:... as the real translator does.
Seven literals are escaped with a stated reason: the stub-resource marker, the three Greengrass runtime ids from the Lambda Runtime enum, S3 Control's error text, and the two console client ids. The three still gated (the managed policy catalog, Flink and the RDS proxy validator) belong to later phases.
ResourceExplorer2IntegrationTest holds every listed ARN to its region's partition again; P0 had relaxed it to commercial regions while China-region resources were still minted arn:aws:.
Part of #4272
* fix(s3): evaluate a bucket policy against the bucket's own partition
A bucket policy names its bucket in the partition of the bucket's region. The authorization paths built the resource ARN from the request's partition instead, so with bucket names shared across regions a same-account request signed for cn-north-1 against a us-east-1 bucket was checked against arn:aws-cn:s3:::bucket/key, missed an explicit deny on arn:aws:s3:::bucket/*, and was allowed. The seven S3Service call sites now take the partition from the bucket's region, which also drops their dependency on a RegionResolver that the package-private test constructors leave null.
* fix(iam): match S3 resource ARNs against the bucket's own partition under IAM enforcement
IamEnforcementFilter built every S3 resource ARN through a regionless Arn.of, which always yields arn:aws:. Once AWS::Partition follows the stack region, a bucket created in cn-north-1 gets a policy naming arn:aws-cn:s3:::bucket/*, and under IAM enforcement its statements never matched, so an explicit deny was skipped.
ResourceArnBuilder now mints S3 ARNs in the request region's partition, which is right for a bucket that does not exist yet. ResourcePolicyProvider gains resolveResourceArn, a default no-op, and S3ResourcePolicyProvider re-mints an existing bucket's ARN in the partition of the bucket's region before any identity or resource policy is evaluated. S3Service.bucketPartition is the single rule for both layers and for the CopyObject source and presigned POST ARNs in S3Controller.
S3PartitionBucketPolicyIamEnforcementIntegrationTest runs with IAM enforcement alone, so S3's own policy check cannot deny first: the China-bucket deny fails without this change, and the cross-partition deny on a us-east-1 bucket fails if the re-minting step is skipped.
This commit is contained in:
1 parent
93c7b1f93f
commit
0e8f965cb6
89 files changed
+763
-297
No files matched your search
@@ -68,6 +68,7 @@ class IamEnforcementFilterTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
config = mock(EmulatorConfig.class);
|
||||
when(config.partitions()).thenReturn(mock(EmulatorConfig.PartitionsConfig.class));
|
||||
services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
iamConfig = mock(EmulatorConfig.IamServiceConfig.class);
|
||||
accountResolver = mock(AccountResolver.class);
|
||||
@@ -1307,7 +1308,7 @@ class IamEnforcementFilterTest {
|
||||
Instance<ResourcePolicyProvider> providers =
|
||||
mock(Instance.class);
|
||||
when(providers.isUnsatisfied()).thenReturn(false);
|
||||
when(providers.iterator()).thenReturn(List.of(provider).iterator());
|
||||
when(providers.iterator()).thenAnswer(invocation -> List.of(provider).iterator());
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<ScpProvider> scpProvider =
|
||||
mock(Instance.class);
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.PartitionMatrix;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Every ARN minted for a request signed in another partition carries that partition. One probe
|
||||
* per sweep group: the CloudFormation pseudo-parameters (template engine), a KMS default key
|
||||
* policy principal (an IAM root ARN built through the resolver), an SSM parameter (a regional
|
||||
* {@code Arn.of} site) and a Service Catalog portfolio (a service that never imported the helper).
|
||||
*/
|
||||
@QuarkusTest
|
||||
class PartitionArnMintingIntegrationTest {
|
||||
|
||||
private static final String REGION = "cn-north-1";
|
||||
private static final String JSON_1_1 = "application/x-amz-json-1.1";
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void cloudFormationPseudoParametersFollowTheStackRegion() {
|
||||
String stackName = "partition-pseudo-" + Long.toString(System.nanoTime(), 36);
|
||||
String template = """
|
||||
{
|
||||
"Resources": {"Wait": {"Type": "AWS::CloudFormation::WaitConditionHandle"}},
|
||||
"Outputs": {
|
||||
"Partition": {"Value": {"Ref": "AWS::Partition"}},
|
||||
"Suffix": {"Value": {"Ref": "AWS::URLSuffix"}},
|
||||
"Sub": {"Value": {"Fn::Sub": "arn:${AWS::Partition}:iam::aws:policy/AdministratorAccess"}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth(REGION, "cloudformation"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth(REGION, "cloudformation"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", stackName)
|
||||
.when().post("/"));
|
||||
|
||||
given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth(REGION, "cloudformation"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<OutputValue>aws-cn</OutputValue>"))
|
||||
.body(containsString("<OutputValue>amazonaws.com.cn</OutputValue>"))
|
||||
.body(containsString("<OutputValue>arn:aws-cn:iam::aws:policy/AdministratorAccess</OutputValue>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void kmsDefaultKeyPolicyNamesTheRootPrincipalInTheRequestPartition() {
|
||||
Response created = given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth(REGION, "kms"))
|
||||
.header("X-Amz-Target", "TrentService.CreateKey")
|
||||
.contentType(JSON_1_1)
|
||||
.body("{}")
|
||||
.when().post("/");
|
||||
created.then().statusCode(200);
|
||||
String keyId = created.jsonPath().getString("KeyMetadata.KeyId");
|
||||
String keyArn = created.jsonPath().getString("KeyMetadata.Arn");
|
||||
cleanup.register(() -> given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth(REGION, "kms"))
|
||||
.header("X-Amz-Target", "TrentService.ScheduleKeyDeletion")
|
||||
.contentType(JSON_1_1)
|
||||
.body("{\"KeyId\":\"" + keyId + "\",\"PendingWindowInDays\":7}")
|
||||
.when().post("/"));
|
||||
assertTrue(keyArn.startsWith("arn:aws-cn:kms:" + REGION + ":"), keyArn);
|
||||
|
||||
String policy = given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth(REGION, "kms"))
|
||||
.header("X-Amz-Target", "TrentService.GetKeyPolicy")
|
||||
.contentType(JSON_1_1)
|
||||
.body("{\"KeyId\":\"" + keyId + "\",\"PolicyName\":\"default\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("Policy");
|
||||
assertTrue(policy.contains("arn:aws-cn:iam::000000000000:root"), policy);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ssmParameterArnIsMintedInTheRequestPartition() {
|
||||
String name = "/partition/" + Long.toString(System.nanoTime(), 36);
|
||||
given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth(REGION, "ssm"))
|
||||
.header("X-Amz-Target", "AmazonSSM.PutParameter")
|
||||
.contentType(JSON_1_1)
|
||||
.body("{\"Name\":\"" + name + "\",\"Type\":\"String\",\"Value\":\"v\"}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth(REGION, "ssm"))
|
||||
.header("X-Amz-Target", "AmazonSSM.DeleteParameter")
|
||||
.contentType(JSON_1_1)
|
||||
.body("{\"Name\":\"" + name + "\"}")
|
||||
.when().post("/"));
|
||||
|
||||
String arn = given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth(REGION, "ssm"))
|
||||
.header("X-Amz-Target", "AmazonSSM.GetParameter")
|
||||
.contentType(JSON_1_1)
|
||||
.body("{\"Name\":\"" + name + "\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("Parameter.ARN");
|
||||
assertEquals("arn:aws-cn:ssm:" + REGION + ":000000000000:parameter" + name, arn);
|
||||
}
|
||||
|
||||
@Test
|
||||
void serviceCatalogPortfolioArnIsMintedInTheRequestPartition() {
|
||||
String token = Long.toString(System.nanoTime(), 36);
|
||||
Response created = given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth(REGION, "servicecatalog"))
|
||||
.header("X-Amz-Target", "AWS242ServiceCatalogService.CreatePortfolio")
|
||||
.contentType(JSON_1_1)
|
||||
.body("{\"DisplayName\":\"partition-" + token + "\",\"ProviderName\":\"floci\",\"IdempotencyToken\":\"" + token + "\"}")
|
||||
.when().post("/");
|
||||
created.then().statusCode(200);
|
||||
String id = created.jsonPath().getString("PortfolioDetail.Id");
|
||||
cleanup.register(() -> given()
|
||||
.header("Authorization", PartitionMatrix.sigV4Auth(REGION, "servicecatalog"))
|
||||
.header("X-Amz-Target", "AWS242ServiceCatalogService.DeletePortfolio")
|
||||
.contentType(JSON_1_1)
|
||||
.body("{\"Id\":\"" + id + "\"}")
|
||||
.when().post("/"));
|
||||
|
||||
String arn = created.jsonPath().getString("PortfolioDetail.ARN");
|
||||
assertEquals("arn:aws-cn:catalog:" + REGION + ":000000000000:portfolio/" + id, arn);
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -21,7 +21,7 @@ class ControlCatalogServiceTest {
|
||||
void listControlsFiltersByImplementationIdentifierAndProvider() throws Exception {
|
||||
var response = service.listControls(objectMapper.readTree("""
|
||||
{"Filter":{"Implementations":{"Identifiers":["CT.S3.PV.5"]},"GovernedProviders":["AWS"]}}
|
||||
"""), null, null);
|
||||
"""), null, null, "aws");
|
||||
|
||||
assertEquals(1, response.path("Controls").size());
|
||||
assertEquals("CT.S3.PV.5", response.path("Controls").get(0).path("Implementation").path("Identifier").asText());
|
||||
@@ -30,7 +30,7 @@ class ControlCatalogServiceTest {
|
||||
@Test
|
||||
void listControlsRejectsInvalidProviderFilter() throws Exception {
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.listControls(
|
||||
objectMapper.readTree("{\"Filter\":{\"GovernedProviders\":[\"invalid\"]}}"), null, null));
|
||||
objectMapper.readTree("{\"Filter\":{\"GovernedProviders\":[\"invalid\"]}}"), null, null, "aws"));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
@@ -39,13 +39,13 @@ class ControlCatalogServiceTest {
|
||||
void clearRemovesPersistedCatalogAndNextReadReseedsIt() {
|
||||
assertTrue(controls.keysForAccount("000000000000").isEmpty());
|
||||
|
||||
service.listControls(objectMapper.createObjectNode(), null, null);
|
||||
service.listControls(objectMapper.createObjectNode(), null, null, "aws");
|
||||
assertFalse(controls.keysForAccount("000000000000").isEmpty());
|
||||
|
||||
service.clear();
|
||||
assertTrue(controls.keysForAccount("000000000000").isEmpty());
|
||||
|
||||
var response = service.listControls(objectMapper.createObjectNode(), null, null);
|
||||
var response = service.listControls(objectMapper.createObjectNode(), null, null, "aws");
|
||||
assertEquals(6, response.path("Controls").size());
|
||||
assertFalse(controls.keysForAccount("000000000000").isEmpty());
|
||||
}
|
||||
|
||||
@@ -295,6 +295,8 @@ class EksClusterManagerTest {
|
||||
RegionResolver regionResolver = Mockito.mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
|
||||
when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation ->
|
||||
"arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2));
|
||||
|
||||
EksClusterManager manager = new EksClusterManager(containerBuilder, lifecycleManager,
|
||||
Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class),
|
||||
@@ -806,6 +808,8 @@ class EksClusterManagerTest {
|
||||
regionResolver = Mockito.mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
|
||||
when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation ->
|
||||
"arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2));
|
||||
|
||||
capturedCmds = new ArrayList<>();
|
||||
execCreate = Mockito.mock(ExecCreateCmd.class, Mockito.withSettings().defaultAnswer(Mockito.RETURNS_SELF));
|
||||
@@ -1245,6 +1249,8 @@ class EksClusterManagerTest {
|
||||
regionResolver = Mockito.mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
|
||||
when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation ->
|
||||
"arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2));
|
||||
|
||||
oidcService = Mockito.mock(EksOidcService.class);
|
||||
when(oidcService.newIssuerUrl(anyString())).thenReturn(
|
||||
@@ -1674,6 +1680,8 @@ class EksClusterManagerTest {
|
||||
RegionResolver regionResolver = Mockito.mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
|
||||
when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation ->
|
||||
"arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2));
|
||||
|
||||
manager = new EksClusterManager(containerBuilder, lifecycleManager,
|
||||
Mockito.mock(ContainerDetector.class), portAllocator,
|
||||
@@ -1872,6 +1880,8 @@ class EksClusterManagerTest {
|
||||
RegionResolver regionResolver = Mockito.mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
|
||||
when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation ->
|
||||
"arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2));
|
||||
|
||||
FlociCertificateAuthority certificateAuthority = Mockito.mock(FlociCertificateAuthority.class);
|
||||
when(certificateAuthority.caPem()).thenReturn(CA_PEM);
|
||||
@@ -2003,6 +2013,8 @@ class EksClusterManagerTest {
|
||||
RegionResolver regionResolver = Mockito.mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
|
||||
when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation ->
|
||||
"arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2));
|
||||
|
||||
logStreamer = Mockito.mock(ContainerLogStreamer.class);
|
||||
mockHandle = Mockito.mock(Closeable.class);
|
||||
|
||||
@@ -324,6 +324,15 @@ class ResourceArnBuilderTest {
|
||||
assertEquals("arn:aws:s3:::my-bucket", arn);
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3BuildsArnsInTheRequestRegionsPartition() {
|
||||
when(uriInfo.getPath()).thenReturn("/my-bucket/key.txt");
|
||||
assertEquals("arn:aws-cn:s3:::my-bucket/key.txt",
|
||||
builder.build("s3", ctx, "cn-north-1", "000000000000"));
|
||||
when(uriInfo.getPath()).thenReturn("/");
|
||||
assertEquals("arn:aws-us-gov:s3:::*", builder.build("s3", ctx, "us-gov-west-1", "000000000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3BuildsObjectArn() {
|
||||
when(uriInfo.getPath()).thenReturn("/my-bucket/folder/file.json");
|
||||
|
||||
+2
-9
@@ -1507,15 +1507,8 @@ class ResourceExplorer2IntegrationTest {
|
||||
String arn = (String) resource.get("Arn");
|
||||
String service = (String) resource.get("Service");
|
||||
Arn parsed = AwsArnUtils.parse(arn);
|
||||
String expectedPartition = AwsRegions.partitionFor(parsed.region());
|
||||
// Only commercial regions are held to their partition here: resources another test
|
||||
// leaves in a China or GovCloud region are still minted arn:aws: by build sites that
|
||||
// have not moved to Arn.of yet, which the partition plan's build-site phase fixes and
|
||||
// then tightens this assertion to every region.
|
||||
if ("aws".equals(expectedPartition)) {
|
||||
assertEquals(expectedPartition, parsed.partition(),
|
||||
"ARN partition must be the one its region belongs to, got: " + arn);
|
||||
}
|
||||
assertEquals(AwsRegions.partitionFor(parsed.region()), parsed.partition(),
|
||||
"ARN partition must be the one its region belongs to, got: " + arn);
|
||||
assertTrue(arn.contains(service),
|
||||
"ARN should contain service '" + service + "', got: " + arn);
|
||||
}
|
||||
|
||||
+56
@@ -2096,6 +2096,62 @@ class S3AuthEnforcementIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(55)
|
||||
void bucketPolicyDenyHoldsForARequestSignedInAnotherPartition() {
|
||||
String bucket = "auth-partition-deny-" + Long.toUnsignedString(System.nanoTime(), 36);
|
||||
String key = "guarded.txt";
|
||||
|
||||
given().filter(LOCAL_SIGNER).when().put("/" + bucket).then().statusCode(200);
|
||||
given()
|
||||
.filter(LOCAL_SIGNER)
|
||||
.body("original")
|
||||
.when()
|
||||
.put("/" + bucket + "/" + key)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
given()
|
||||
.filter(LOCAL_SIGNER)
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Deny",
|
||||
"Principal": "*",
|
||||
"Action": ["s3:GetObject", "s3:PutObject"],
|
||||
"Resource": "arn:aws:s3:::%s/*"
|
||||
}
|
||||
]
|
||||
}
|
||||
""".formatted(bucket))
|
||||
.when()
|
||||
.put("/" + bucket + "?policy")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// The bucket lives in us-east-1, so its policy names it arn:aws: even when a same-account
|
||||
// caller signs for a China region, and the deny has to match as written.
|
||||
S3RequestSigner chinaSigner = LOCAL_SIGNER.inRegion("cn-north-1");
|
||||
given()
|
||||
.filter(chinaSigner)
|
||||
.body("overwritten")
|
||||
.when()
|
||||
.put("/" + bucket + "/" + key)
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body(containsString("AccessDenied"));
|
||||
|
||||
given()
|
||||
.filter(chinaSigner)
|
||||
.when()
|
||||
.get("/" + bucket + "/" + key)
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body(containsString("AccessDenied"));
|
||||
}
|
||||
|
||||
private static RequestSpecification presignedRequest(String signature) {
|
||||
return given()
|
||||
.queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
|
||||
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testutil.S3RequestSigner;
|
||||
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 java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
|
||||
/**
|
||||
* A bucket policy names its bucket in the partition of the bucket's own region, and IAM
|
||||
* enforcement has to match it that way whatever partition the request was signed for. Runs with
|
||||
* IAM enforcement alone, so S3's own bucket-policy check cannot deny first and hide the filter's
|
||||
* decision.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class S3PartitionBucketPolicyIamEnforcementIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "444455556666";
|
||||
|
||||
@Test
|
||||
void chinaBucketPolicyNamedInItsOwnPartitionHolds() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String bucket = "cn-policy-" + suffix;
|
||||
String key = "guarded.txt";
|
||||
S3RequestSigner china = createAccountAdmin("cn-admin-" + suffix).inRegion("cn-north-1");
|
||||
|
||||
createBucket(bucket, china);
|
||||
putObject(bucket, key, china);
|
||||
putBucketPolicy(bucket, denyObjectReadWritePolicy("aws-cn", bucket), china);
|
||||
|
||||
assertPutObjectDenied(bucket, key, china);
|
||||
assertGetObjectDenied(bucket, key, china);
|
||||
}
|
||||
|
||||
@Test
|
||||
void commercialBucketPolicyHoldsForARequestSignedInAnotherPartition() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String bucket = "us-policy-" + suffix;
|
||||
String key = "guarded.txt";
|
||||
S3RequestSigner commercial = createAccountAdmin("us-admin-" + suffix);
|
||||
|
||||
createBucket(bucket, commercial);
|
||||
putObject(bucket, key, commercial);
|
||||
putBucketPolicy(bucket, denyObjectReadWritePolicy("aws", bucket), commercial);
|
||||
|
||||
S3RequestSigner china = commercial.inRegion("cn-north-1");
|
||||
assertPutObjectDenied(bucket, key, china);
|
||||
assertGetObjectDenied(bucket, key, china);
|
||||
}
|
||||
|
||||
private static String denyObjectReadWritePolicy(String partition, String bucket) {
|
||||
return """
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Deny",
|
||||
"Principal": "*",
|
||||
"Action": ["s3:GetObject", "s3:PutObject"],
|
||||
"Resource": "arn:%s:s3:::%s/*"
|
||||
}
|
||||
]
|
||||
}""".formatted(partition, bucket);
|
||||
}
|
||||
|
||||
private static void assertPutObjectDenied(String bucket, String key, S3RequestSigner signer) {
|
||||
given()
|
||||
.filter(signer)
|
||||
.body("overwritten")
|
||||
.when()
|
||||
.put("/" + bucket + "/" + key)
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body(containsString("AccessDenied"));
|
||||
}
|
||||
|
||||
private static void assertGetObjectDenied(String bucket, String key, S3RequestSigner signer) {
|
||||
given()
|
||||
.filter(signer)
|
||||
.when()
|
||||
.get("/" + bucket + "/" + key)
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body(containsString("AccessDenied"));
|
||||
}
|
||||
|
||||
private static void createBucket(String bucket, S3RequestSigner signer) {
|
||||
given().filter(signer).when().put("/" + bucket).then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void putObject(String bucket, String key, S3RequestSigner signer) {
|
||||
given().filter(signer).body("original").when().put("/" + bucket + "/" + key).then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void putBucketPolicy(String bucket, String policy, S3RequestSigner signer) {
|
||||
given()
|
||||
.filter(signer)
|
||||
.contentType("application/json")
|
||||
.body(policy)
|
||||
.when()
|
||||
.put("/" + bucket + "?policy")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
/** An IAM user in {@link #ACCOUNT} whose identity policy allows every S3 action. */
|
||||
private static S3RequestSigner createAccountAdmin(String userName) {
|
||||
iam("CreateUser", "UserName", userName);
|
||||
iam("PutUserPolicy", "UserName", userName,
|
||||
"PolicyName", "S3Admin",
|
||||
"PolicyDocument", """
|
||||
{"Version": "2012-10-17",
|
||||
"Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]}""");
|
||||
ExtractableResponse<Response> key = iam("CreateAccessKey", "UserName", userName);
|
||||
return S3RequestSigner.signedAs(
|
||||
key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"),
|
||||
key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey"));
|
||||
}
|
||||
|
||||
private static ExtractableResponse<Response> iam(String action, String... params) {
|
||||
RequestSpecification request = given()
|
||||
.formParam("Action", action)
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT
|
||||
+ "/20260629/us-east-1/iam/aws4_request, SignedHeaders=host, Signature=abc");
|
||||
for (int i = 0; i < params.length; i += 2) {
|
||||
request = request.formParam(params[i], params[i + 1]);
|
||||
}
|
||||
return request.when().post("/").then().statusCode(200).extract();
|
||||
}
|
||||
}
|
||||
+9
-2
@@ -513,7 +513,14 @@ class S3PublicAccessEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void arnHelpersBuildBucketAndObjectArns() {
|
||||
assertEquals(BUCKET_ARN, S3PublicAccessEvaluator.bucketArn(BUCKET));
|
||||
assertEquals(OBJECT_ARN, S3PublicAccessEvaluator.objectArn(BUCKET, "folder/object.txt"));
|
||||
assertEquals(BUCKET_ARN, S3PublicAccessEvaluator.bucketArn("aws", BUCKET));
|
||||
assertEquals(OBJECT_ARN, S3PublicAccessEvaluator.objectArn("aws", BUCKET, "folder/object.txt"));
|
||||
}
|
||||
|
||||
/** The policy-evaluation ARNs carry the request's partition, or a China bucket policy never matches. */
|
||||
@Test
|
||||
void arnHelpersCarryTheGivenPartition() {
|
||||
assertEquals("arn:aws-cn:s3:::" + BUCKET, S3PublicAccessEvaluator.bucketArn("aws-cn", BUCKET));
|
||||
assertEquals("arn:aws-us-gov:s3:::" + BUCKET + "/k", S3PublicAccessEvaluator.objectArn("aws-us-gov", BUCKET, "k"));
|
||||
}
|
||||
}
|
||||
+24
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.testing.PartitionMatrix.PartitionCase;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.NullAndEmptySource;
|
||||
@@ -8,6 +9,8 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The bucket-policy lookup is on the authorization path: a bucket ARN whose partition the
|
||||
@@ -30,4 +33,25 @@ class S3ResourcePolicyProviderTest {
|
||||
void nonS3ArnsYieldNoBucket(String value) {
|
||||
assertNull(S3ResourcePolicyProvider.extractBucketName(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveResourceArnNamesAnExistingBucketInItsOwnPartition() {
|
||||
S3Service s3Service = mock(S3Service.class);
|
||||
when(s3Service.bucketPartition("commercial-bucket")).thenReturn("aws");
|
||||
S3ResourcePolicyProvider provider = new S3ResourcePolicyProvider(s3Service);
|
||||
|
||||
assertEquals("arn:aws:s3:::commercial-bucket/documents/hello.txt",
|
||||
provider.resolveResourceArn("s3", "arn:aws-cn:s3:::commercial-bucket/documents/hello.txt"));
|
||||
assertEquals("arn:aws:s3:::commercial-bucket",
|
||||
provider.resolveResourceArn("s3", "arn:aws-cn:s3:::commercial-bucket"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveResourceArnLeavesWildcardsAndOtherServicesAlone() {
|
||||
S3ResourcePolicyProvider provider = new S3ResourcePolicyProvider(mock(S3Service.class));
|
||||
|
||||
assertEquals("arn:aws-cn:s3:::*", provider.resolveResourceArn("s3", "arn:aws-cn:s3:::*"));
|
||||
assertEquals("arn:aws-cn:sqs:cn-north-1:000000000000:q",
|
||||
provider.resolveResourceArn("sqs", "arn:aws-cn:sqs:cn-north-1:000000000000:q"));
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,8 @@ class SigninServiceTest {
|
||||
RegionResolver region = mock(RegionResolver.class);
|
||||
accountId = new AtomicReference<>(ACCOUNT_A);
|
||||
when(region.getAccountId()).thenAnswer(ignored -> accountId.get());
|
||||
when(region.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation ->
|
||||
"arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2));
|
||||
clock = new MutableClock();
|
||||
service = new SigninService(iam, region, new ObjectMapper(), clock);
|
||||
}
|
||||
|
||||
@@ -92,6 +92,12 @@ public final class S3RequestSigner implements Filter {
|
||||
signatureOverride, contentSha256, signHost);
|
||||
}
|
||||
|
||||
/** Signs with {@code region} in the credential scope instead of {@code us-east-1}. */
|
||||
public S3RequestSigner inRegion(String region) {
|
||||
return new S3RequestSigner(accessKeyId, secretKey, sessionToken, region, signedAt,
|
||||
signatureOverride, contentSha256Override, signHost);
|
||||
}
|
||||
|
||||
/** Leaves {@code host} out of {@code SignedHeaders}; no real signer does this. */
|
||||
public S3RequestSigner withoutSignedHost() {
|
||||
return new S3RequestSigner(accessKeyId, secretKey, sessionToken, region, signedAt,
|
||||
|
||||
Reference in new issue
Block a user