feat(resourcegroups): support EC2 capacity reservation pools (#6011)

Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-20 00:04:50 -04:00
1 parent 691499d335
commit be2cb677d0
28 files changed
+1772 -1

No files matched your search

@@ -45,7 +45,7 @@ class PartitionCrossServiceSmokeIntegrationTest {
"ecr", "ecs", "efs", "eks", "elasticache", "elasticbeanstalk", "elbv2", "emr", "emrserverless",
"eventbridge", "firehose", "fis", "glue", "guardduty", "iot", "kinesis", "kinesisanalytics", "lambda",
"lambdamicrovms", "lambdaweb", "memorydb", "msk", "mwaa", "networkfirewall", "oam", "opensearch", "organizations",
"pipes", "ram", "rds", "redshift", "redshiftserverless", "resourceexplorer2", "route53resolver",
"pipes", "ram", "rds", "redshift", "redshiftserverless", "resourceexplorer2", "resourcegroups", "route53resolver",
"s3tables", "s3vectors", "sagemaker", "scheduler", "secretsmanager", "servicequotas", "ses", "sns", "sqs",
"stepfunctions", "timestreaminfluxdb", "transfer", "verifiedpermissions", "wafv2");
@@ -61,6 +61,22 @@ class PartitionCrossServiceSmokeIntegrationTest {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@ParameterizedTest
@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
void resourceGroupArn(PartitionCase partitionCase) {
String region = offered(partitionCase, "resource-groups");
String name = unique("smoke-pool", partitionCase);
String body = "{\"Name\":\"" + name + "\",\"Configuration\":["
+ "{\"Type\":\"AWS::EC2::CapacityReservationPool\"},"
+ "{\"Type\":\"AWS::ResourceGroups::Generic\",\"Parameters\":["
+ "{\"Name\":\"allowed-resource-types\",\"Values\":[\"AWS::EC2::CapacityReservation\"]}]}]}";
String arn = signed(region, "resource-groups").contentType(JSON).body(body)
.when().post("/groups").then().statusCode(200).extract().path("Group.GroupArn");
cleanup.register(() -> signed(region, "resource-groups").contentType(JSON)
.body("{\"Group\":\"" + arn + "\"}").when().post("/delete-group"));
PartitionMatrix.assertArnIn(partitionCase, arn);
}
@ParameterizedTest
@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
void snsTopicArn(PartitionCase partitionCase) {
@@ -36,6 +36,19 @@ class IamActionRegistryTest {
private final IamActionRegistry registry = new IamActionRegistry();
@ParameterizedTest
@CsvSource({"groups,CreateGroup", "get-group,GetGroup", "delete-group,DeleteGroup",
"group-resources,GroupResources", "list-group-resources,ListGroupResources"})
void resourceGroupsManagementRoutesResolveTheirOwnActions(String path, String operation) {
ContainerRequestContext ctx = mockCtx("POST", "/_rg/" + path,
new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}");
assertEquals("resource-groups:" + operation, registry.resolveRoute("resource-groups", ctx));
assertNull(registry.resolveRoute("resource-groups", mockCtx("GET", "/_rg/" + path,
new MultivaluedHashMap<>(), null, "")));
assertNull(registry.resolveRoute("resource-groups", mockCtx("POST", "/_rg/" + path + "/extra",
new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}")));
}
@Test
void cloudWatchGetUsesQueryActionAndOperationPrecedence() {
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
@@ -682,6 +682,23 @@ class ResourceArnBuilderTest {
}).when(ctx).setEntityStream(any(InputStream.class));
}
@Test
void resourceGroupTargetsUseNamesOrArnsInTheRequestPartition() {
for (String region : List.of("us-east-1", "cn-north-1", "us-gov-west-1")) {
String arn = "arn:" + AwsRegions.partitionFor(region) + ":resource-groups:"
+ region + ":" + ACCOUNT + ":group/pool";
for (String selector : List.of("Name", "GroupName", "Group")) {
when(uriInfo.getPath()).thenReturn(selector.equals("Name") ? "_rg/groups" : "_rg/get-group");
setJsonBody("{\"" + selector + "\":\"pool\"}");
assertEquals(List.of(arn), builder.buildResources("resource-groups", ctx, region, ACCOUNT));
}
setJsonBody("{\"Group\":\"" + arn + "\"}");
assertEquals(List.of(arn), builder.buildResources("resource-groups", ctx, region, ACCOUNT));
}
setJsonBody("{}");
assertEquals(List.of("*"), builder.buildResources("resource-groups", ctx, "us-east-1", ACCOUNT));
}
@Test
void logStreamTargetsUseTheServingActionAndRequestPartition() {
for (String action : List.of("logs:CreateLogStream", "logs:DeleteLogStream")) {
@@ -0,0 +1,146 @@
package io.github.hectorvent.floci.services.resourcegroups;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.net.URI;
import java.util.Map;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class ResourceGroupsIamEnforcementIntegrationTest {
private static final String ACCOUNT = "111111111111";
private static final Map<String, String> OPERATIONS = Map.of(
"/groups", "CreateGroup",
"/get-group", "GetGroup",
"/delete-group", "DeleteGroup",
"/group-resources", "GroupResources",
"/list-group-resources", "ListGroupResources");
@TestHTTPResource("/")
static URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void explicitDenyAppliesToEveryManagementOperation() {
String user = "rg-deny-" + UUID.randomUUID();
String key = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ACCOUNT, "iam"), user)
.accessKeyId();
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), user, "deny", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"*","Resource":"*"},
{"Effect":"Deny","Action":"resource-groups:*","Resource":"*"}]}
""");
for (String path : OPERATIONS.keySet()) {
call(key, path, Map.of()).statusCode(403).body("__type", equalTo("AccessDeniedException"));
}
}
@Test
void createAuthorizesNameInsteadOfIgnoredGroupSelectors() {
String user = "rg-create-scope-" + UUID.randomUUID();
String key = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ACCOUNT, "iam"), user)
.accessKeyId();
String name = "rg-secret-" + UUID.randomUUID();
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), user, "allow", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"resource-groups:CreateGroup",
"Resource":"arn:aws:resource-groups:us-east-1:%s:group/allowed"}]}
""".formatted(ACCOUNT));
call(key, "/groups", "{\"Name\":\"" + name + "\",\"Group\":\"allowed\",\"GroupName\":\"allowed\","
+ "\"Configuration\":" + ResourceGroupsServiceTest.CONFIGURATION + "}").statusCode(403);
call(ACCOUNT, "/get-group", Map.of("Group", name)).statusCode(404);
}
@Test
void groupScopedDenyAppliesToEveryManagementOperation() {
String user = "rg-scoped-deny-" + UUID.randomUUID();
String key = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ACCOUNT, "iam"), user)
.accessKeyId();
String name = "rg-scoped-" + UUID.randomUUID();
String arn = "arn:aws:resource-groups:us-east-1:" + ACCOUNT + ":group/" + name;
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), user, "deny", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"*","Resource":"*"},
{"Effect":"Deny","Action":"resource-groups:*","Resource":"%s"}]}
""".formatted(arn));
for (String path : OPERATIONS.keySet()) {
Object body = path.equals("/groups")
? "{\"Name\":\"" + name + "\",\"Configuration\":" + ResourceGroupsServiceTest.CONFIGURATION + "}"
: Map.of("Group", name);
call(key, path, body).statusCode(403).body("__type", equalTo("AccessDeniedException"));
if (!path.equals("/groups")) {
call(key, path, Map.of("Group", arn)).statusCode(403)
.body("__type", equalTo("AccessDeniedException"));
}
}
call(ACCOUNT, "/get-group", Map.of("Group", name)).statusCode(404);
}
@ParameterizedTest
@CsvSource({"Group,false", "Group,true", "GroupName,false"})
void aGroupScopedGrantAllowsOnlyThatGroup(String selector, boolean useArn) {
String name = "rg-scoped-allow-" + UUID.randomUUID();
String arn = "arn:aws:resource-groups:us-east-1:" + ACCOUNT + ":group/" + name;
String user = "rg-scoped-allow-" + UUID.randomUUID();
String key = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ACCOUNT, "iam"), user)
.accessKeyId();
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), user, "allow", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"resource-groups:GetGroup","Resource":"%s"}]}
""".formatted(arn));
call(ACCOUNT, "/groups", "{\"Name\":\"" + name + "\",\"Configuration\":"
+ ResourceGroupsServiceTest.CONFIGURATION + "}").statusCode(200);
try {
call(key, "/get-group", Map.of(selector, useArn ? arn : name)).statusCode(200);
call(key, "/get-group", Map.of("Group", name + "-other")).statusCode(403);
call(key, "/delete-group", Map.of("Group", name)).statusCode(403);
} finally {
call(ACCOUNT, "/delete-group", Map.of("Group", name)).statusCode(200);
}
}
@Test
void allowedManagementOperationsStillReachTheirService() {
String user = "rg-allow-" + UUID.randomUUID();
String key = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ACCOUNT, "iam"), user)
.accessKeyId();
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), user, "allow", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"resource-groups:*","Resource":"*"}]}
""");
String name = "rg-allow-" + UUID.randomUUID();
call(key, "/groups", "{\"Name\":\"" + name + "\",\"Configuration\":"
+ ResourceGroupsServiceTest.CONFIGURATION + "}").statusCode(200);
try {
call(key, "/get-group", Map.of("Group", name)).statusCode(200);
call(key, "/list-group-resources", Map.of("Group", name)).statusCode(200);
call(key, "/group-resources", Map.of("Group", name, "ResourceArns",
new String[]{"arn:aws:ec2:us-east-1:" + ACCOUNT + ":capacity-reservation/cr-00000000000000001"}))
.statusCode(200).body("Failed[0].ErrorCode", equalTo("ResourceGroupsValidationException"));
} finally {
call(key, "/delete-group", Map.of("Group", name)).statusCode(200);
}
}
private static ValidatableResponse call(String key, String path, Object body) {
return given().header("Authorization", auth(key, "resource-groups"))
.contentType("application/json").body(body).post(path).then();
}
}
@@ -0,0 +1,119 @@
package io.github.hectorvent.floci.services.resourcegroups;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class ResourceGroupsIntegrationTest {
private static final String ACCOUNT = "111122223333";
private static final String REGION = "eu-west-1";
@Inject
ServiceRegistry registry;
@Test
void standardServiceRegistrationIncludesResourceGroups() {
assertTrue(registry.getEnabledServices().contains("resource-groups"));
}
private static String auth(String service, String account) {
return "AWS4-HMAC-SHA256 Credential=" + account + "/20261008/" + REGION + "/" + service + "/aws4_request";
}
private static ValidatableResponse call(String path, Object body) {
return given().header("Authorization", auth("resource-groups", ACCOUNT))
.contentType("application/json").body(body).post(path).then();
}
@Test
void publicCapacityPoolLifecycleUsesRealEc2Records() {
String name = "pool-" + UUID.randomUUID();
String reservation = given().header("Authorization", auth("ec2", ACCOUNT))
.formParam("Action", "CreateCapacityReservation").formParam("InstanceType", "t3.micro")
.formParam("InstancePlatform", "Linux/UNIX").formParam("AvailabilityZone", REGION + "a")
.formParam("InstanceCount", 1).post("/").then().statusCode(200)
.extract().xmlPath().getString("CreateCapacityReservationResponse.capacityReservation.capacityReservationArn");
String id = reservation.substring(reservation.lastIndexOf('/') + 1);
try {
String arn = call("/groups", "{\"Name\":\"" + name + "\",\"Configuration\":"
+ ResourceGroupsServiceTest.CONFIGURATION + "}").statusCode(200)
.body("GroupConfiguration.Status", equalTo("UPDATE_COMPLETE"))
.extract().path("Group.GroupArn");
try {
call("/get-group", Map.of("GroupName", name)).statusCode(200).body("Group.GroupArn", equalTo(arn));
call("/group-resources", Map.of("Group", arn, "ResourceArns", new String[]{reservation}))
.statusCode(200).body("Succeeded", contains(reservation)).body("Failed", empty())
.body("Pending", empty());
call("/list-group-resources", Map.of("Group", arn)).statusCode(200)
.body("ResourceIdentifiers[0].ResourceArn", equalTo(reservation))
.body("Resources[0].Identifier.ResourceType", equalTo(ResourceGroupsService.RESOURCE_TYPE));
given().header("Authorization", auth("resource-groups", "444455556666"))
.contentType("application/json").body(Map.of("GroupName", name))
.post("/get-group").then().statusCode(404).body("__type", equalTo("NotFoundException"));
} finally {
call("/delete-group", Map.of("GroupName", name)).statusCode(200).body("Group.GroupArn", equalTo(arn));
}
call("/get-group", Map.of("GroupName", name)).statusCode(404);
given().header("Authorization", auth("ec2", ACCOUNT))
.formParam("Action", "DescribeCapacityReservations").formParam("CapacityReservationId.1", id)
.post("/").then().statusCode(200)
.body("DescribeCapacityReservationsResponse.capacityReservationSet.item.state", equalTo("active"));
} finally {
given().header("Authorization", auth("ec2", ACCOUNT))
.formParam("Action", "CancelCapacityReservation").formParam("CapacityReservationId", id)
.post("/").then().statusCode(200);
}
}
@Test
void standardRestErrorsRefuseUnsupportedAndMalformedRequests() {
call("/groups", Map.of("Name", "unsupported", "ResourceQuery", Map.of())).statusCode(400)
.body("__type", equalTo("BadRequestException"));
call("/groups", "[]").statusCode(400);
call("/groups", "{").statusCode(400);
call("/get-group", Map.of("GroupName", "missing-" + UUID.randomUUID())).statusCode(404);
}
@ParameterizedTest
@ValueSource(strings = {"groups", "get-group", "delete-group", "group-resources", "list-group-resources"})
void s3BucketPostsKeepTheirOwnRoutes(String bucket) {
String authorization = auth("s3", ACCOUNT);
given().header("Authorization", authorization).contentType("application/xml")
.body("<CreateBucketConfiguration><LocationConstraint>" + REGION
+ "</LocationConstraint></CreateBucketConfiguration>")
.put("/" + bucket).then().statusCode(200);
try {
given().header("Authorization", authorization).body("value").put("/" + bucket + "/key")
.then().statusCode(200);
given().header("Authorization", authorization).contentType("application/xml")
.body("<Delete><Object><Key>key</Key></Object></Delete>").post("/" + bucket + "?delete")
.then().statusCode(200).body("DeleteResult.Deleted.Key", equalTo("key"));
given().header("Authorization", authorization).get("/" + bucket + "/key")
.then().statusCode(404);
} finally {
given().header("Authorization", authorization).delete("/" + bucket + "/key");
given().header("Authorization", authorization).delete("/" + bucket).then().statusCode(204);
}
}
@Test
void querySignedResourceGroupsRequestsReachTheSameController() {
given().queryParam("X-Amz-Credential", ACCOUNT + "/20261020/" + REGION + "/resource-groups/aws4_request")
.contentType("application/json").body(Map.of("Group", "missing-" + UUID.randomUUID()))
.post("/get-group").then().statusCode(404).body("__type", equalTo("NotFoundException"));
given().contentType("application/json").body("{}").post("/_rg/groups").then().statusCode(400)
.body(containsString("<Code>InvalidBucketName</Code>"));
}
}
@@ -0,0 +1,355 @@
package io.github.hectorvent.floci.services.resourcegroups;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.CapacityReservation;
import io.github.hectorvent.floci.services.resourcegroups.model.ResourceGroup;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class ResourceGroupsServiceTest {
static final String ACCOUNT = "111122223333";
static final String REGION = "eu-west-1";
static final String CONFIGURATION = """
[{"Type":"AWS::EC2::CapacityReservationPool"},
{"Type":"AWS::ResourceGroups::Generic","Parameters":[
{"Name":"allowed-resource-types","Values":["AWS::EC2::CapacityReservation"]}]}]
""";
private final ObjectMapper mapper = new ObjectMapper();
private final Map<String, CapacityReservation> reservations = new HashMap<>();
private ResourceGroupsService service;
private AccountAwareStorageBackend<ResourceGroup> groups;
private Ec2Service ec2;
private Clock clock;
@BeforeEach
void setUp() {
ec2 = mock(Ec2Service.class);
clock = mock(Clock.class);
when(clock.millis()).thenReturn(1000L);
when(ec2.describeCapacityReservations(anyString(), anyList(), anyMap())).thenAnswer(invocation -> {
List<String> ids = invocation.getArgument(1);
CapacityReservation reservation = reservations.get(ids.getFirst());
if (reservation == null) {
throw new AwsException("InvalidCapacityReservationId.NotFound", "missing", 400);
}
return List.of(reservation);
});
groups = AccountAwareStorageBackend.inMemory(ACCOUNT);
service = new ResourceGroupsService(groups, ec2, clock);
}
private JsonNode json(Object value) {
return mapper.valueToTree(value);
}
private JsonNode createRequest(String name) throws Exception {
return mapper.readTree("{\"Name\":\"" + name + "\",\"Configuration\":" + CONFIGURATION
+ ",\"Description\":\"capacity pool\",\"Tags\":{\"purpose\":\"test\"}}");
}
private ResourceGroup create(String name) throws Exception {
return service.create(REGION, ACCOUNT, createRequest(name));
}
private String reservation(int number) {
String id = "cr-" + String.format("%017x", number);
CapacityReservation reservation = new CapacityReservation();
reservation.setCapacityReservationId(id);
reservation.setCapacityReservationArn(
AwsArnUtils.Arn.of("ec2", REGION, ACCOUNT, "capacity-reservation/" + id).toString());
reservation.setOwnerId(ACCOUNT);
reservation.setState("active");
reservations.put(id, reservation);
return reservation.getCapacityReservationArn();
}
private Map<String, Object> add(String group, String... arns) {
return service.add(REGION, ACCOUNT, json(Map.of("Group", group, "ResourceArns", List.of(arns))));
}
private Map<String, Object> list(String group) {
return service.list(REGION, ACCOUNT, json(Map.of("Group", group)));
}
@Test
void storesConfigurationTagsAndDeprecatedNameSelector() throws Exception {
ResourceGroup group = create("pool");
assertEquals("arn:aws:resource-groups:eu-west-1:111122223333:group/pool", group.arn());
assertEquals("capacity pool", group.description());
assertEquals(Map.of("purpose", "test"), group.tags());
assertEquals(2, group.configuration().size());
assertEquals(group, service.get(REGION, ACCOUNT, json(Map.of("GroupName", "pool"))));
assertEquals(group, mapper.readValue(mapper.writeValueAsBytes(group), ResourceGroup.class));
assertThrows(AwsException.class, () -> create("pool"));
}
@Test
void realMembershipIsIdempotentAndDeleteLeavesReservations() throws Exception {
ResourceGroup group = create("pool");
String arn = reservation(1);
Map<String, Object> result = add(group.arn(), arn, arn);
assertEquals(List.of(arn), result.get("Succeeded"));
assertEquals(List.of(), result.get("Failed"));
assertEquals(List.of(), result.get("Pending"));
assertEquals(result, add("pool", arn));
Map<String, String> identifier = Map.of("ResourceArn", arn, "ResourceType", ResourceGroupsService.RESOURCE_TYPE);
assertEquals(List.of(identifier), list("pool").get("ResourceIdentifiers"));
assertEquals(List.of(Map.of("Identifier", identifier)), list("pool").get("Resources"));
service.delete(REGION, ACCOUNT, json(Map.of("GroupName", "pool")));
assertEquals("NotFoundException", assertThrows(AwsException.class,
() -> list("pool")).getErrorCode());
assertEquals(1, reservations.size());
create("pool");
assertEquals(List.of(), list("pool").get("ResourceIdentifiers"));
}
@ParameterizedTest
@ValueSource(strings = {"us-gov-west-1", "cn-north-1", "us-iso-east-1", "eusc-de-east-1"})
void derivesPartitionFromActualRegion(String region) throws Exception {
ResourceGroup group = service.create(region, ACCOUNT, createRequest("pool"));
assertEquals(AwsArnUtils.Arn.of("resource-groups", region, ACCOUNT, "group/pool").toString(), group.arn());
assertEquals(group, service.get(region, ACCOUNT, json(Map.of("Group", "pool"))));
if (!region.startsWith("eusc-")) {
assertEquals(group, service.get(region, ACCOUNT, json(Map.of("Group", group.arn()))));
}
}
@Test
void accountRegionAndFullArnSelectorsAreIsolated() throws Exception {
ResourceGroup group = create("pool");
assertThrows(AwsException.class, () -> service.get(REGION, "444455556666", json(Map.of("Group", "pool"))));
assertThrows(AwsException.class, () -> service.get("us-east-1", ACCOUNT, json(Map.of("Group", "pool"))));
assertThrows(AwsException.class,
() -> service.get(REGION, "444455556666", json(Map.of("Group", group.arn()))));
assertThrows(AwsException.class,
() -> service.get("us-east-1", ACCOUNT, json(Map.of("Group", group.arn()))));
ResourceGroup other = service.create(REGION, "444455556666", createRequest("pool"));
assertNotEquals(group.arn(), other.arn());
}
@Test
void missingForeignAndInactiveReservationsReturnFailedWithoutMembership() throws Exception {
create("pool");
String active = reservation(1);
String cancelled = reservation(2);
reservations.get("cr-00000000000000002").setState("cancelled");
String absent = active.replace("00000000000000001", "00000000000000003");
String foreign = active.replace(ACCOUNT, "444455556666");
Map<String, Object> result = add("pool", active, cancelled, absent, foreign);
assertEquals(List.of(active), result.get("Succeeded"));
List<?> failed = (List<?>) result.get("Failed");
assertEquals(3, failed.size());
assertTrue(failed.stream().allMatch(item -> ((Map<?, ?>) item).get("ErrorCode")
.equals("ResourceGroupsValidationException")));
assertEquals(1, ((List<?>) list("pool").get("ResourceIdentifiers")).size());
}
@ParameterizedTest
@CsvSource({
"arn:aws:ec2:us-east-1:111122223333:capacity-reservation/cr-00000000000000001,ValidationException",
"arn:aws:ec2:eu-west-1:111122223333:instance/i-00000000000000001,ResourceArnValidationException",
"arn:aws:lambda:eu-west-1:111122223333:function:missing,ResourceArnValidationException",
"arn:aws:ec2:eu-west-1:111122223333:capacity-reservation/cr-invalid,ResourceGroupsValidationException"
})
void unsupportedReservationIdentityUsesTheAwsPerResourceFailure(String arn, String code) throws Exception {
create("pool");
Map<String, Object> result = add("pool", arn);
List<?> failed = (List<?>) result.get("Failed");
assertEquals(1, failed.size());
assertEquals(code, ((Map<?, ?>) failed.getFirst()).get("ErrorCode"));
assertEquals(List.of(), result.get("Succeeded"));
assertEquals(List.of(), list("pool").get("ResourceIdentifiers"));
}
@Test
void unexpectedLookupOrForeignRecordedOwnerDoesNotCommitEarlierSuccess() throws Exception {
create("pool");
String first = reservation(1);
String second = reservation(2);
reservations.get("cr-00000000000000002").setOwnerId("444455556666");
assertThrows(AwsException.class, () -> add("pool", first, second));
assertEquals(List.of(), list("pool").get("ResourceIdentifiers"));
when(ec2.describeCapacityReservations(eq(REGION), eq(List.of("cr-00000000000000002")), anyMap()))
.thenThrow(new AwsException("ServiceUnavailable", "not ready", 503));
assertEquals(503, assertThrows(AwsException.class, () -> add("pool", first, second)).getHttpStatus());
assertEquals(List.of(), list("pool").get("ResourceIdentifiers"));
}
@ParameterizedTest
@ValueSource(strings = {
"{}", "[]", "{\"Name\":\"pool\"}", "{\"Name\":\"pool\",\"Configuration\":[]}",
"{\"Name\":\"pool\",\"Configuration\":[{\"Type\":\"AWS::EC2::HostManagement\"}]}",
"{\"Name\":\"pool\",\"ResourceQuery\":{}}"
})
void unsupportedOrMissingConfigurationFails(String body) throws Exception {
assertThrows(AwsException.class, () -> service.create(REGION, ACCOUNT, mapper.readTree(body)));
}
@ParameterizedTest
@ValueSource(strings = {"AWSreserved", "aWsreserved", "bad/name", "bad name", ""})
void invalidNamesRefuse(String name) throws Exception {
assertThrows(AwsException.class, () -> create(name));
}
@Test
void publicSdkNameAndDescriptionBoundsArePreserved() throws Exception {
JsonNode request = mapper.readTree("{\"Name\":\"" + "p".repeat(300) + "\",\"Description\":\""
+ "a".repeat(1024) + "\",\"Configuration\":" + CONFIGURATION + "}");
assertEquals(300, service.create(REGION, ACCOUNT, request).name().length());
assertThrows(AwsException.class, () -> create("p".repeat(301)));
assertThrows(AwsException.class, () -> service.create(REGION, ACCOUNT,
mapper.readTree(request.toString().replace("a".repeat(1024), "a".repeat(1025)))));
assertThrows(AwsException.class, () -> service.create(REGION, ACCOUNT,
mapper.readTree(request.toString().replace("a".repeat(1024), "bad/description"))));
}
@Test
void malformedConfigurationParametersAndMixedQueryRefuse() throws Exception {
String valid = mapper.writeValueAsString(createRequest("pool"));
for (String changed : List.of(
valid.replace(ResourceGroupsService.RESOURCE_TYPE, "AWS::EC2::Instance"),
valid.replace("allowed-resource-types", "unrecognized"),
valid.replace("AWS::EC2::CapacityReservationPool", "AWS::ResourceGroups::Generic"),
valid.replace("\"Name\":\"pool\"", "\"Name\":\"pool\",\"ResourceQuery\":{}"))) {
assertThrows(AwsException.class, () -> service.create(REGION, ACCOUNT, mapper.readTree(changed)));
}
}
@Test
void invalidMembershipRequestsFailBeforeAnyChange() throws Exception {
create("pool");
String valid = reservation(1);
assertThrows(AwsException.class, () -> add("pool"));
assertThrows(AwsException.class, () -> add("pool", valid, "not-an-arn"));
assertThrows(AwsException.class, () -> add("missing", valid));
assertThrows(AwsException.class, () -> service.get(REGION, ACCOUNT,
json(Map.of("Group", "pool", "GroupName", "pool"))));
assertThrows(AwsException.class, () -> service.list(REGION, ACCOUNT,
json(Map.of("Group", "pool", "MaxResults", true))));
assertEquals(List.of(), list("pool").get("ResourceIdentifiers"));
verifyNoInteractions(ec2);
}
@Test
void ignoresUnknownFieldsAndChecksModeledTagsAndMetadata() throws Exception {
JsonNode request = createRequest("pool");
((ObjectNode) request).put("Group", "ignored");
((ObjectNode) request).set("Tags", json(Map.of("équipe /", "a:b@c")));
ResourceGroup group = service.create(REGION, ACCOUNT, request);
assertEquals(Map.of("équipe /", "a:b@c"), group.tags());
assertEquals("pool", group.name());
for (String field : List.of("Owner", "DisplayName", "Criticality")) {
JsonNode modeled = createRequest("metadata-" + field);
((ObjectNode) modeled).set(field,
json(field.equals("Criticality") ? 7 : "valid / +"));
assertEquals("Unsupported parameter for this operation",
assertThrows(AwsException.class, () -> service.create(REGION, ACCOUNT, modeled)).getMessage());
}
for (Map<String, String> tags : List.of(Map.of("bad$", "value"), Map.of("key", "bad$"))) {
JsonNode invalid = createRequest("bad-tags");
((ObjectNode) invalid).set("Tags", json(tags));
assertThrows(AwsException.class, () -> service.create(REGION, ACCOUNT, invalid));
}
for (int value : List.of(0, 11)) {
JsonNode invalid = createRequest("bad-criticality");
((ObjectNode) invalid).put("Criticality", value);
assertThrows(AwsException.class, () -> service.create(REGION, ACCOUNT, invalid));
}
assertEquals("pool", service.get(REGION, ACCOUNT,
json(Map.of("Group", "pool", "Unknown", "ignored", "DisplayName", Map.of()))).name());
}
@Test
void paginationSurvivesRemovalOfTheLastItemOnThePreviousPage() throws Exception {
ResourceGroup group = create("pool");
String first = reservation(1);
String second = reservation(2);
String third = reservation(3);
add("pool", first, second, third);
String token = (String) service.list(REGION, ACCOUNT,
json(Map.of("Group", "pool", "MaxResults", 2))).get("NextToken");
groups.putForAccount(ACCOUNT, REGION + "::pool", group.withMembers(List.of(first, third)));
Map<String, Object> page = service.list(REGION, ACCOUNT,
json(Map.of("Group", "pool", "NextToken", token)));
assertEquals(List.of(Map.of("ResourceArn", third, "ResourceType", ResourceGroupsService.RESOURCE_TYPE)),
page.get("ResourceIdentifiers"));
assertFalse(page.containsKey("NextToken"));
}
@Test
void paginationKeepsSnapshotScopeReplayAndGroupGeneration() throws Exception {
create("pool");
create("other");
String first = reservation(1);
String second = reservation(2);
add("pool", first, second);
Map<String, Object> firstPage = service.list(REGION, ACCOUNT, json(Map.of("Group", "pool", "MaxResults", 1)));
String token = (String) firstPage.get("NextToken");
assertTrue(token.matches("[a-zA-Z0-9+/]*={0,2}"));
assertDoesNotThrow(() -> Base64.getDecoder().decode(token));
JsonNode continued = json(Map.of("Group", "pool", "NextToken", token));
add("pool", reservation(3));
Map<String, Object> page = service.list(REGION, ACCOUNT, continued);
assertEquals(List.of(Map.of("ResourceArn", second, "ResourceType", ResourceGroupsService.RESOURCE_TYPE)),
page.get("ResourceIdentifiers"));
assertEquals(page, service.list(REGION, ACCOUNT, continued));
assertThrows(AwsException.class, () -> service.list(REGION, ACCOUNT,
json(Map.of("Group", "other", "NextToken", token))));
assertThrows(AwsException.class, () -> service.list(REGION, ACCOUNT,
json(Map.of("Group", "pool", "NextToken", token, "Filters",
List.of(Map.of("Name", "resource-type", "Values", List.of(ResourceGroupsService.RESOURCE_TYPE)))))));
service.delete(REGION, ACCOUNT, json(Map.of("Group", "pool")));
create("pool");
assertThrows(AwsException.class, () -> service.list(REGION, ACCOUNT, continued));
}
@Test
void paginationHasBoundedExpiryAndAllowsFreshTraversal() throws Exception {
create("pool");
add("pool", reservation(1), reservation(2));
JsonNode request = json(Map.of("Group", "pool", "MaxResults", 1));
List<String> tokens = new ArrayList<>();
for (int index = 0; index <= ResourceGroupsService.MAX_PAGES; index++) {
tokens.add((String) service.list(REGION, ACCOUNT, request).get("NextToken"));
}
assertThrows(AwsException.class, () -> service.list(REGION, ACCOUNT,
json(Map.of("Group", "pool", "NextToken", tokens.getFirst()))));
when(clock.millis()).thenReturn(ResourceGroupsService.PAGE_IDLE_MILLIS + 1001);
assertThrows(AwsException.class, () -> service.list(REGION, ACCOUNT,
json(Map.of("Group", "pool", "NextToken", tokens.getLast()))));
assertNotNull(service.list(REGION, ACCOUNT, request).get("NextToken"));
}
@Test
void clearDropsGroupsAndTokens() throws Exception {
create("pool");
add("pool", reservation(1), reservation(2));
String token = (String) service.list(REGION, ACCOUNT,
json(Map.of("Group", "pool", "MaxResults", 1))).get("NextToken");
service.clear();
assertThrows(AwsException.class, () -> list("pool"));
create("pool");
assertThrows(AwsException.class, () -> service.list(REGION, ACCOUNT,
json(Map.of("Group", "pool", "NextToken", token))));
}
}