diff --git a/docs/services/applicationautoscaling.md b/docs/services/applicationautoscaling.md index 09f765f97d..a1c26288f1 100644 --- a/docs/services/applicationautoscaling.md +++ b/docs/services/applicationautoscaling.md @@ -28,6 +28,15 @@ Auto Scaling groups over the Query protocol under the `autoscaling` signing name | `UntagResource` | Removes tags from a scalable target | +## Pagination + +`DescribeScalableTargets` accepts `MaxResults` from 1 to 50 and defaults to 50. +`DescribeScalingPolicies` accepts `MaxResults` from 1 to 10 and defaults to 10. +When more results remain, pass the returned `NextToken` with the same operation, +region, and filters to retrieve the next page. An invalid token returns +`InvalidNextTokenException`; an out-of-range page size returns `ValidationException`. +Tokens expire when the emulator restarts. + ## Identity A scalable target is keyed by the triple **(ServiceNamespace, ResourceId, @@ -136,8 +145,6 @@ arn:aws:iam:::role/aws-service-role/.application-autoscaling implemented. - `PredictiveScalingPolicyConfiguration` is accepted only insofar as `PolicyType` is validated; the configuration block is not stored. -- Pagination is not implemented — `DescribeScalableTargets` and `DescribeScalingPolicies` - return all matching results and never emit a `NextToken`. - **The evaluation range's exact width is an approximation.** Alarm evaluation follows CloudWatch's documented precedence: a wider "evaluation range" than `Period × EvaluationPeriods` is queried, and whenever enough *real* datapoints exist within diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingJsonHandler.java index 6eaafdb2ee..6f087597ef 100644 --- a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingJsonHandler.java @@ -5,6 +5,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsErrorResponse; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.services.applicationautoscaling.model.Alarm; import io.github.hectorvent.floci.services.applicationautoscaling.model.PredefinedMetricSpecification; import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalableTarget; @@ -86,15 +88,20 @@ public class ApplicationAutoScalingJsonHandler { } private Response handleDescribeScalableTargets(JsonNode request, String region) { - List found = service.describeScalableTargets( + PaginatedResult result = service.describeScalableTargets( text(request, "ServiceNamespace"), stringList(request.path("ResourceIds")), text(request, "ScalableDimension"), + optionalMaxResults(request), + text(request, "NextToken"), region); ObjectNode response = objectMapper.createObjectNode(); ArrayNode array = response.putArray("ScalableTargets"); - found.forEach(t -> array.add(scalableTargetJson(t))); + result.items().forEach(t -> array.add(scalableTargetJson(t))); + if (result.nextToken() != null) { + response.put("NextToken", result.nextToken()); + } return Response.ok(response).build(); } @@ -128,16 +135,21 @@ public class ApplicationAutoScalingJsonHandler { } private Response handleDescribeScalingPolicies(JsonNode request, String region) { - List found = service.describeScalingPolicies( + PaginatedResult result = service.describeScalingPolicies( text(request, "ServiceNamespace"), text(request, "ResourceId"), text(request, "ScalableDimension"), stringList(request.path("PolicyNames")), + optionalMaxResults(request), + text(request, "NextToken"), region); ObjectNode response = objectMapper.createObjectNode(); ArrayNode array = response.putArray("ScalingPolicies"); - found.forEach(p -> array.add(scalingPolicyJson(p))); + result.items().forEach(p -> array.add(scalingPolicyJson(p))); + if (result.nextToken() != null) { + response.put("NextToken", result.nextToken()); + } return Response.ok(response).build(); } @@ -369,4 +381,15 @@ public class ApplicationAutoScalingJsonHandler { JsonNode value = node.path(field); return value.isMissingNode() || value.isNull() ? null : value.asInt(); } + + private static Integer optionalMaxResults(JsonNode request) { + JsonNode value = request.get("MaxResults"); + if (value == null || value.isNull()) { + return null; + } + if (!value.isIntegralNumber() || !value.canConvertToInt()) { + throw new AwsException("ValidationException", "MaxResults must be an integer.", 400); + } + return value.intValue(); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java index 95671a2afd..9305d33efc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingService.java @@ -2,8 +2,11 @@ package io.github.hectorvent.floci.services.applicationautoscaling; import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.Pagination; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.ServicePrincipals; +import io.github.hectorvent.floci.core.common.SignedMarkers; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.applicationautoscaling.model.Alarm; @@ -45,6 +48,8 @@ import java.util.UUID; public class ApplicationAutoScalingService { private static final Logger LOG = Logger.getLogger(ApplicationAutoScalingService.class); + private static final int MAX_TARGET_PAGE_SIZE = 50; + private static final int MAX_POLICY_PAGE_SIZE = 10; static final Set SERVICE_NAMESPACES = Set.of( "ecs", "elasticmapreduce", "ec2", "appstream", "dynamodb", "rds", "sagemaker", @@ -85,6 +90,7 @@ public class ApplicationAutoScalingService { private final StorageBackend activities; private final RegionResolver regionResolver; private final CloudWatchMetricsService cloudWatchMetricsService; + private final SignedMarkers pageTokens = new SignedMarkers(); @Inject public ApplicationAutoScalingService(StorageFactory factory, @@ -186,6 +192,18 @@ public class ApplicationAutoScalingService { .toList(); } + PaginatedResult describeScalableTargets(String serviceNamespace, List resourceIds, + String scalableDimension, Integer maxResults, + String nextToken, String region) { + String cursor = decodeNextToken(nextToken, "DescribeScalableTargets"); + List matching = describeScalableTargets(serviceNamespace, resourceIds, + scalableDimension, region); + return signedPage(Pagination.paginate(matching, ApplicationAutoScalingService::scalableTargetCursor, + pageSize(maxResults, MAX_TARGET_PAGE_SIZE), cursor, + pageNamespace(resourceIds, "DescribeScalableTargets", region, serviceNamespace, scalableDimension), + token -> invalidNextToken("DescribeScalableTargets"))); + } + /** * Deregisters a scalable target and, per AWS semantics, deletes every scaling policy * attached to it along with the CloudWatch alarms those policies own. @@ -275,10 +293,23 @@ public class ApplicationAutoScalingService { .filter(p -> resourceId == null || resourceId.equals(p.getResourceId())) .filter(p -> scalableDimension == null || scalableDimension.equals(p.getScalableDimension())) .filter(p -> policyNames == null || policyNames.isEmpty() || policyNames.contains(p.getPolicyName())) - .sorted(Comparator.comparing(ScalingPolicy::getPolicyName)) + .sorted(Comparator.comparing(ApplicationAutoScalingService::scalingPolicyCursor)) .toList(); } + PaginatedResult describeScalingPolicies(String serviceNamespace, String resourceId, + String scalableDimension, List policyNames, + Integer maxResults, String nextToken, String region) { + String cursor = decodeNextToken(nextToken, "DescribeScalingPolicies"); + List matching = describeScalingPolicies(serviceNamespace, resourceId, + scalableDimension, policyNames, region); + return signedPage(Pagination.paginate(matching, ApplicationAutoScalingService::scalingPolicyCursor, + pageSize(maxResults, MAX_POLICY_PAGE_SIZE), cursor, + pageNamespace(policyNames, "DescribeScalingPolicies", region, serviceNamespace, + resourceId, scalableDimension), + token -> invalidNextToken("DescribeScalingPolicies"))); + } + public void deleteScalingPolicy(String policyName, String serviceNamespace, String resourceId, String scalableDimension, String region) { validateTriple(serviceNamespace, resourceId, scalableDimension); @@ -513,6 +544,57 @@ public class ApplicationAutoScalingService { return now.getEpochSecond() + (now.getNano() / 1_000_000 / 1000.0d); } + private static int pageSize(Integer maxResults, int maximum) { + if (maxResults != null && (maxResults < 1 || maxResults > maximum)) { + throw new AwsException("ValidationException", + "MaxResults must be between 1 and " + maximum + ".", 400); + } + return maxResults == null ? maximum : maxResults; + } + + private static AwsException invalidNextToken(String operation) { + return new AwsException("InvalidNextTokenException", + "Invalid NextToken for " + operation + ".", 400); + } + + private String decodeNextToken(String nextToken, String operation) { + if (nextToken == null) { + return null; + } + String cursor = pageTokens.cursorOf(nextToken); + if (cursor == null) { + throw invalidNextToken(operation); + } + return cursor; + } + + private PaginatedResult signedPage(PaginatedResult page) { + return new PaginatedResult<>(page.items(), + page.nextToken() == null ? null : pageTokens.issue(page.nextToken())); + } + + private static String scalableTargetCursor(ScalableTarget target) { + return target.getResourceId() + "\u0000" + target.getScalableDimension(); + } + + private static String scalingPolicyCursor(ScalingPolicy policy) { + return policy.getPolicyName() + "\u0000" + policy.getResourceId() + + "\u0000" + policy.getScalableDimension(); + } + + private static String pageNamespace(List filters, String... fields) { + StringBuilder namespace = new StringBuilder(); + for (String field : fields) { + namespace.append(field == null ? "-1:" : field.length() + ":" + field); + } + List normalized = filters == null ? List.of() : filters.stream().distinct().sorted().toList(); + namespace.append(normalized.size()).append(':'); + for (String filter : normalized) { + namespace.append(filter.length()).append(':').append(filter); + } + return namespace.toString(); + } + private static String targetKey(String region, String serviceNamespace, String resourceId, String scalableDimension) { return region + "::" + serviceNamespace + "::" + scalableDimension + "::" + resourceId; diff --git a/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingIntegrationTest.java index 5385ec4013..93508cf429 100644 --- a/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingIntegrationTest.java @@ -9,6 +9,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestMethodOrder; +import java.util.List; + import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -33,6 +35,7 @@ class ApplicationAutoScalingIntegrationTest { private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; private static final String TARGET_PREFIX = "AnyScaleFrontendService."; private static final String RESOURCE_ID = "service/aas-it-cluster/aas-it-service"; + private static final String PAGED_RESOURCE_ID = "service/aas-it-cluster/aas-it-service-paged"; private static final String DIMENSION = "ecs:service:DesiredCount"; private static String scalableTargetArn; @@ -118,6 +121,37 @@ class ApplicationAutoScalingIntegrationTest { @Test @Order(4) + void describeScalableTargetsPaginatesWithMaxResultsAndNextToken() { + call("RegisterScalableTarget") + .body(""" + { + "ServiceNamespace": "ecs", + "ResourceId": "%s", + "ScalableDimension": "%s", + "MinCapacity": 1, + "MaxCapacity": 2 + } + """.formatted(PAGED_RESOURCE_ID, DIMENSION)) + .when().post("/").then().statusCode(200); + + String nextToken = call("DescribeScalableTargets") + .body("{ \"ServiceNamespace\": \"ecs\", \"MaxResults\": 1 }") + .when().post("/") + .then().statusCode(200) + .body("ScalableTargets", hasSize(1)) + .body("NextToken", notNullValue()) + .extract().path("NextToken"); + + call("DescribeScalableTargets") + .body("{ \"ServiceNamespace\": \"ecs\", \"MaxResults\": 1, \"NextToken\": \"%s\" }" + .formatted(nextToken)) + .when().post("/").then().statusCode(200) + .body("ScalableTargets", hasSize(1)) + .body("NextToken", nullValue()); + } + + @Test + @Order(5) void listTagsForResourceResolvesByScalableTargetArn() { call("ListTagsForResource") .body("{ \"ResourceARN\": \"%s\" }".formatted(scalableTargetArn)) @@ -126,7 +160,7 @@ class ApplicationAutoScalingIntegrationTest { } @Test - @Order(5) + @Order(6) void tagAndUntagResource() { call("TagResource") .body(""" @@ -154,7 +188,7 @@ class ApplicationAutoScalingIntegrationTest { } @Test - @Order(6) + @Order(7) void putScalingPolicyReturnsPolicyArnAndAlarms() { call("PutScalingPolicy") .body(""" @@ -185,7 +219,7 @@ class ApplicationAutoScalingIntegrationTest { } @Test - @Order(7) + @Order(8) void describeScalingPoliciesRoundTripsEveryConfiguredField() { call("DescribeScalingPolicies") .body(""" @@ -213,7 +247,53 @@ class ApplicationAutoScalingIntegrationTest { } @Test - @Order(8) + @Order(9) + void describeScalingPoliciesPaginatesWithMaxResultsAndNextToken() { + call("PutScalingPolicy") + .body(""" + { + "PolicyName": "aas-it-step-policy", + "PolicyType": "StepScaling", + "ServiceNamespace": "ecs", + "ResourceId": "%s", + "ScalableDimension": "%s", + "StepScalingPolicyConfiguration": { "AdjustmentType": "ChangeInCapacity" } + } + """.formatted(RESOURCE_ID, DIMENSION)) + .when().post("/").then().statusCode(200); + + String nextToken = call("DescribeScalingPolicies") + .body(""" + { + "ServiceNamespace": "ecs", + "ResourceId": "%s", + "ScalableDimension": "%s", + "MaxResults": 1 + } + """.formatted(RESOURCE_ID, DIMENSION)) + .when().post("/") + .then().statusCode(200) + .body("ScalingPolicies", hasSize(1)) + .body("NextToken", notNullValue()) + .extract().path("NextToken"); + + call("DescribeScalingPolicies") + .body(""" + { + "ServiceNamespace": "ecs", + "ResourceId": "%s", + "ScalableDimension": "%s", + "MaxResults": 1, + "NextToken": "%s" + } + """.formatted(RESOURCE_ID, DIMENSION, nextToken)) + .when().post("/").then().statusCode(200) + .body("ScalingPolicies", hasSize(1)) + .body("NextToken", nullValue()); + } + + @Test + @Order(10) void putScalingPolicyOnUnregisteredTargetThrowsObjectNotFound() { call("PutScalingPolicy") .body(""" @@ -236,7 +316,7 @@ class ApplicationAutoScalingIntegrationTest { } @Test - @Order(9) + @Order(11) void invalidServiceNamespaceIsRejected() { call("DescribeScalableTargets") .body("{ \"ServiceNamespace\": \"bogus\" }") @@ -245,7 +325,7 @@ class ApplicationAutoScalingIntegrationTest { } @Test - @Order(10) + @Order(12) void tagsOnUnknownArnThrowResourceNotFound() { call("ListTagsForResource") .body(""" @@ -256,7 +336,7 @@ class ApplicationAutoScalingIntegrationTest { } @Test - @Order(11) + @Order(13) void deregisterScalableTargetCascadesToItsPolicies() { call("DeregisterScalableTarget") .body(""" @@ -280,7 +360,7 @@ class ApplicationAutoScalingIntegrationTest { } @Test - @Order(12) + @Order(14) void deregisteringTwiceThrowsObjectNotFound() { call("DeregisterScalableTarget") .body(""" @@ -291,10 +371,40 @@ class ApplicationAutoScalingIntegrationTest { } @Test - @Order(13) + @Order(15) void unsupportedActionIsRejected() { call("PutScheduledAction") .body("{ \"ServiceNamespace\": \"ecs\" }") .when().post("/").then().statusCode(400); } + + @Test + @Order(16) + void invalidPaginationTokensReturnTheModeledError() { + for (String action : List.of("DescribeScalableTargets", "DescribeScalingPolicies")) { + for (String token : List.of("", "not!base64")) { + call(action) + .body("{ \"ServiceNamespace\": \"ecs\", \"NextToken\": \"%s\" }".formatted(token)) + .when().post("/").then().statusCode(400) + .body("__type", equalTo("InvalidNextTokenException")); + } + } + } + + @Test + @Order(17) + void pageSizeLimitsAreSpecificToEachOperation() { + call("DescribeScalableTargets") + .body("{ \"ServiceNamespace\": \"ecs\", \"MaxResults\": 50 }") + .when().post("/").then().statusCode(200); + + call("DescribeScalingPolicies") + .body("{ \"ServiceNamespace\": \"ecs\", \"MaxResults\": 10 }") + .when().post("/").then().statusCode(200); + + call("DescribeScalingPolicies") + .body("{ \"ServiceNamespace\": \"ecs\", \"MaxResults\": 11 }") + .when().post("/").then().statusCode(400) + .body("__type", equalTo("ValidationException")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.java index dd596100fa..a140602d75 100644 --- a/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/applicationautoscaling/ApplicationAutoScalingServiceTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.applicationautoscaling; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.applicationautoscaling.model.PredefinedMetricSpecification; @@ -11,7 +12,10 @@ import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsS import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import java.nio.charset.StandardCharsets; +import java.util.Base64; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; @@ -150,6 +154,167 @@ class ApplicationAutoScalingServiceTest { assertEquals(0, service.describeScalableTargets("kafka", null, null, REGION).size()); } + @Test + void describeScalableTargetsHonorsMaxResultsAndNextToken() { + service.registerScalableTarget(NAMESPACE, "service/a/one", DIMENSION, 1, 10, + null, null, Map.of(), REGION); + service.registerScalableTarget(NAMESPACE, "service/a/two", DIMENSION, 1, 10, + null, null, Map.of(), REGION); + + PaginatedResult first = service.describeScalableTargets( + NAMESPACE, null, null, 1, null, REGION); + + assertEquals(1, first.items().size()); + assertNotNull(first.nextToken()); + + service.deregisterScalableTarget(NAMESPACE, first.items().getFirst().getResourceId(), DIMENSION, REGION); + PaginatedResult second = service.describeScalableTargets( + NAMESPACE, null, null, 1, first.nextToken(), REGION); + + assertEquals(1, second.items().size()); + assertNull(second.nextToken()); + assertTrue(!first.items().getFirst().getResourceId() + .equals(second.items().getFirst().getResourceId())); + } + + @Test + void describeScalingPoliciesHonorsMaxResultsAndNextToken() { + register(); + service.putScalingPolicy("policy-a", "StepScaling", NAMESPACE, RESOURCE_ID, DIMENSION, + null, null, REGION); + service.putScalingPolicy("policy-b", "StepScaling", NAMESPACE, RESOURCE_ID, DIMENSION, + null, null, REGION); + + PaginatedResult first = service.describeScalingPolicies( + NAMESPACE, RESOURCE_ID, DIMENSION, null, 1, null, REGION); + + assertEquals(1, first.items().size()); + assertNotNull(first.nextToken()); + + service.deleteScalingPolicy(first.items().getFirst().getPolicyName(), NAMESPACE, RESOURCE_ID, DIMENSION, REGION); + PaginatedResult second = service.describeScalingPolicies( + NAMESPACE, RESOURCE_ID, DIMENSION, null, 1, first.nextToken(), REGION); + + assertEquals(1, second.items().size()); + assertNull(second.nextToken()); + assertTrue(!first.items().getFirst().getPolicyName() + .equals(second.items().getFirst().getPolicyName())); + } + + @Test + void describePaginationValidatesPageSizeAndToken() { + register(); + + assertThrows(AwsException.class, () -> service.describeScalableTargets( + NAMESPACE, null, null, 0, null, REGION)); + assertThrows(AwsException.class, () -> service.describeScalableTargets( + NAMESPACE, null, null, 51, null, REGION)); + assertThrows(AwsException.class, () -> service.describeScalableTargets( + NAMESPACE, null, null, null, "", REGION)); + } + + @Test + void targetTokensDistinguishFilterListsWithCommas() { + String dimension = "custom-resource:ResourceType:Property"; + for (String id : List.of("a, b", "x")) { + service.registerScalableTarget("custom-resource", id, dimension, 1, 10, null, null, null, REGION); + } + String token = service.describeScalableTargets("custom-resource", List.of("a, b", "x"), + null, 1, null, REGION).nextToken(); + assertNotNull(token); + assertEquals("x", service.describeScalableTargets("custom-resource", List.of("x", "a, b"), + null, 1, token, REGION).items().getFirst().getResourceId()); + + assertInvalidToken(() -> service.describeScalableTargets("custom-resource", List.of("a", "b", "x"), + null, 1, token, REGION)); + } + + @Test + void policyTokensDistinguishFilterListsWithCommas() { + register(); + for (String name : List.of("a, b", "x")) { + service.putScalingPolicy(name, "StepScaling", NAMESPACE, RESOURCE_ID, DIMENSION, null, null, REGION); + } + String token = service.describeScalingPolicies(NAMESPACE, RESOURCE_ID, DIMENSION, + List.of("a, b", "x"), 1, null, REGION).nextToken(); + assertNotNull(token); + assertEquals("x", service.describeScalingPolicies(NAMESPACE, RESOURCE_ID, DIMENSION, + List.of("x", "a, b"), 1, token, REGION).items().getFirst().getPolicyName()); + + assertInvalidToken(() -> service.describeScalingPolicies(NAMESPACE, RESOURCE_ID, DIMENSION, + List.of("a", "b", "x"), 1, token, REGION)); + } + + @Test + void targetTokensRejectEditedCursors() { + register(); + service.registerScalableTarget(NAMESPACE, "service/z/last", DIMENSION, 1, 10, null, null, null, REGION); + String token = service.describeScalableTargets(NAMESPACE, null, null, 1, null, REGION).nextToken(); + assertNotNull(token); + + assertInvalidToken(() -> service.describeScalableTargets(NAMESPACE, null, null, 1, editedToken(token), REGION)); + assertInvalidToken(() -> service.describeScalingPolicies(NAMESPACE, null, null, null, 1, token, REGION)); + } + + @Test + void policyTokensRejectEditedCursors() { + register(); + for (String name : List.of("first", "last")) { + service.putScalingPolicy(name, "StepScaling", NAMESPACE, RESOURCE_ID, DIMENSION, null, null, REGION); + } + String token = service.describeScalingPolicies(NAMESPACE, null, null, null, 1, null, REGION).nextToken(); + assertNotNull(token); + + assertInvalidToken(() -> service.describeScalingPolicies( + NAMESPACE, null, null, null, 1, editedToken(token), REGION)); + assertInvalidToken(() -> service.describeScalableTargets(NAMESPACE, null, null, 1, token, REGION)); + } + + @Test + void malformedTokensUseTheModeledErrorCode() { + for (String token : List.of("", "not!base64")) { + assertInvalidToken(() -> service.describeScalableTargets(NAMESPACE, null, null, 1, token, REGION)); + assertInvalidToken(() -> service.describeScalingPolicies(NAMESPACE, null, null, null, 1, token, REGION)); + } + } + + @Test + void scalingPolicyPageSizeDefaultsToTen() { + register(); + for (int index = 0; index < 11; index++) { + service.putScalingPolicy("policy-" + index, "StepScaling", NAMESPACE, RESOURCE_ID, DIMENSION, + null, null, REGION); + } + PaginatedResult first = service.describeScalingPolicies( + NAMESPACE, null, null, null, null, null, REGION); + assertEquals(10, first.items().size()); + assertNotNull(first.nextToken()); + PaginatedResult second = service.describeScalingPolicies( + NAMESPACE, null, null, null, null, first.nextToken(), REGION); + assertEquals(1, second.items().size()); + assertNull(second.nextToken()); + } + + @Test + void scalingPolicyPageSizeHasItsOwnMaximum() { + register(); + assertEquals(1, service.describeScalableTargets(NAMESPACE, null, null, 50, null, REGION).items().size()); + assertEquals(0, service.describeScalingPolicies(NAMESPACE, null, null, null, 10, null, REGION).items().size()); + AwsException error = assertThrows(AwsException.class, + () -> service.describeScalingPolicies(NAMESPACE, null, null, null, 11, null, REGION)); + assertEquals("ValidationException", error.getErrorCode()); + } + + private static String editedToken(String token) { + String decoded = new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8); + return Base64.getUrlEncoder().withoutPadding().encodeToString((decoded + "edited").getBytes(StandardCharsets.UTF_8)); + } + + private static void assertInvalidToken(Executable request) { + AwsException error = assertThrows(AwsException.class, request); + assertEquals("InvalidNextTokenException", error.getErrorCode()); + } + @Test void describeRejectsDimensionWithoutResourceId() { register();