feat(apigateway): add documentation part operations (#7712)

This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-11-07 02:09:21 -04:00
1 parent a99119e3b9
commit 856970a24f
11 files changed
+973 -4

No files matched your search

+7
View File
@@ -286,6 +286,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s
$(PYTHON) tools/aws/regen_apigateway_types.py
$(PYTHON) tools/aws/regen_sesv2_shapes.py
$(PYTHON) tools/aws/regen_apigateway_shapes.py
$(PYTHON) tools/aws/regen_apigateway_documentation_shapes.py
$(PYTHON) tools/aws/regen_ecs_shapes.py
$(PYTHON) tools/aws/regen_emr_serverless_shapes.py
$(PYTHON) tools/aws/regen_query_services.py
@@ -397,6 +398,12 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres
echo " Run 'make aws-data-sync' and commit the result."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_apigateway_documentation_shapes.py --check || { \
echo ""; \
echo "error: src/main/resources/aws/apigateway-documentation-request-shapes.json is out of date."; \
echo " Run 'make aws-data-sync' and commit the result."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_ecs_shapes.py --check || { \
echo ""; \
echo "error: src/main/resources/aws/ecs-request-shapes.json is out of date."; \
+5 -1
View File
@@ -115,11 +115,15 @@ changing the API. Leading/trailing whitespace and non-ASCII lookalikes are not a
| **Request Validators** | CreateRequestValidator, GetRequestValidator, GetRequestValidators, UpdateRequestValidator, DeleteRequestValidator |
| **Gateway Responses** | PutGatewayResponse, GetGatewayResponse, GetGatewayResponses, UpdateGatewayResponse, DeleteGatewayResponse |
| **Models** | CreateModel, GetModel, GetModels, UpdateModel, DeleteModel |
| **Documentation Parts** | CreateDocumentationPart, GetDocumentationPart, GetDocumentationParts, UpdateDocumentationPart, DeleteDocumentationPart |
| **Domain Names** | CreateDomainName, GetDomainName, GetDomainNames, UpdateDomainName, DeleteDomainName |
| **Base Path Mappings** | CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, UpdateBasePathMapping, DeleteBasePathMapping |
| **Account** | GetAccount, UpdateAccount |
| **Tags** | TagResource, UntagResource, GetTags (ListTagsForResource) |
Documentation part listing covers created parts. The `UNDOCUMENTED` location status does not
discover API locations without documentation content yet.
`TagResource`, `UntagResource` and `GetTags` also accept API key and usage plan ARNs,
`arn:aws:apigateway:<region>::/apikeys/<id>` and `arn:aws:apigateway:<region>::/usageplans/<id>`.
An ARN nested under `/restapis/<id>/` other than a stage, such as a deployment or resource, is rejected with `BadRequestException`.
@@ -395,7 +399,7 @@ These management-plane operations have no handler in v1. Calls will return `404`
- Authorizer testing: `TestInvokeAuthorizer`
- Model templates: `GetModelTemplate`
- Documentation parts and versions (the entire family, 10 operations)
- Documentation versions (5 operations)
- Client Certificates (5 operations)
- `ImportDocumentationParts`
+1 -1
View File
@@ -21,7 +21,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Lambda](lambda.md) | `/2015-03-31/functions/...` + `/2025-12-01/durable-executions/...` | REST JSON | 55 |
| [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 22 |
| [Lambda Web Functions](lambda-web-functions.md) | `/2025-03-07/web-functions/...` | REST JSON | 20 |
| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 80 |
| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 85 |
| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane |
| [IAM](iam.md) | `POST /` with `Action=` param | Query | 180 |
| [STS](sts.md) | `POST /` with `Action=` param | Query | 11 |
@@ -18,6 +18,7 @@ import io.floci.aws.services.apigateway.model.ApiGatewayResource;
import io.floci.aws.services.apigateway.model.ApiKey;
import io.floci.aws.services.apigateway.model.BasePathMapping;
import io.floci.aws.services.apigateway.model.CustomDomain;
import io.floci.aws.services.apigateway.model.DocumentationPart;
import io.floci.aws.services.apigateway.model.EndpointConfiguration;
import io.floci.aws.services.apigateway.model.EndpointType;
import io.floci.aws.services.apigateway.model.GatewayResponse;
@@ -1222,6 +1223,71 @@ public class ApiGatewayController {
return Response.accepted().build();
}
// ──────────────────────────── Documentation Parts (v1) ────────────────────────────
@POST
@Path("/restapis/{apiId}/documentation/parts")
public Response createDocumentationPart(@Context HttpHeaders headers, @PathParam("apiId") String apiId,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
DocumentationPart part = service.createDocumentationPart(region, apiId, request);
return Response.status(201).entity(objectMapper.valueToTree(part).toString())
.type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/restapis/{apiId}/documentation/parts")
public Response getDocumentationParts(@Context HttpHeaders headers, @PathParam("apiId") String apiId,
@QueryParam("type") String type, @QueryParam("name") String name,
@QueryParam("path") String path,
@QueryParam("locationStatus") String locationStatus,
@QueryParam("limit") Integer limit, @QueryParam("position") String position) {
String region = regionResolver.resolveRegion(headers);
ApiGatewayService.DocumentationPartPage page = service.getDocumentationParts(region, apiId, type, name,
path, locationStatus, limit, position);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("item");
page.items().forEach(part -> items.add(objectMapper.valueToTree(part)));
if (page.position() != null) {
root.put("position", page.position());
}
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/restapis/{apiId}/documentation/parts/{partId}")
public Response getDocumentationPart(@Context HttpHeaders headers, @PathParam("apiId") String apiId,
@PathParam("partId") String partId) {
String region = regionResolver.resolveRegion(headers);
DocumentationPart part = service.getDocumentationPart(region, apiId, partId);
return Response.ok(objectMapper.valueToTree(part).toString()).type(MediaType.APPLICATION_JSON).build();
}
@PATCH
@Path("/restapis/{apiId}/documentation/parts/{partId}")
public Response updateDocumentationPart(@Context HttpHeaders headers, @PathParam("apiId") String apiId,
@PathParam("partId") String partId, String body) {
String region = regionResolver.resolveRegion(headers);
List<Map<String, String>> operations = parsePatchOperations(body);
DocumentationPart part = service.updateDocumentationPart(region, apiId, partId, operations);
return Response.ok(objectMapper.valueToTree(part).toString()).type(MediaType.APPLICATION_JSON).build();
}
@DELETE
@Path("/restapis/{apiId}/documentation/parts/{partId}")
public Response deleteDocumentationPart(@Context HttpHeaders headers, @PathParam("apiId") String apiId,
@PathParam("partId") String partId) {
String region = regionResolver.resolveRegion(headers);
service.deleteDocumentationPart(region, apiId, partId);
return Response.accepted().build();
}
// ──────────────────────────── Custom Domains (v1) ────────────────────────────
@POST
@@ -0,0 +1,51 @@
package io.floci.aws.services.apigateway;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestConstraintCheck;
import java.util.List;
/** Checks documentation-part requests against the pinned API Gateway service model. */
final class ApiGatewayDocumentationRequestShapes {
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load(
"aws/apigateway-documentation-request-shapes.json", "API Gateway documentation request shapes",
new RequestConstraintCheck.Messages() {
@Override
public AwsException type(String path, String type) {
return bad(path + " must be a " + type + ".");
}
@Override
public AwsException bounds(String path, String type, Long min, Long max, long size) {
return bad(path + " is outside the modeled bounds.");
}
@Override
public AwsException pattern(String path, String pattern) {
return bad(path + " does not match the modeled pattern.");
}
@Override
public AwsException enumValue(String path, List<String> values) {
return bad(path + " is not a modeled value.");
}
@Override
public AwsException required(String path) {
return bad(path + " is required.");
}
});
private ApiGatewayDocumentationRequestShapes() {
}
static void check(String operation, JsonNode request) {
CHECK.check(operation, request);
}
private static AwsException bad(String message) {
return new AwsException("BadRequestException", message, 400);
}
}
@@ -2,6 +2,7 @@ package io.floci.aws.services.apigateway;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
@@ -31,6 +32,7 @@ import io.floci.aws.services.apigateway.model.BasePathMapping;
import io.floci.aws.services.apigateway.model.CustomDomain;
import io.floci.aws.services.apigateway.model.Deployment;
import io.floci.aws.services.apigateway.model.DeploymentExportSnapshot;
import io.floci.aws.services.apigateway.model.DocumentationPart;
import io.floci.aws.services.apigateway.model.EndpointConfiguration;
import io.floci.aws.services.apigateway.model.EndpointType;
import io.floci.aws.services.apigateway.model.GatewayResponse;
@@ -81,6 +83,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.StringJoiner;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Predicate;
@@ -124,6 +127,7 @@ public class ApiGatewayService implements ResourceProvider {
private final StorageBackend<String, RequestValidator> requestValidatorStore;
private final StorageBackend<String, GatewayResponse> gatewayResponseStore;
private final StorageBackend<String, Model> modelStore;
private final StorageBackend<String, DocumentationPart> documentationPartStore;
private final StorageBackend<String, VpcLink> vpcLinkStore;
private final StorageBackend<String, Account> accountStore;
private final AccountAwareStorageBackend<CustomDomain> domainStore;
@@ -229,6 +233,9 @@ public class ApiGatewayService implements ResourceProvider {
this.modelStore = storageFactory.create("apigateway", "apigateway-models.json",
new TypeReference<>() {
});
this.documentationPartStore = storageFactory.create("apigateway", "apigateway-documentation-parts.json",
new TypeReference<>() {
});
this.vpcLinkStore = storageFactory.create("apigateway", "apigateway-vpclinks.json",
new TypeReference<>() {
});
@@ -471,7 +478,7 @@ public class ApiGatewayService implements ResourceProvider {
return apiStore.scan(k -> k.startsWith(prefix));
}
public void deleteRestApi(String region, String apiId) {
public synchronized void deleteRestApi(String region, String apiId) {
getRestApi(region, apiId);
apiStore.delete(apiKey(region, apiId));
// Simple cascade: delete resources for this API
@@ -481,6 +488,9 @@ public class ApiGatewayService implements ResourceProvider {
deploymentModelStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(deploymentModelStore::delete);
stageStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(stageStore::delete);
modelStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(modelStore::delete);
Set<String> documentationPartKeys = new HashSet<>(documentationPartStore.keys());
documentationPartKeys.removeIf(key -> !key.startsWith(prefix));
documentationPartStore.deleteAllAtomically(documentationPartKeys);
requestValidatorStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(requestValidatorStore::delete);
gatewayResponseStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(gatewayResponseStore::delete);
LOG.infov("Deleted REST API: {0} in {1}", apiId, region);
@@ -2230,6 +2240,184 @@ public class ApiGatewayService implements ResourceProvider {
modelStore.delete(modelKey(region, apiId, modelName));
}
// ──────────────────────────── Documentation Parts ────────────────────────────
private static final Set<String> DOCUMENTATION_PART_NAMED_TYPES = Set.of("AUTHORIZER", "MODEL",
"PATH_PARAMETER", "QUERY_PARAMETER", "REQUEST_HEADER", "REQUEST_BODY", "RESPONSE_HEADER");
private static final Set<String> DOCUMENTATION_PART_PATH_TYPES = Set.of("RESOURCE", "METHOD", "PATH_PARAMETER",
"QUERY_PARAMETER", "REQUEST_HEADER", "REQUEST_BODY", "RESPONSE", "RESPONSE_HEADER", "RESPONSE_BODY");
private static final Set<String> DOCUMENTATION_PART_METHOD_TYPES = Set.of("METHOD", "PATH_PARAMETER",
"QUERY_PARAMETER", "REQUEST_HEADER", "REQUEST_BODY", "RESPONSE", "RESPONSE_HEADER", "RESPONSE_BODY");
private static final Set<String> DOCUMENTATION_PART_STATUS_TYPES = Set.of("RESPONSE", "RESPONSE_HEADER",
"RESPONSE_BODY");
public synchronized DocumentationPart createDocumentationPart(String region, String apiId,
Map<String, Object> request) {
getRestApi(region, apiId);
if (request == null) {
throw new AwsException("BadRequestException", "Documentation part request is required", 400);
}
ObjectNode modeledRequest = JSON.valueToTree(request);
modeledRequest.put("restApiId", apiId);
ApiGatewayDocumentationRequestShapes.check("CreateDocumentationPart", modeledRequest);
Map<String, String> location = documentationPartLocation(request.get("location"));
String properties = documentationPartProperties(request.get("properties"));
String prefix = region + "::" + apiId + "::";
if (documentationPartStore.scan(key -> key.startsWith(prefix)).stream()
.anyMatch(part -> part.getLocation().equals(location))) {
StringJoiner fields = new StringJoiner(", ");
location.forEach((field, value) -> fields.add(field + " '" + value + "'"));
throw new AwsException("ConflictException",
"Documentation part already exists for the specified location: " + fields + ".", 409);
}
DocumentationPart part = new DocumentationPart();
String id;
do {
id = shortId(6);
} while (documentationPartStore.get(documentationPartKey(region, apiId, id)).isPresent());
part.setId(id);
part.setLocation(location);
part.setProperties(properties);
documentationPartStore.putAllAtomically(Map.of(documentationPartKey(region, apiId, part.getId()), part));
return part;
}
public DocumentationPart getDocumentationPart(String region, String apiId, String partId) {
getRestApi(region, apiId);
return documentationPartStore.get(documentationPartKey(region, apiId, partId))
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid documentation part id specified", 404));
}
public record DocumentationPartPage(List<DocumentationPart> items, String position) {}
public DocumentationPartPage getDocumentationParts(String region, String apiId, String type, String name,
String path, String locationStatus, Integer limit,
String position) {
getRestApi(region, apiId);
ObjectNode modeledRequest = JSON.createObjectNode().put("restApiId", apiId);
if (type != null) {
modeledRequest.put("type", type);
}
if (name != null) {
modeledRequest.put("nameQuery", name);
}
if (path != null) {
modeledRequest.put("path", path);
}
if (locationStatus != null) {
modeledRequest.put("locationStatus", locationStatus);
}
if (limit != null) {
modeledRequest.put("limit", limit);
}
if (position != null) {
modeledRequest.put("position", position);
}
ApiGatewayDocumentationRequestShapes.check("GetDocumentationParts", modeledRequest);
if (limit != null && limit < 1) {
throw new AwsException("BadRequestException", "Invalid limit parameter", 400);
}
int pageSize = limit == null ? 25 : Math.min(limit, 500);
String prefix = region + "::" + apiId + "::";
List<DocumentationPart> parts = documentationPartStore.scan(key -> key.startsWith(prefix)).stream()
.filter(part -> type == null || type.equals(part.getLocation().get("type")))
.filter(part -> name == null || name.equals(part.getLocation().get("name")))
.filter(part -> path == null || path.equals(part.getLocation().get("path")))
.filter(part -> !"UNDOCUMENTED".equals(locationStatus))
.sorted(Comparator.comparing(DocumentationPart::getId))
.toList();
int start = 0;
if (position != null && !position.isBlank()) {
while (start < parts.size() && !position.equals(parts.get(start).getId())) {
start++;
}
if (start == parts.size()) {
throw new AwsException("BadRequestException", "Invalid position parameter", 400);
}
start++;
}
int end = Math.min(start + pageSize, parts.size());
String nextPosition = end < parts.size() ? parts.get(end - 1).getId() : null;
return new DocumentationPartPage(List.copyOf(parts.subList(start, end)), nextPosition);
}
public synchronized DocumentationPart updateDocumentationPart(String region, String apiId, String partId,
List<Map<String, String>> patchOperations) {
DocumentationPart part = getDocumentationPart(region, apiId, partId);
String properties = part.getProperties();
if (patchOperations != null) {
for (Map<String, String> operation : patchOperations) {
if (!"replace".equals(operation.get("op")) || !"/properties".equals(operation.get("path"))) {
throw new AwsException("BadRequestException", "Unsupported documentation part patch operation", 400);
}
properties = documentationPartProperties(operation.get("value"));
}
}
DocumentationPart updated = new DocumentationPart();
updated.setId(part.getId());
updated.setLocation(part.getLocation());
updated.setProperties(properties);
documentationPartStore.putAllAtomically(Map.of(documentationPartKey(region, apiId, partId), updated));
return updated;
}
public synchronized void deleteDocumentationPart(String region, String apiId, String partId) {
getDocumentationPart(region, apiId, partId);
documentationPartStore.deleteAllAtomically(Set.of(documentationPartKey(region, apiId, partId)));
}
private static Map<String, String> documentationPartLocation(Object value) {
Map<?, ?> input = (Map<?, ?>) value;
String type = (String) input.get("type");
Map<String, String> location = new LinkedHashMap<>();
for (Map.Entry<?, ?> entry : input.entrySet()) {
if (!(entry.getKey() instanceof String key) || !(entry.getValue() instanceof String fieldValue)
|| !Set.of("type", "path", "method", "statusCode", "name").contains(key)) {
throw new AwsException("BadRequestException", "Invalid documentation part location", 400);
}
location.put(key, fieldValue);
}
// AWS REST examples allow REQUEST_BODY without a name despite the model's required marker.
if (DOCUMENTATION_PART_NAMED_TYPES.contains(type) && !"REQUEST_BODY".equals(type)
&& (location.get("name") == null || location.get("name").isBlank())) {
throw new AwsException("BadRequestException", "Documentation part location name is required", 400);
}
if (location.containsKey("name") && !DOCUMENTATION_PART_NAMED_TYPES.contains(type)
|| location.containsKey("path") && !DOCUMENTATION_PART_PATH_TYPES.contains(type)
|| location.containsKey("method") && !DOCUMENTATION_PART_METHOD_TYPES.contains(type)
|| location.containsKey("statusCode") && !DOCUMENTATION_PART_STATUS_TYPES.contains(type)) {
throw new AwsException("BadRequestException", "Invalid documentation part location field", 400);
}
if (DOCUMENTATION_PART_PATH_TYPES.contains(type)) {
location.putIfAbsent("path", "/");
}
if (DOCUMENTATION_PART_METHOD_TYPES.contains(type)) {
location.putIfAbsent("method", "*");
}
if (DOCUMENTATION_PART_STATUS_TYPES.contains(type)) {
location.putIfAbsent("statusCode", "*");
}
return location;
}
private static String documentationPartProperties(Object value) {
if (!(value instanceof String properties)) {
throw new AwsException("BadRequestException", "Documentation part properties must be a JSON string", 400);
}
try {
JsonNode content = JSON.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
.readTree(properties);
if (content == null || !content.isObject()) {
throw new AwsException("BadRequestException", "Documentation part properties must be a JSON object", 400);
}
} catch (JsonProcessingException e) {
throw new AwsException("BadRequestException", "Invalid documentation part properties", 400);
}
return properties;
}
// ──────────────────────────── Custom Domains ────────────────────────────
/**
@@ -4733,6 +4921,10 @@ public class ApiGatewayService implements ResourceProvider {
return region + "::" + apiId + "::" + modelName;
}
private String documentationPartKey(String region, String apiId, String partId) {
return region + "::" + apiId + "::" + partId;
}
private String accountKey(String region) {
return region + "::account";
}
@@ -0,0 +1,42 @@
package io.floci.aws.services.apigateway.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.LinkedHashMap;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
@RegisterForReflection
public class DocumentationPart {
private String id;
private Map<String, String> location = new LinkedHashMap<>();
private String properties;
public DocumentationPart() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Map<String, String> getLocation() {
return location;
}
public void setLocation(Map<String, String> location) {
this.location = new LinkedHashMap<>(location);
}
public String getProperties() {
return properties;
}
public void setProperties(String properties) {
this.properties = properties;
}
}
@@ -0,0 +1,87 @@
{
"_source": {
"generator": "tools/aws/regen_apigateway_documentation_shapes.py",
"botocore": "botocore 1.43.118 (installed package)"
},
"operations": {
"CreateDocumentationPart": "CreateDocumentationPartRequest",
"GetDocumentationParts": "GetDocumentationPartsRequest"
},
"shapes": {
"CreateDocumentationPartRequest": {
"type": "structure",
"required": [
"restApiId",
"location",
"properties"
],
"members": {
"restApiId": "String",
"location": "DocumentationPartLocation",
"properties": "String"
}
},
"DocumentationPartLocation": {
"type": "structure",
"required": [
"type"
],
"members": {
"type": "DocumentationPartType",
"path": "String",
"method": "String",
"statusCode": "DocumentationPartLocationStatusCode",
"name": "String"
}
},
"DocumentationPartLocationStatusCode": {
"type": "string",
"pattern": "^([1-5]\\d\\d|\\*|\\s*)$"
},
"DocumentationPartType": {
"type": "string",
"enum": [
"API",
"AUTHORIZER",
"MODEL",
"RESOURCE",
"METHOD",
"PATH_PARAMETER",
"QUERY_PARAMETER",
"REQUEST_HEADER",
"REQUEST_BODY",
"RESPONSE",
"RESPONSE_HEADER",
"RESPONSE_BODY"
]
},
"GetDocumentationPartsRequest": {
"type": "structure",
"required": [
"restApiId"
],
"members": {
"restApiId": "String",
"type": "DocumentationPartType",
"nameQuery": "String",
"path": "String",
"position": "String",
"limit": "NullableInteger",
"locationStatus": "LocationStatusType"
}
},
"LocationStatusType": {
"type": "string",
"enum": [
"DOCUMENTED",
"UNDOCUMENTED"
]
},
"NullableInteger": {
"type": "integer"
},
"String": {
"type": "string"
}
}
}
@@ -0,0 +1,479 @@
package io.floci.aws.services.apigateway;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.apigateway.model.DocumentationPart;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.mockito.MockMakers;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import software.amazon.awssdk.http.apache5.Apache5HttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.apigateway.ApiGatewayClient;
import software.amazon.awssdk.services.apigateway.model.BadRequestException;
import software.amazon.awssdk.services.apigateway.model.ConflictException;
import software.amazon.awssdk.services.apigateway.model.CreateDocumentationPartResponse;
import software.amazon.awssdk.services.apigateway.model.DocumentationPartLocation;
import software.amazon.awssdk.services.apigateway.model.DocumentationPartType;
import software.amazon.awssdk.services.apigateway.model.GetDocumentationPartsResponse;
import software.amazon.awssdk.services.apigateway.model.LocationStatusType;
import software.amazon.awssdk.services.apigateway.model.NotFoundException;
import software.amazon.awssdk.services.apigateway.model.PatchOperation;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class ApiGatewayDocumentationPartIntegrationTest {
@Inject
StorageFactory storageFactory;
@Inject
ApiGatewayService service;
private ApiGatewayClient client() {
return client(Region.US_EAST_1);
}
private ApiGatewayClient client(Region region) {
return AwsTestClients.create(ApiGatewayClient.builder(), "test", region, Apache5HttpClient.builder());
}
@Test
void createDocumentationPartReturnsSdkResponse() {
try (ApiGatewayClient client = client()) {
String apiId = client.createRestApi(request -> request.name("documentation-part-sdk")).id();
try {
DocumentationPartLocation location = DocumentationPartLocation.builder()
.type(DocumentationPartType.MODEL).name("Example").build();
String properties = "{\"title\":\"Example\"}";
CreateDocumentationPartResponse created = client.createDocumentationPart(request -> request
.restApiId(apiId).location(location).properties(properties));
assertNotNull(created.id());
assertEquals(6, created.id().length());
assertEquals(location, created.location());
assertEquals(properties, created.properties());
} finally {
client.deleteRestApi(request -> request.restApiId(apiId));
}
}
}
@Test
void duplicateApiLocationReportsAwsConflictMessage() {
try (ApiGatewayClient client = client()) {
String apiId = client.createRestApi(request -> request.name("documentation-part-conflict")).id();
try {
DocumentationPartLocation location = DocumentationPartLocation.builder()
.type(DocumentationPartType.API).build();
client.createDocumentationPart(request -> request.restApiId(apiId)
.location(location).properties("{}"));
ConflictException conflict = assertThrows(ConflictException.class,
() -> client.createDocumentationPart(request -> request.restApiId(apiId)
.location(location).properties("{}")));
assertEquals("Documentation part already exists for the specified location: type 'API'.",
conflict.awsErrorDetails().errorMessage());
} finally {
client.deleteRestApi(request -> request.restApiId(apiId));
}
}
}
@Test
void modeledDocumentationConstraintsRejectInvalidFields() {
String region = "us-east-1";
String apiId = service.createRestApi(region, Map.of("name", "documentation-part-model-constraints")).getId();
try {
AwsException missing = assertThrows(AwsException.class,
() -> service.createDocumentationPart(region, apiId,
Map.of("location", Map.of("type", "API"))));
assertEquals("CreateDocumentationPart.properties is required.", missing.getMessage());
AwsException type = assertThrows(AwsException.class,
() -> service.createDocumentationPart(region, apiId,
Map.of("location", Map.of("type", "UNKNOWN"), "properties", "{}")));
assertEquals("CreateDocumentationPart.location.type is not a modeled value.", type.getMessage());
AwsException statusCode = assertThrows(AwsException.class,
() -> service.createDocumentationPart(region, apiId,
Map.of("location", Map.of("type", "RESPONSE", "statusCode", "600"),
"properties", "{}")));
assertEquals("CreateDocumentationPart.location.statusCode does not match the modeled pattern.",
statusCode.getMessage());
AwsException listType = assertThrows(AwsException.class,
() -> service.getDocumentationParts(region, apiId, "UNKNOWN", null, null, null, null, null));
assertEquals("GetDocumentationParts.type is not a modeled value.", listType.getMessage());
AwsException locationStatus = assertThrows(AwsException.class,
() -> service.getDocumentationParts(region, apiId, null, null, null, "UNKNOWN", null, null));
assertEquals("GetDocumentationParts.locationStatus is not a modeled value.",
locationStatus.getMessage());
} finally {
service.deleteRestApi(region, apiId);
}
}
@Test
void defaultLocationFieldsAreReturnedAndPreventDuplicateParts() {
try (ApiGatewayClient client = client()) {
String apiId = client.createRestApi(request -> request.name("documentation-part-defaults")).id();
try {
CreateDocumentationPartResponse resource = client.createDocumentationPart(request -> request
.restApiId(apiId).location(DocumentationPartLocation.builder()
.type(DocumentationPartType.RESOURCE).build())
.properties("{\"description\":\"Root\"}"));
assertEquals("/", resource.location().path());
assertEquals("/", client.getDocumentationPart(request -> request.restApiId(apiId)
.documentationPartId(resource.id())).location().path());
assertThrows(ConflictException.class, () -> client.createDocumentationPart(request -> request
.restApiId(apiId).location(DocumentationPartLocation.builder()
.type(DocumentationPartType.RESOURCE).path("/").build())
.properties("{\"description\":\"Duplicate\"}")));
CreateDocumentationPartResponse response = client.createDocumentationPart(request -> request
.restApiId(apiId).location(DocumentationPartLocation.builder()
.type(DocumentationPartType.RESPONSE).build())
.properties("{\"description\":\"Default response\"}"));
assertEquals("/", response.location().path());
assertEquals("*", response.location().method());
assertEquals("*", response.location().statusCode());
assertThrows(ConflictException.class, () -> client.createDocumentationPart(request -> request
.restApiId(apiId).location(DocumentationPartLocation.builder()
.type(DocumentationPartType.RESPONSE).path("/").method("*")
.statusCode("*").build())
.properties("{\"description\":\"Duplicate response\"}")));
} finally {
client.deleteRestApi(request -> request.restApiId(apiId));
}
}
}
@Test
void requestBodyLocationDoesNotRequireName() {
try (ApiGatewayClient client = client()) {
String apiId = client.createRestApi(request -> request.name("documentation-part-request-body")).id();
try {
CreateDocumentationPartResponse created = client.createDocumentationPart(request -> request
.restApiId(apiId).location(DocumentationPartLocation.builder()
.type(DocumentationPartType.REQUEST_BODY).path("/pets").method("POST").build())
.properties("{\"description\":\"Pet request\"}"));
assertNull(created.location().name());
assertEquals("/pets", created.location().path());
assertEquals("POST", created.location().method());
} finally {
client.deleteRestApi(request -> request.restApiId(apiId));
}
}
}
@Test
void nullRequestBodyReturnsBadRequest() {
try (ApiGatewayClient client = client()) {
String apiId = client.createRestApi(request -> request.name("documentation-part-null-body")).id();
try {
given().contentType("application/json").body("null")
.post("/restapis/" + apiId + "/documentation/parts")
.then().statusCode(400);
} finally {
client.deleteRestApi(request -> request.restApiId(apiId));
}
}
}
@Test
void absentRequestBodyReturnsBadRequest() {
try (ApiGatewayClient client = client()) {
String apiId = client.createRestApi(request -> request.name("documentation-part-absent-body")).id();
try {
given().contentType("application/json")
.post("/restapis/" + apiId + "/documentation/parts")
.then().statusCode(400);
} finally {
client.deleteRestApi(request -> request.restApiId(apiId));
}
}
}
@Test
void concurrentCreatesAtSameLocationConflict() throws Exception {
String region = "us-east-1";
String apiId = service.createRestApi(region, Map.of("name", "documentation-part-concurrent")).getId();
try {
int attempts = 24;
CountDownLatch ready = new CountDownLatch(attempts);
CountDownLatch start = new CountDownLatch(1);
try (ExecutorService workers = Executors.newFixedThreadPool(attempts)) {
List<Future<Boolean>> results = new ArrayList<>();
for (int index = 0; index < attempts; index++) {
results.add(workers.submit(() -> {
ready.countDown();
start.await();
try {
service.createDocumentationPart(region, apiId, Map.of(
"location", Map.of("type", "MODEL", "name", "Concurrent"),
"properties", "{}"));
return true;
} catch (AwsException e) {
assertEquals("ConflictException", e.getErrorCode());
return false;
}
}));
}
boolean allReady;
try {
allReady = ready.await(30, TimeUnit.SECONDS);
} finally {
start.countDown();
}
assertTrue(allReady);
int successes = 0;
for (Future<Boolean> result : results) {
if (result.get()) {
successes++;
}
}
assertEquals(1, successes);
assertEquals(1, service.getDocumentationParts(region, apiId, null, null, null,
null, null, null).items().size());
}
} finally {
service.deleteRestApi(region, apiId);
}
}
@Test
void generatedIdCollisionPreservesBothParts() {
String region = "us-east-1";
String apiId = service.createRestApi(region, Map.of("name", "documentation-part-id-collision")).getId();
UUID collision = UUID.fromString("abcdef00-0000-0000-0000-000000000001");
UUID retry = UUID.fromString("12345678-0000-0000-0000-000000000002");
try {
try (MockedStatic<UUID> ids = Mockito.mockStatic(UUID.class,
Mockito.withSettings().mockMaker(MockMakers.INLINE).defaultAnswer(Mockito.CALLS_REAL_METHODS))) {
ids.when(UUID::randomUUID).thenReturn(collision, collision, retry);
DocumentationPart first = service.createDocumentationPart(region, apiId, Map.of(
"location", Map.of("type", "MODEL", "name", "First"), "properties", "{}"));
DocumentationPart second = service.createDocumentationPart(region, apiId, Map.of(
"location", Map.of("type", "MODEL", "name", "Second"), "properties", "{}"));
assertNotEquals(first.getId(), second.getId());
assertEquals("First", service.getDocumentationPart(region, apiId, first.getId())
.getLocation().get("name"));
assertEquals("Second", service.getDocumentationPart(region, apiId, second.getId())
.getLocation().get("name"));
}
} finally {
service.deleteRestApi(region, apiId);
}
}
@Test
void knownApiIdDoesNotCrossAccountBoundary() {
String region = "us-east-1";
String owner = "111122223333";
String other = "444455556666";
String apiId = RequestScopes.callAs(owner, region,
() -> service.createRestApi(region, Map.of("name", "documentation-part-owner")).getId());
try {
String partId = RequestScopes.callAs(owner, region, () -> service.createDocumentationPart(region,
apiId, Map.of("location", Map.of("type", "MODEL", "name", "Owner"),
"properties", "{}")).getId());
RequestScopes.runAs(other, region, () -> {
assertEquals("NotFoundException", assertThrows(AwsException.class,
() -> service.getDocumentationPart(region, apiId, partId)).getErrorCode());
assertEquals("NotFoundException", assertThrows(AwsException.class,
() -> service.getDocumentationParts(region, apiId, null, null, null,
null, null, null)).getErrorCode());
assertEquals("NotFoundException", assertThrows(AwsException.class,
() -> service.updateDocumentationPart(region, apiId, partId,
List.of(Map.of("op", "replace", "path", "/properties", "value", "{}"))))
.getErrorCode());
assertEquals("NotFoundException", assertThrows(AwsException.class,
() -> service.deleteDocumentationPart(region, apiId, partId)).getErrorCode());
});
assertNotNull(RequestScopes.callAs(owner, region,
() -> service.getDocumentationPart(region, apiId, partId)));
} finally {
RequestScopes.runAs(owner, region, () -> service.deleteRestApi(region, apiId));
}
}
@Test
void deletingRestApiRemovesDocumentationPartKeys() {
try (ApiGatewayClient client = client()) {
StorageBackend<String, DocumentationPart> parts = storageFactory.create("apigateway",
"apigateway-documentation-parts.json",
new TypeReference<Map<String, DocumentationPart>>() {});
String apiId = client.createRestApi(request -> request.name("documentation-part-cascade")).id();
boolean deleted = false;
try {
String partId = client.createDocumentationPart(request -> request.restApiId(apiId)
.location(DocumentationPartLocation.builder().type(DocumentationPartType.MODEL)
.name("Example").build())
.properties("{\"title\":\"Example\"}")).id();
String key = "us-east-1::" + apiId + "::" + partId;
assertTrue(parts.keys().contains(key));
client.deleteRestApi(request -> request.restApiId(apiId));
deleted = true;
assertFalse(parts.keys().contains(key));
assertThrows(NotFoundException.class, () -> client.getDocumentationPart(request -> request
.restApiId(apiId).documentationPartId(partId)));
String newApiId = client.createRestApi(request -> request.name("documentation-part-cascade")).id();
try {
assertTrue(client.getDocumentationParts(request -> request.restApiId(newApiId)).items().isEmpty());
assertThrows(NotFoundException.class, () -> client.getDocumentationPart(request -> request
.restApiId(newApiId).documentationPartId(partId)));
} finally {
client.deleteRestApi(request -> request.restApiId(newApiId));
}
} finally {
if (!deleted) {
client.deleteRestApi(request -> request.restApiId(apiId));
}
}
}
}
@Test
void documentationPartRoundTripsThroughReadUpdateAndDelete() {
try (ApiGatewayClient client = client(); ApiGatewayClient otherRegion = client(Region.EU_WEST_1)) {
String apiId = client.createRestApi(request -> request.name("documentation-part-lifecycle")).id();
String otherApiId = client.createRestApi(request -> request.name("documentation-part-other-api")).id();
try {
DocumentationPartLocation location = DocumentationPartLocation.builder()
.type(DocumentationPartType.MODEL).name("Widget").build();
CreateDocumentationPartResponse created = client.createDocumentationPart(request -> request
.restApiId(apiId).location(location).properties("{\"title\":\"Before\"}"));
String partId = created.id();
assertEquals("{\"title\":\"Before\"}", client.getDocumentationPart(request -> request
.restApiId(apiId).documentationPartId(partId)).properties());
assertEquals(partId, client.getDocumentationParts(request -> request.restApiId(apiId))
.items().getFirst().id());
assertThrows(NotFoundException.class, () -> client.getDocumentationPart(request -> request
.restApiId(otherApiId).documentationPartId(partId)));
assertThrows(NotFoundException.class, () -> otherRegion.getDocumentationPart(request -> request
.restApiId(apiId).documentationPartId(partId)));
String updated = "{\"title\":\"After\"}";
assertEquals(updated, client.updateDocumentationPart(request -> request.restApiId(apiId)
.documentationPartId(partId).patchOperations(PatchOperation.builder()
.op("replace").path("/properties").value(updated).build())).properties());
assertEquals(updated, client.getDocumentationPart(request -> request.restApiId(apiId)
.documentationPartId(partId)).properties());
client.deleteDocumentationPart(request -> request.restApiId(apiId).documentationPartId(partId));
assertThrows(NotFoundException.class, () -> client.getDocumentationPart(request -> request
.restApiId(apiId).documentationPartId(partId)));
} finally {
client.deleteRestApi(request -> request.restApiId(apiId));
client.deleteRestApi(request -> request.restApiId(otherApiId));
}
}
}
@Test
void documentationPartsFilterAndPage() {
try (ApiGatewayClient client = client()) {
String apiId = client.createRestApi(request -> request.name("documentation-part-list")).id();
try {
Set<String> ids = new HashSet<>();
for (String name : new String[] {"Alpha", "Beta", "Gamma"}) {
ids.add(client.createDocumentationPart(request -> request.restApiId(apiId)
.location(DocumentationPartLocation.builder().type(DocumentationPartType.MODEL)
.name(name).build()).properties("{\"title\":\"" + name + "\"}")).id());
}
String resourceId = client.createDocumentationPart(request -> request.restApiId(apiId)
.location(DocumentationPartLocation.builder().type(DocumentationPartType.RESOURCE)
.path("/pets").build()).properties("{\"description\":\"Pets\"}")).id();
assertEquals("Beta", client.getDocumentationParts(request -> request.restApiId(apiId)
.nameQuery("Beta")).items().getFirst().location().name());
assertEquals(resourceId, client.getDocumentationParts(request -> request.restApiId(apiId)
.path("/pets")).items().getFirst().id());
assertEquals(3, client.getDocumentationParts(request -> request.restApiId(apiId)
.type(DocumentationPartType.MODEL).locationStatus(LocationStatusType.DOCUMENTED)).items().size());
GetDocumentationPartsResponse page = client.getDocumentationParts(request -> request.restApiId(apiId)
.type(DocumentationPartType.MODEL).limit(1));
Set<String> pagedIds = new HashSet<>();
for (int index = 0; index < ids.size(); index++) {
assertEquals(1, page.items().size());
pagedIds.add(page.items().getFirst().id());
if (index == ids.size() - 1) {
assertNull(page.position());
} else {
assertNotNull(page.position());
String position = page.position();
page = client.getDocumentationParts(request -> request.restApiId(apiId)
.type(DocumentationPartType.MODEL).limit(1).position(position));
}
}
assertEquals(ids, pagedIds);
} finally {
client.deleteRestApi(request -> request.restApiId(apiId));
}
}
}
@Test
void invalidPatchDoesNotChangeDocumentationPart() {
try (ApiGatewayClient client = client()) {
String apiId = client.createRestApi(request -> request.name("documentation-part-validation")).id();
try {
DocumentationPartLocation location = DocumentationPartLocation.builder()
.type(DocumentationPartType.MODEL).name("Example").build();
String original = "{\"title\":\"Original\"}";
CreateDocumentationPartResponse created = client.createDocumentationPart(request -> request
.restApiId(apiId).location(location).properties(original));
assertThrows(BadRequestException.class,
() -> client.updateDocumentationPart(request -> request.restApiId(apiId)
.documentationPartId(created.id()).patchOperations(
PatchOperation.builder().op("replace").path("/properties")
.value("{\"title\":\"Changed\"}").build(),
PatchOperation.builder().op("add").path("/properties")
.value("{\"title\":\"Invalid\"}").build())));
assertThrows(BadRequestException.class,
() -> client.updateDocumentationPart(request -> request.restApiId(apiId)
.documentationPartId(created.id()).patchOperations(PatchOperation.builder()
.op("replace").path("/properties").value("{} trailing").build())));
assertEquals(original, client.getDocumentationPart(request -> request.restApiId(apiId)
.documentationPartId(created.id())).properties());
assertThrows(BadRequestException.class,
() -> client.createDocumentationPart(request -> request.restApiId(apiId)
.location(DocumentationPartLocation.builder().type(DocumentationPartType.MODEL).build())
.properties(original)));
} finally {
client.deleteRestApi(request -> request.restApiId(apiId));
}
}
}
}
@@ -0,0 +1,25 @@
#!/usr/bin/env python3
"""Vendor API Gateway documentation-part request constraints from botocore's service model.
Unlike the body-only API Gateway shape file, this includes URI and query members so the
documentation-part validator can check required members and query enums as modeled.
"""
from __future__ import annotations
import sys
from pathlib import Path
import request_shapes
OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/apigateway-documentation-request-shapes.json"
MODEL = Path("apigateway/2015-07-09")
OPERATIONS = ("CreateDocumentationPart", "GetDocumentationParts")
def main(argv: list[str] | None = None) -> int:
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT,
description=__doc__, operations=OPERATIONS)
if __name__ == "__main__":
sys.exit(main())
+17 -1
View File
@@ -17,6 +17,7 @@ from pathlib import Path
import pytest
import regen_apigateway_documentation_shapes
import regen_apigateway_shapes
import regen_dynamodb_shapes
import regen_ecr_shapes
@@ -327,6 +328,8 @@ def test_build_constraints_output_is_stable():
@pytest.mark.parametrize("script, model, output, extra", [
(regen_apigateway_documentation_shapes, "apigateway/2015-07-09",
"apigateway-documentation-request-shapes.json", {}),
# IAM vendors some operations in part, so it hands the driver its reductions as well as the
# list: the required members an operation answers for itself and the members it answers in a
# wording of its own.
@@ -356,7 +359,8 @@ def vendored(script) -> tuple[str, ...]:
@pytest.mark.parametrize("script", [
regen_ecr_shapes, regen_iam_shapes, regen_logs_delivery_shapes, regen_payment_cryptography_shapes,
regen_apigateway_documentation_shapes, regen_ecr_shapes, regen_iam_shapes, regen_logs_delivery_shapes,
regen_payment_cryptography_shapes,
regen_resource_groups_shapes, regen_sts_shapes,
])
def test_each_vendored_constraints_file_carries_its_operations_and_resolves_its_shapes(script):
@@ -372,6 +376,18 @@ def test_each_vendored_constraints_file_carries_its_operations_and_resolves_its_
assert child in doc["shapes"], f"{name} names {child}"
def test_apigateway_documentation_shapes_keep_path_query_and_body_constraints():
doc = json.loads(regen_apigateway_documentation_shapes.OUTPUT.read_text(encoding="utf-8"))
shapes = doc["shapes"]
assert shapes["CreateDocumentationPartRequest"]["required"] == ["restApiId", "location", "properties"]
assert shapes["DocumentationPartLocation"]["required"] == ["type"]
assert shapes["DocumentationPartLocationStatusCode"]["pattern"] == r"^([1-5]\d\d|\*|\s*)$"
assert "API" in shapes["DocumentationPartType"]["enum"]
assert shapes["GetDocumentationPartsRequest"]["members"]["locationStatus"] == "LocationStatusType"
assert shapes["LocationStatusType"]["enum"] == ["DOCUMENTED", "UNDOCUMENTED"]
def test_ecr_shapes_name_the_ecr_model_and_its_registry_setting_actions():
assert regen_ecr_shapes.MODEL == Path("ecr/2015-09-21")
assert regen_ecr_shapes.OUTPUT.name == "ecr-request-shapes.json"