diff --git a/src/main/java/io/floci/aws/services/appconfig/AppConfigController.java b/src/main/java/io/floci/aws/services/appconfig/AppConfigController.java index 4c959ecd35..ca490a5277 100644 --- a/src/main/java/io/floci/aws/services/appconfig/AppConfigController.java +++ b/src/main/java/io/floci/aws/services/appconfig/AppConfigController.java @@ -3,6 +3,7 @@ package io.floci.aws.services.appconfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.services.appconfig.AppConfigDataService.LegacyConfiguration; @@ -79,17 +80,9 @@ public class AppConfigController { public Response listApplications(@QueryParam("max_results") String maxResults, @QueryParam("next_token") String nextToken, @Context UriInfo uriInfo) { - String token = nextToken == null && uriInfo.getQueryParameters().containsKey("next_token") - ? "" : nextToken; PaginatedResult page = service.listApplicationsPage( - Pagination.parseMaxResults(maxResults, "BadRequestException"), token); - ObjectNode root = objectMapper.createObjectNode(); - ArrayNode items = root.putArray("Items"); - page.items().forEach(items::addPOJO); - if (page.nextToken() != null) { - root.put("NextToken", page.nextToken()); - } - return Response.ok(root).build(); + Pagination.parseMaxResults(maxResults, "BadRequestException"), rawNextToken(nextToken, uriInfo)); + return listResponse(page.items(), page.nextToken()); } @DELETE @@ -125,12 +118,13 @@ public class AppConfigController { @GET @Path("/applications/{appId}/environments") - public Response listEnvironments(@PathParam("appId") String appId) { - List envs = service.listEnvironments(appId); - ObjectNode root = objectMapper.createObjectNode(); - ArrayNode items = root.putArray("Items"); - envs.forEach(items::addPOJO); - return Response.ok(root).build(); + public Response listEnvironments(@PathParam("appId") String appId, + @QueryParam("max_results") String maxResults, + @QueryParam("next_token") String nextToken, + @Context UriInfo uriInfo) { + PaginatedResult page = service.listEnvironmentsPage(appId, + parseListMaxResults(maxResults, uriInfo), rawNextToken(nextToken, uriInfo)); + return listResponse(page.items(), page.nextToken()); } // ──────────────────────────── Configuration Profile ──────────────────────────── @@ -152,12 +146,13 @@ public class AppConfigController { @GET @Path("/applications/{appId}/configurationprofiles") - public Response listConfigurationProfiles(@PathParam("appId") String appId) { - List profiles = service.listConfigurationProfiles(appId); - ObjectNode root = objectMapper.createObjectNode(); - ArrayNode items = root.putArray("Items"); - profiles.forEach(items::addPOJO); - return Response.ok(root).build(); + public Response listConfigurationProfiles(@PathParam("appId") String appId, + @QueryParam("max_results") String maxResults, + @QueryParam("next_token") String nextToken, + @Context UriInfo uriInfo) { + PaginatedResult page = service.listConfigurationProfilesPage(appId, + parseListMaxResults(maxResults, uriInfo), rawNextToken(nextToken, uriInfo)); + return listResponse(page.items(), page.nextToken()); } @DELETE @@ -172,12 +167,14 @@ public class AppConfigController { @GET @Path("/applications/{appId}/configurationprofiles/{profileId}/hostedconfigurationversions") public Response listHostedConfigurationVersions(@PathParam("appId") String appId, - @PathParam("profileId") String profileId) { - List items = service.listHostedConfigurationVersions(appId, profileId); - ObjectNode root = objectMapper.createObjectNode(); - ArrayNode arr = root.putArray("Items"); - items.forEach(arr::addPOJO); - return Response.ok(root).build(); + @PathParam("profileId") String profileId, + @QueryParam("max_results") String maxResults, + @QueryParam("next_token") String nextToken, + @Context UriInfo uriInfo) { + PaginatedResult page = service.listHostedConfigurationVersionsPage( + appId, profileId, parseListMaxResults(maxResults, uriInfo), + rawNextToken(nextToken, uriInfo)); + return listResponse(page.items(), page.nextToken()); } @POST @@ -239,12 +236,12 @@ public class AppConfigController { @GET @Path("/deploymentstrategies") - public Response listDeploymentStrategies() { - List items = service.listDeploymentStrategies(); - ObjectNode root = objectMapper.createObjectNode(); - ArrayNode arr = root.putArray("Items"); - items.forEach(arr::addPOJO); - return Response.ok(root).build(); + public Response listDeploymentStrategies(@QueryParam("max_results") String maxResults, + @QueryParam("next_token") String nextToken, + @Context UriInfo uriInfo) { + PaginatedResult page = service.listDeploymentStrategiesPage( + parseListMaxResults(maxResults, uriInfo), rawNextToken(nextToken, uriInfo)); + return listResponse(page.items(), page.nextToken()); } // AWS's own API model spells this path "deployementstrategies" (extra "e") - every other @@ -278,11 +275,15 @@ public class AppConfigController { @QueryParam("next_token") String nextToken) { AppConfigService.DeploymentPage page = service.listDeployments(appId, envId, Pagination.parseMaxResults(maxResults, "BadRequestException"), nextToken); + return listResponse(page.items(), page.nextToken()); + } + + private Response listResponse(List items, String nextToken) { ObjectNode root = objectMapper.createObjectNode(); - ArrayNode items = root.putArray("Items"); - page.items().forEach(items::addPOJO); - if (page.nextToken() != null) { - root.put("NextToken", page.nextToken()); + ArrayNode itemArray = root.putArray("Items"); + items.forEach(itemArray::addPOJO); + if (nextToken != null) { + root.put("NextToken", nextToken); } return Response.ok(root).build(); } @@ -331,4 +332,17 @@ public class AppConfigController { .header("Configuration-Version", data.configurationVersion()) .build(); } + + private static String rawNextToken(String nextToken, UriInfo uriInfo) { + return nextToken == null && uriInfo.getQueryParameters().containsKey("next_token") + ? "" : nextToken; + } + + private static Integer parseListMaxResults(String maxResults, UriInfo uriInfo) { + if (uriInfo.getQueryParameters().containsKey("max_results") + && (maxResults == null || maxResults.isBlank())) { + throw new AwsException("BadRequestException", "max_results must be an integer.", 400); + } + return Pagination.parseMaxResults(maxResults, "BadRequestException"); + } } diff --git a/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java b/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java index 86fabad539..3e4694e3ea 100644 --- a/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java +++ b/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java @@ -30,10 +30,12 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; import java.util.regex.Pattern; @ApplicationScoped @@ -109,8 +111,7 @@ public class AppConfigService { public PaginatedResult listApplicationsPage(Integer maxResults, String nextToken) { String scope = "appconfig-applications:" + regions.getAccountId() + ":" + regions.getRegion(); - return Pagination.paginate(listApplications(), Application::getId, maxResults, nextToken, - 50, 50, 2048, "BadRequestException", scope, true); + return pageAppConfigList(listApplications(), Application::getId, maxResults, nextToken, scope); } /** The application whose ID is exactly {@code applicationId}; GetApplication also takes a name. */ @@ -231,6 +232,13 @@ public class AppConfigService { .toList(); } + public PaginatedResult listEnvironmentsPage(String applicationIdentifier, + Integer maxResults, String nextToken) { + String appId = resolveApplication(applicationIdentifier).getId(); + String scope = "appconfig-environments:" + regions.getAccountId() + ":" + regions.getRegion() + ":" + appId; + return pageAppConfigList(listEnvironments(appId), Environment::getId, maxResults, nextToken, scope); + } + /** The environment whose ID is exactly {@code environmentId}, in whichever application holds it. */ public Optional findEnvironment(String environmentId) { return environmentStore.get(environmentId); @@ -327,6 +335,14 @@ public class AppConfigService { .toList(); } + public PaginatedResult listConfigurationProfilesPage(String applicationIdentifier, + Integer maxResults, String nextToken) { + String appId = resolveApplication(applicationIdentifier).getId(); + String scope = "appconfig-profiles:" + regions.getAccountId() + ":" + regions.getRegion() + ":" + appId; + return pageAppConfigList(listConfigurationProfiles(appId), ConfigurationProfile::getId, + maxResults, nextToken, scope); + } + /** The configuration profile whose ID is exactly {@code profileId}, in whichever application holds it. */ public Optional findConfigurationProfile(String profileId) { return profileStore.get(profileId); @@ -447,6 +463,17 @@ public class AppConfigService { .toList(); } + public PaginatedResult listHostedConfigurationVersionsPage( + String applicationIdentifier, String profileIdentifier, Integer maxResults, String nextToken) { + String appId = resolveApplication(applicationIdentifier).getId(); + String profileId = resolveConfigurationProfile(appId, profileIdentifier).getId(); + String scope = "appconfig-hosted-versions:" + regions.getAccountId() + ":" + regions.getRegion() + + ":" + appId + ":" + profileId; + return pageAppConfigList(listHostedConfigurationVersions(appId, profileId), + version -> String.format(Locale.ROOT, "%010d", version.getVersionNumber()), + maxResults, nextToken, scope); + } + public synchronized void deleteHostedConfigurationVersion(String applicationIdentifier, String profileIdentifier, int versionNumber) { @@ -495,6 +522,19 @@ public class AppConfigService { return result; } + public PaginatedResult listDeploymentStrategiesPage(Integer maxResults, String nextToken) { + String scope = "appconfig-strategies:" + regions.getAccountId() + ":" + regions.getRegion(); + return pageAppConfigList(listDeploymentStrategies(), DeploymentStrategy::getId, + maxResults, nextToken, scope); + } + + private static PaginatedResult pageAppConfigList(List items, Function cursorOf, + Integer maxResults, String nextToken, + String scope) { + return Pagination.paginate(items, cursorOf, maxResults, nextToken, + 50, 50, 2048, "BadRequestException", scope, true); + } + /** * Sets the mutable settings of a stored deployment strategy, as a CloudFormation update of * {@code AWS::AppConfig::DeploymentStrategy} does; its name and {@code ReplicateTo} are diff --git a/src/test/java/io/floci/aws/services/appconfig/AppConfigListResourcesPaginationTest.java b/src/test/java/io/floci/aws/services/appconfig/AppConfigListResourcesPaginationTest.java new file mode 100644 index 0000000000..c3b6de05ab --- /dev/null +++ b/src/test/java/io/floci/aws/services/appconfig/AppConfigListResourcesPaginationTest.java @@ -0,0 +1,355 @@ +package io.floci.aws.services.appconfig; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.IntStream; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class AppConfigListResourcesPaginationTest { + private static final String SCOPE = + "AWS4-HMAC-SHA256 Credential=123456789012/20261109/us-east-1/appconfig/aws4_request"; + private static final String OTHER_ACCOUNT = + "AWS4-HMAC-SHA256 Credential=210987654321/20261109/us-east-1/appconfig/aws4_request"; + private static final String OTHER_REGION = + "AWS4-HMAC-SHA256 Credential=123456789012/20261109/us-west-2/appconfig/aws4_request"; + private static final String DEFAULT_PAGE_ACCOUNT = + "AWS4-HMAC-SHA256 Credential=321098765432/20261109/us-east-1/appconfig/aws4_request"; + + @Test + void listEnvironmentsPaginatesAndScopesTokensToTheApplication() { + String app = createApplication(); + String otherApp = createApplication(); + List environments = new ArrayList<>(); + try { + for (int i = 0; i < 2; i++) { + environments.add(createEnvironment(app, "environment-" + i)); + } + String path = "/applications/" + app + "/environments"; + String token = assertTwoPages(path, "Id", environments); + assertInvalidInputs(path); + assertInvalidToken("/applications/" + otherApp + "/environments", SCOPE, token); + } finally { + for (String environment : environments) { + deleteEnvironment(app, environment); + } + deleteApplication(otherApp); + deleteApplication(app); + } + } + + @Test + void listEnvironmentsDefaultsToFiftyItems() { + String app = createApplication(); + List environments = new ArrayList<>(); + try { + for (int i = 0; i < 51; i++) { + environments.add(createEnvironment(app, "default-environment-" + i)); + } + assertDefaultPageOfFifty("/applications/" + app + "/environments", SCOPE, + Set.copyOf(environments)); + } finally { + for (String environment : environments) { + deleteEnvironment(app, environment); + } + deleteApplication(app); + } + } + + @Test + void listConfigurationProfilesPaginatesAndScopesTokensToTheApplicationAndOperation() { + String app = createApplication(); + String otherApp = createApplication(); + List profiles = new ArrayList<>(); + try { + for (int i = 0; i < 2; i++) { + profiles.add(createProfile(app, "profile-" + i)); + } + String path = "/applications/" + app + "/configurationprofiles"; + String token = assertTwoPages(path, "Id", profiles); + assertInvalidInputs(path); + assertInvalidToken("/applications/" + otherApp + "/configurationprofiles", SCOPE, token); + assertInvalidToken("/applications/" + app + "/environments", SCOPE, token); + } finally { + for (String profile : profiles) { + deleteProfile(app, profile); + } + deleteApplication(otherApp); + deleteApplication(app); + } + } + + @Test + void listConfigurationProfilesDefaultsToFiftyItems() { + String app = createApplication(); + List profiles = new ArrayList<>(); + try { + for (int i = 0; i < 51; i++) { + profiles.add(createProfile(app, "default-profile-" + i)); + } + assertDefaultPageOfFifty("/applications/" + app + "/configurationprofiles", SCOPE, + Set.copyOf(profiles)); + } finally { + for (String profile : profiles) { + deleteProfile(app, profile); + } + deleteApplication(app); + } + } + + @Test + void listHostedVersionsPaginatesInNumericOrderAndScopesTokensToTheProfile() { + String app = createApplication(); + String profile = createProfile(app, "hosted"); + String otherProfile = createProfile(app, "other"); + try { + String path = "/applications/" + app + "/configurationprofiles/" + profile + + "/hostedconfigurationversions"; + createHostedVersions(path, 10); + PageWalk versions = walkPages(path, "VersionNumber", Integer.class, 2, 10); + assertEquals(IntStream.rangeClosed(1, 10).boxed().toList(), versions.items()); + assertEquals(5, versions.pageCount()); + assertInvalidInputs(path); + assertInvalidToken("/applications/" + app + "/configurationprofiles/" + otherProfile + + "/hostedconfigurationversions", SCOPE, versions.firstToken()); + + createHostedVersions(path, 41); + Response defaultPage = given().header("Authorization", SCOPE) + .when().get(path) + .then().statusCode(200).extract().response(); + assertEquals(IntStream.rangeClosed(1, 50).boxed().toList(), + defaultPage.jsonPath().getList("Items.VersionNumber", Integer.class)); + String defaultToken = defaultPage.jsonPath().getString("NextToken"); + assertNotNull(defaultToken); + Response lastPage = given().header("Authorization", SCOPE) + .queryParam("next_token", defaultToken) + .when().get(path) + .then().statusCode(200).extract().response(); + assertEquals(List.of(51), lastPage.jsonPath().getList("Items.VersionNumber", Integer.class)); + assertNull(lastPage.jsonPath().getString("NextToken")); + } finally { + deleteProfile(app, otherProfile); + deleteProfile(app, profile); + deleteApplication(app); + } + } + + @Test + void listDeploymentStrategiesPaginatesAndScopesTokensToAccountAndRegion() { + String path = "/deploymentstrategies"; + PageWalk strategies = walkPages(path, "Id", String.class, 2, 100); + assertTrue(strategies.items().containsAll(List.of("AppConfig.AllAtOnce", "AppConfig.Linear50PercentEvery30Seconds", + "AppConfig.Canary10Percent20Minutes"))); + assertEquals(strategies.items().size(), new HashSet<>(strategies.items()).size()); + assertInvalidInputs(path); + assertInvalidToken(path, OTHER_ACCOUNT, strategies.firstToken()); + assertInvalidToken(path, OTHER_REGION, strategies.firstToken()); + } + + @Test + void listDeploymentStrategiesDefaultsToFiftyItemsIncludingBuiltins() { + List strategies = new ArrayList<>(); + try { + for (int i = 0; i < 48; i++) { + strategies.add(given().header("Authorization", DEFAULT_PAGE_ACCOUNT) + .contentType(ContentType.JSON) + .body("{\"Name\":\"default-strategy-" + i + + "\",\"DeploymentDurationInMinutes\":0,\"GrowthFactor\":100," + + "\"FinalBakeTimeInMinutes\":0}") + .when().post("/deploymentstrategies") + .then().statusCode(201).extract().path("Id")); + } + Set expected = new HashSet<>(strategies); + expected.addAll(List.of("AppConfig.AllAtOnce", "AppConfig.Linear50PercentEvery30Seconds", + "AppConfig.Canary10Percent20Minutes")); + assertDefaultPageOfFifty("/deploymentstrategies", DEFAULT_PAGE_ACCOUNT, expected); + } finally { + for (String strategy : strategies) { + given().header("Authorization", DEFAULT_PAGE_ACCOUNT) + .when().delete("/deployementstrategies/" + strategy) + .then().statusCode(204); + } + } + } + + private static void assertDefaultPageOfFifty(String path, String authorization, Set expected) { + assertEquals(51, expected.size()); + Response first = given().header("Authorization", authorization) + .when().get(path) + .then().statusCode(200).extract().response(); + List firstIds = first.jsonPath().getList("Items.Id", String.class); + assertEquals(50, firstIds.size()); + String nextToken = first.jsonPath().getString("NextToken"); + assertNotNull(nextToken); + + Response second = given().header("Authorization", authorization) + .queryParam("next_token", nextToken) + .when().get(path) + .then().statusCode(200).extract().response(); + List secondIds = second.jsonPath().getList("Items.Id", String.class); + assertEquals(1, secondIds.size()); + assertNull(second.jsonPath().getString("NextToken")); + + List allIds = new ArrayList<>(firstIds); + allIds.addAll(secondIds); + assertEquals(51, new HashSet<>(allIds).size()); + assertEquals(expected, Set.copyOf(allIds)); + } + + private static PageWalk walkPages(String path, String field, Class type, + int pageSize, int maxItems) { + List items = new ArrayList<>(); + Set seenTokens = new HashSet<>(); + String token = null; + String firstToken = null; + int pageCount = 0; + do { + RequestSpecification request = given().header("Authorization", SCOPE) + .queryParam("max_results", pageSize); + if (token != null) { + request.queryParam("next_token", token); + } + Response page = request.when().get(path) + .then().statusCode(200).extract().response(); + List pageItems = page.jsonPath().getList("Items." + field, type); + assertTrue(pageItems.size() <= pageSize); + items.addAll(pageItems); + token = page.jsonPath().getString("NextToken"); + if (pageCount++ == 0) { + firstToken = token; + assertNotNull(firstToken); + } + if (token != null) { + assertTrue(seenTokens.add(token)); + } + } while (token != null && items.size() < maxItems); + assertNull(token); + return new PageWalk<>(items, firstToken, pageCount); + } + + private record PageWalk(List items, String firstToken, int pageCount) {} + + private static String assertTwoPages(String path, String idField, List expected) { + Response unpaged = given().header("Authorization", SCOPE) + .when().get(path) + .then().statusCode(200).extract().response(); + assertEquals(expected.size(), unpaged.jsonPath().getList("Items").size()); + assertNull(unpaged.jsonPath().getString("NextToken")); + + Response first = given().header("Authorization", SCOPE) + .queryParam("max_results", 1) + .when().get(path) + .then().statusCode(200).extract().response(); + String token = first.jsonPath().getString("NextToken"); + assertEquals(1, first.jsonPath().getList("Items").size()); + assertNotNull(token); + + Response second = given().header("Authorization", SCOPE) + .queryParam("max_results", 1) + .queryParam("next_token", token) + .when().get(path) + .then().statusCode(200).extract().response(); + assertEquals(1, second.jsonPath().getList("Items").size()); + assertNull(second.jsonPath().getString("NextToken")); + String firstId = first.jsonPath().getString("Items[0]." + idField); + String secondId = second.jsonPath().getString("Items[0]." + idField); + assertNotEquals(firstId, secondId); + assertEquals(Set.copyOf(expected), Set.of(firstId, secondId)); + return token; + } + + private static void assertInvalidInputs(String path) { + given().header("Authorization", SCOPE) + .when().get(path + "?max_results=") + .then().statusCode(400); + given().header("Authorization", SCOPE) + .when().get(path + "?max_results=%20") + .then().statusCode(400); + for (int maxResults : List.of(0, 51)) { + given().header("Authorization", SCOPE) + .queryParam("max_results", maxResults) + .when().get(path) + .then().statusCode(400); + } + for (String token : List.of("not-a-token", "x".repeat(2049))) { + assertInvalidToken(path, SCOPE, token); + } + given().header("Authorization", SCOPE) + .when().get(path + "?next_token=") + .then().statusCode(400); + } + + private static void assertInvalidToken(String path, String scope, String token) { + given().header("Authorization", scope) + .queryParam("next_token", token) + .when().get(path) + .then().statusCode(400); + } + + private static String createApplication() { + return given().header("Authorization", SCOPE) + .contentType(ContentType.JSON) + .body("{\"Name\":\"pagination-" + UUID.randomUUID() + "\"}") + .when().post("/applications") + .then().statusCode(201).extract().path("Id"); + } + + private static String createEnvironment(String app, String name) { + return given().header("Authorization", SCOPE) + .contentType(ContentType.JSON) + .body("{\"Name\":\"" + name + "\"}") + .when().post("/applications/" + app + "/environments") + .then().statusCode(201).extract().path("Id"); + } + + private static void deleteEnvironment(String app, String environment) { + given().header("Authorization", SCOPE) + .when().delete("/applications/" + app + "/environments/" + environment) + .then().statusCode(204); + } + + private static void createHostedVersions(String path, int count) { + for (int i = 0; i < count; i++) { + given().header("Authorization", SCOPE) + .contentType(ContentType.JSON) + .body("{}") + .when().post(path) + .then().statusCode(201); + } + } + + private static String createProfile(String app, String name) { + return given().header("Authorization", SCOPE) + .contentType(ContentType.JSON) + .body("{\"Name\":\"" + name + "\",\"LocationUri\":\"hosted\"}") + .when().post("/applications/" + app + "/configurationprofiles") + .then().statusCode(201).extract().path("Id"); + } + + private static void deleteProfile(String app, String profile) { + given().header("Authorization", SCOPE) + .when().delete("/applications/" + app + "/configurationprofiles/" + profile) + .then().statusCode(204); + } + + private static void deleteApplication(String app) { + given().header("Authorization", SCOPE) + .when().delete("/applications/" + app) + .then().statusCode(204); + } +}