fix(apigatewayv2): page GetApis with MaxResults and NextToken (#7770)

This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-11-09 01:30:45 -04:00
1 parent ed45a35274
commit b93afa9e89
5 files changed
+211 -7

No files matched your search

+4
View File
@@ -951,6 +951,10 @@ listener relays the request unchanged and does not add a hop.
(`arn:<partition>:apigateway:<region>::/vpclinks/<vpcLinkId>`). `UpdateVpcLink` changes only the
name, as in the API model.
`GetApis` pages with `MaxResults` and `NextToken`: a page holds at most `MaxResults` APIs and
carries a `NextToken` unless it is the last. Without `MaxResults` every API comes back on one page.
A `MaxResults` below 1 or an unreadable `NextToken` is refused with `BadRequestException`.
### Custom Domain Names and API Mappings
A custom domain created through either API is one record, routed by its `Host` header as
@@ -10,6 +10,8 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
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.core.common.RegionResolver;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.services.apigateway.ApiGatewayService.StoredMapping;
@@ -1418,12 +1420,18 @@ public class ApiGatewayController {
@GET
@Path("/v2/apis")
public Response getApis(@Context HttpHeaders headers) {
public Response getApis(@Context HttpHeaders headers,
@QueryParam("maxResults") String maxResults,
@QueryParam("nextToken") String nextToken) {
String region = regionResolver.resolveRegion(headers);
List<Api> apis = v2Service.getApis(region);
PaginatedResult<Api> page = v2Service.getApis(region,
Pagination.parseMaxResults(maxResults, "BadRequestException"), nextToken);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("items");
apis.forEach(a -> items.add(toV2ApiNode(a)));
page.items().forEach(a -> items.add(toV2ApiNode(a)));
if (page.nextToken() != null) {
root.put("nextToken", page.nextToken());
}
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@@ -8,6 +8,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.EpochSeconds;
import io.floci.aws.core.common.JsonErrorResponseUtils;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.services.apigatewayv2.model.*;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -40,7 +42,7 @@ public class ApiGatewayV2JsonHandler {
case "CreateApi" -> handleCreateApi(request, region);
case "ImportApi" -> handleImportApi(request, region);
case "ReimportApi" -> handleReimportApi(request, region);
case "GetApis" -> handleGetApis(region);
case "GetApis" -> handleGetApis(request, region);
case "GetApi" -> handleGetApi(request, region);
case "UpdateApi" -> handleUpdateApi(request, region);
case "DeleteApi" -> handleDeleteApi(request, region);
@@ -116,11 +118,20 @@ public class ApiGatewayV2JsonHandler {
return Response.status(201).entity(toApiNode(api).toString()).build();
}
private Response handleGetApis(String region) {
List<Api> apis = service.getApis(region);
private Response handleGetApis(JsonNode request, String region) {
JsonNode maxResults = request.path("MaxResults");
if (maxResults.isContainerNode()) {
throw new AwsException("BadRequestException", "MaxResults must be a string.", 400);
}
PaginatedResult<Api> page = service.getApis(region,
Pagination.parseMaxResults(maxResults.asText(null), "BadRequestException"),
Pagination.parseNextToken(request, "NextToken", "BadRequestException"));
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("Items");
apis.forEach(a -> items.add(toApiNode(a)));
page.items().forEach(a -> items.add(toApiNode(a)));
if (page.nextToken() != null) {
root.put("NextToken", page.nextToken());
}
return Response.ok(root.toString()).build();
}
@@ -5,6 +5,8 @@ import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsEndpoints;
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.core.common.RegionResolver;
import io.floci.aws.core.common.ReservedTags;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
@@ -228,6 +230,16 @@ public class ApiGatewayV2Service {
return apiStore.scan(k -> k.startsWith(prefix));
}
public PaginatedResult<Api> getApis(String region, Integer maxResults, String nextToken) {
if (maxResults != null && maxResults < 1) {
throw new AwsException("BadRequestException", "MaxResults must be at least 1", 400);
}
return Pagination.paginate(getApis(region), Api::getApiId,
maxResults == null ? Integer.MAX_VALUE : maxResults, nextToken,
"apis:" + regionResolver.getAccountId() + ":" + region,
token -> new AwsException("BadRequestException", "Invalid NextToken", 400));
}
public void deleteApi(String region, String apiId) {
getApi(region, apiId);
apiStore.delete(apiKey(region, apiId));
@@ -0,0 +1,169 @@
package io.floci.aws.services.apigatewayv2;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.http.apache5.Apache5HttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.apigatewayv2.ApiGatewayV2Client;
import software.amazon.awssdk.services.apigatewayv2.model.Api;
import software.amazon.awssdk.services.apigatewayv2.model.BadRequestException;
import software.amazon.awssdk.services.apigatewayv2.model.GetApisResponse;
import software.amazon.awssdk.services.apigatewayv2.model.ProtocolType;
import java.util.ArrayList;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ApiGatewayV2GetApisPaginationIntegrationTest {
// A Region no other test creates APIs in, so the pages hold exactly this test's APIs.
private static final Region REGION = Region.AP_SOUTHEAST_3;
private static final List<String> NAMES = List.of("paging-a", "paging-b", "paging-c");
private static final List<String> CREATED = new ArrayList<>();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static ApiGatewayV2Client client() {
return AwsTestClients.create(ApiGatewayV2Client.builder(), "test", REGION, Apache5HttpClient.builder());
}
@Test
@Order(1)
void createApis() {
try (ApiGatewayV2Client client = client()) {
for (String name : NAMES) {
CREATED.add(client.createApi(r -> r.name(name).protocolType(ProtocolType.HTTP)).apiId());
}
}
}
@Test
@Order(2)
void getApisPagesOneApiAtATimeWithATokenOnEveryPageButTheLast() {
try (ApiGatewayV2Client client = client()) {
List<String> seen = new ArrayList<>();
List<Boolean> tokens = new ArrayList<>();
String token = null;
do {
String next = token;
GetApisResponse page = client.getApis(r -> r.maxResults("1").nextToken(next));
assertEquals(1, page.items().size());
page.items().stream().map(Api::apiId).forEach(seen::add);
token = page.nextToken();
tokens.add(token != null);
} while (token != null && seen.size() < 10);
assertEquals(CREATED.stream().sorted().toList(), seen.stream().sorted().toList());
assertEquals(List.of(true, true, false), tokens);
}
}
@Test
@Order(3)
void getApisWithoutMaxResultsReturnsEveryApiWithoutAToken() {
try (ApiGatewayV2Client client = client()) {
GetApisResponse page = client.getApis(r -> { });
assertEquals(3, page.items().size());
assertNull(page.nextToken());
}
}
@Test
@Order(4)
void getApisRefusesAnUnreadableToken() {
try (ApiGatewayV2Client client = client()) {
BadRequestException e = assertThrows(BadRequestException.class,
() -> client.getApis(r -> r.nextToken("not-a-token")));
assertEquals(400, e.statusCode());
}
}
@Test
@Order(5)
void getApisRefusesAMaxResultsBelowOne() {
try (ApiGatewayV2Client client = client()) {
BadRequestException e = assertThrows(BadRequestException.class,
() -> client.getApis(r -> r.maxResults("0")));
assertEquals(400, e.statusCode());
}
}
@Test
@Order(6)
void getApisOverJson11PagesWithMaxResultsAndNextToken() {
String token = json11GetApis(REGION, "{\"MaxResults\":\"2\"}")
.then().statusCode(200)
.body("Items", hasSize(2))
.body("NextToken", notNullValue())
.extract().path("NextToken");
json11GetApis(REGION, "{\"MaxResults\":\"2\",\"NextToken\":\"" + token + "\"}")
.then().statusCode(200)
.body("Items", hasSize(1))
.body("NextToken", nullValue());
}
@Test
@Order(7)
void getApisRefusesATokenIssuedForAnotherRegion() {
String token;
try (ApiGatewayV2Client client = client()) {
token = client.getApis(r -> r.maxResults("1")).nextToken();
}
try (ApiGatewayV2Client other = AwsTestClients.create(ApiGatewayV2Client.builder(), "test",
Region.AP_SOUTHEAST_4, Apache5HttpClient.builder())) {
assertThrows(BadRequestException.class, () -> other.getApis(r -> r.nextToken(token)));
}
}
@ParameterizedTest
@Order(8)
@ValueSource(strings = {"{\"MaxResults\":{\"n\":1}}", "{\"NextToken\":[\"x\"]}"})
void getApisOverJson11RefusesAPaginationFieldThatIsNotAScalar(String body) {
json11GetApis(REGION, body)
.then().statusCode(400)
.body("__type", containsString("BadRequestException"));
}
private static Response json11GetApis(Region region, String body) {
return given()
.contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", "AmazonApiGatewayV2.GetApis")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260413/" + region.id() + "/apigatewayv2/aws4_request")
.body(body)
.when().post("/");
}
@Test
@Order(20)
void deleteApis() {
try (ApiGatewayV2Client client = client()) {
for (String apiId : CREATED) {
client.deleteApi(r -> r.apiId(apiId));
}
}
}
}