Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(apigateway): export deployed REST APIs as OpenAPI (#5131)

vamsiak1acedaf06827
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayExportCompatibilityTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayExportCompatibilityTest.java
new file mode 100644
index 0000000000..c76ddb9360
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayExportCompatibilityTest.java
@@ -0,0 +1,198 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.services.apigateway.ApiGatewayClient;
+import software.amazon.awssdk.services.apigateway.model.AuthorizerType;
+import software.amazon.awssdk.services.apigateway.model.BadRequestException;
+import software.amazon.awssdk.services.apigateway.model.GetExportResponse;
+import software.amazon.awssdk.services.apigateway.model.IntegrationType;
+import software.amazon.awssdk.services.apigateway.model.Method;
+import software.amazon.awssdk.services.apigateway.model.Resource;
+
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+@DisplayName("REST API Gateway stage export")
+class ApiGatewayExportCompatibilityTest {
+ @ParameterizedTest
+ @CsvSource({"oas30,application/json", "swagger,application/json", "oas30,application/yaml", "swagger,application/yaml"})
+ @DisplayName("SDK export returns an OpenAPI blob that reimports with method and integration settings")
+ void exportAndReimport(String exportType, String accepts) {
+ try (ApiGatewayClient client = TestFixtures.apiGatewayClient()) {
+ String apiId = client.createRestApi(request -> request.name(TestFixtures.uniqueName("export"))).id();
+ String restoredId = null;
+ try {
+ String rootId = client.getResources(request -> request.restApiId(apiId)).items().get(0).id();
+ client.createModel(request -> request.restApiId(apiId).name("Widget").contentType("application/json")
+ .schema("{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"}}}"));
+ client.putMethod(request -> request.restApiId(apiId).resourceId(rootId).httpMethod("GET")
+ .authorizationType("AWS_IAM").apiKeyRequired(true)
+ .requestModels(Map.of("application/json", "Widget"))
+ .requestParameters(Map.of("method.request.header.X-Trace", true)));
+ client.putIntegration(request -> request.restApiId(apiId).resourceId(rootId).httpMethod("GET")
+ .type(IntegrationType.MOCK).timeoutInMillis(9000)
+ .requestTemplates(Map.of("application/json", "{\"statusCode\":200}")));
+ client.putMethodResponse(request -> request.restApiId(apiId).resourceId(rootId).httpMethod("GET")
+ .statusCode("200").responseParameters(Map.of("method.response.header.X-Trace", false)));
+ client.putIntegrationResponse(request -> request.restApiId(apiId).resourceId(rootId).httpMethod("GET")
+ .statusCode("200").responseTemplates(Map.of("application/json", "{\"exported\":true}")));
+ client.createDeployment(request -> request.restApiId(apiId).stageName("dev"));
+ // Removing the working method must not remove it from the deployed export.
+ client.deleteMethod(request -> request.restApiId(apiId).resourceId(rootId).httpMethod("GET"));
+ GetExportResponse exported = client.getExport(request -> request.restApiId(apiId).stageName("dev")
+ .exportType(exportType).accepts(accepts).parameters(Map.of("extensions", "apigateway")));
+ assertThat(exported.contentType()).startsWith(accepts);
+ assertThat(exported.contentDisposition()).contains("attachment");
+ assertThat(exported.body().asUtf8String()).contains("x-amazon-apigateway-integration");
+ SdkBytes body = exported.body();
+ restoredId = client.importRestApi(request -> request.body(body)).id();
+ String importedId = restoredId;
+ Resource restored = client.getResources(request -> request.restApiId(importedId).embed("methods"))
+ .items().stream().filter(resource -> resource.path().equals("/")).findFirst().orElseThrow();
+ Method get = restored.resourceMethods().get("GET");
+ assertThat(get.authorizationType()).isEqualTo("AWS_IAM");
+ assertThat(get.apiKeyRequired()).isTrue();
+ assertThat(get.requestParameters()).containsEntry("method.request.header.X-Trace", true);
+ assertThat(get.requestModels()).containsEntry("application/json", "Widget");
+ assertThat(client.getModel(request -> request.restApiId(importedId).modelName("Widget")).schema())
+ .contains("name", "string");
+ assertThat(get.methodResponses().get("200").responseParameters()).containsEntry("method.response.header.X-Trace", false);
+ assertThat(get.methodIntegration().type()).isEqualTo(IntegrationType.MOCK);
+ assertThat(get.methodIntegration().timeoutInMillis()).isEqualTo(9000);
+ assertThat(get.methodIntegration().requestTemplates()).containsEntry("application/json", "{\"statusCode\":200}");
+ assertThat(get.methodIntegration().integrationResponses().get("200").responseTemplates())
+ .containsEntry("application/json", "{\"exported\":true}");
+ } finally {
+ if (restoredId != null) {
+ String importedId = restoredId;
+ client.deleteRestApi(request -> request.restApiId(importedId));
+ }
+ client.deleteRestApi(request -> request.restApiId(apiId));
+ }
+ }
+ }
+ @ParameterizedTest
+ @CsvSource({"TOKEN,oas30", "TOKEN,swagger", "COGNITO_USER_POOLS,oas30", "COGNITO_USER_POOLS,swagger"})
+ @DisplayName("Unused authorizers do not block default export re-import")
+ void unusedAuthorizerDoesNotProtectPublicMethods(String kind, String format) {
+ try (ApiGatewayClient client = TestFixtures.apiGatewayClient()) {
+ String apiId = client.createRestApi(request -> request.name(TestFixtures.uniqueName("unused-authorizer"))).id();
+ String restoredId = null;
+ try {
+ client.createAuthorizer(request -> {
+ request.restApiId(apiId).name("Unused").type(AuthorizerType.fromValue(kind))
+ .identitySource("method.request.header.Authorization");
+ if ("TOKEN".equals(kind)) {
+ request.authorizerUri("arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:auth/invocations");
+ } else {
+ request.providerARNs("arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_fixture");
+ }
+ });
+ String rootId = client.getResources(request -> request.restApiId(apiId)).items().get(0).id();
+ client.putMethod(request -> request.restApiId(apiId).resourceId(rootId).httpMethod("GET")
+ .authorizationType("NONE"));
+ client.createDeployment(request -> request.restApiId(apiId).stageName("dev"));
+ SdkBytes document = client.getExport(request -> request.restApiId(apiId).stageName("dev")
+ .exportType(format).accepts("application/json")).body();
+ restoredId = client.importRestApi(request -> request.body(document)).id();
+ String importedId = restoredId;
+ Resource restored = client.getResources(request -> request.restApiId(importedId).embed("methods"))
+ .items().stream().filter(resource -> resource.path().equals("/")).findFirst().orElseThrow();
+ assertThat(restored.resourceMethods().get("GET").authorizationType()).isEqualTo("NONE");
+ assertThat(restored.resourceMethods().get("GET").apiKeyRequired()).isFalse();
+ } finally {
+ if (restoredId != null) {
+ String importedId = restoredId;
+ client.deleteRestApi(request -> request.restApiId(importedId));
+ }
+ client.deleteRestApi(request -> request.restApiId(apiId));
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({"TOKEN,oas30", "TOKEN,swagger", "COGNITO_USER_POOLS,oas30", "COGNITO_USER_POOLS,swagger"})
+ @DisplayName("Protected exports need authorizer definitions for a safe re-import")
+ void authorizerExportCannotBeMisclassifiedAsApiKey(String kind, String format) {
+ try (ApiGatewayClient client = TestFixtures.apiGatewayClient()) {
+ String apiId = client.createRestApi(request -> request.name(TestFixtures.uniqueName("protected-export"))).id();
+ String restoredId = null;
+ try {
+ String rootId = client.getResources(request -> request.restApiId(apiId)).items().get(0).id();
+ String authorizerId = client.createAuthorizer(request -> {
+ request.restApiId(apiId).name("Protected").type(AuthorizerType.fromValue(kind))
+ .identitySource("method.request.header.Authorization");
+ if ("TOKEN".equals(kind)) {
+ request.authorizerUri("arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:auth/invocations");
+ } else {
+ request.providerARNs("arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_fixture");
+ }
+ }).id();
+ client.putMethod(request -> {
+ request.restApiId(apiId).resourceId(rootId).httpMethod("GET").authorizerId(authorizerId)
+ .authorizationType("TOKEN".equals(kind) ? "CUSTOM" : kind);
+ if (!"TOKEN".equals(kind)) {
+ request.authorizationScopes("widgets/read");
+ }
+ });
+ client.createDeployment(request -> request.restApiId(apiId).stageName("dev"));
+ SdkBytes incomplete = client.getExport(request -> request.restApiId(apiId).stageName("dev")
+ .exportType(format)).body();
+ assertThatThrownBy(() -> client.importRestApi(request -> request.body(incomplete)))
+ .isInstanceOf(BadRequestException.class).hasMessageContaining("authorizer definition");
+ SdkBytes complete = client.getExport(request -> request.restApiId(apiId).stageName("dev")
+ .exportType(format).parameters(Map.of("extensions", "authorizers"))).body();
+ restoredId = client.importRestApi(request -> request.body(complete)).id();
+ String importedId = restoredId;
+ Resource root = client.getResources(request -> request.restApiId(importedId).embed("methods")).items().get(0);
+ Method method = root.resourceMethods().get("GET");
+ assertThat(method.authorizationType()).isEqualTo("TOKEN".equals(kind) ? "CUSTOM" : kind);
+ assertThat(method.apiKeyRequired()).isFalse();
+ assertThat(client.getAuthorizer(request -> request.restApiId(importedId).authorizerId(method.authorizerId())).type())
+ .isEqualTo(AuthorizerType.fromValue(kind));
+ if (!"TOKEN".equals(kind)) {
+ assertThat(method.authorizationScopes()).containsExactly("widgets/read");
+ }
+ } finally {
+ if (restoredId != null) {
+ String importedId = restoredId;
+ client.deleteRestApi(request -> request.restApiId(importedId));
+ }
+ client.deleteRestApi(request -> request.restApiId(apiId));
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"oas30", "swagger"})
+ @DisplayName("Duplicate default responses produce an explicit export error")
+ void duplicateResponsePatternsCannotSilentlyOverwrite(String format) {
+ try (ApiGatewayClient client = TestFixtures.apiGatewayClient()) {
+ String apiId = client.createRestApi(request -> request.name(TestFixtures.uniqueName("duplicate-export"))).id();
+ try {
+ String rootId = client.getResources(request -> request.restApiId(apiId)).items().get(0).id();
+ client.putMethod(request -> request.restApiId(apiId).resourceId(rootId).httpMethod("GET").authorizationType("NONE"));
+ client.putIntegration(request -> request.restApiId(apiId).resourceId(rootId).httpMethod("GET").type(IntegrationType.MOCK));
+ for (String status : new String[]{"200", "400"}) {
+ client.putIntegrationResponse(request -> request.restApiId(apiId).resourceId(rootId).httpMethod("GET")
+ .statusCode(status).selectionPattern("").responseTemplates(Map.of("application/json", status)));
+ }
+ client.createDeployment(request -> request.restApiId(apiId).stageName("dev"));
+ assertThatThrownBy(() -> client.getExport(request -> request.restApiId(apiId).stageName("dev")
+ .exportType(format).parameters(Map.of("extensions", "integrations"))))
+ .isInstanceOf(BadRequestException.class).hasMessageContaining("duplicate integration response selection pattern");
+ assertThat(client.getIntegration(request -> request.restApiId(apiId).resourceId(rootId).httpMethod("GET"))
+ .integrationResponses()).containsOnlyKeys("200", "400");
+ } finally {
+ client.deleteRestApi(request -> request.restApiId(apiId));
+ }
+ }
+ }
+
+}
diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md
index 999ce80bd6..c75436656e 100644
--- a/docs/services/api-gateway.md
+++ b/docs/services/api-gateway.md
@@ -87,7 +87,7 @@ includes mapping templates and applies to both `ImportRestApi` and `PutRestApi`.
| **Integrations** | PutIntegration, GetIntegration, UpdateIntegration, DeleteIntegration |
| **Integration Responses** | PutIntegrationResponse, GetIntegrationResponse, UpdateIntegrationResponse, DeleteIntegrationResponse |
| **Deployments** | CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment |
-| **Stages** | CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, FlushStageAuthorizersCache |
+| **Stages** | CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, FlushStageAuthorizersCache, GetExport |
| **Authorizers** | CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer |
| **API Keys** | CreateApiKey, ImportApiKeys, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey |
| **Usage Plans** | CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, GetUsage |
@@ -310,7 +310,7 @@ These management-plane operations have no handler in v1. Calls will return `404`
- Model templates: `GetModelTemplate`
- Documentation parts and versions (the entire family, 10 operations)
- Client Certificates (5 operations)
-- `GetExport` / `ImportDocumentationParts`
+- `ImportDocumentationParts`
The execute plane (actual proxied HTTP traffic via `/restapis/{id}/{stage}/_user_request_/…`)
is implemented separately and is not counted as management-plane operations. A deployed REST
@@ -387,8 +387,46 @@ authorization settings, request parameters and models, method responses, and int
configuration. Resources without methods omit `resourceMethods`.
For example, `aws apigateway get-resources --rest-api-id <id> --embed methods` lists method
-metadata without a separate `get-method` call for each operation. Stage OpenAPI export
-(`GetExport`) is not implemented.
+metadata without a separate `get-method` call for each operation.
+
+### Stage OpenAPI Export
+
+`GetExport` returns a deployed REST API as OpenAPI 3.0 (`oas30`) or Swagger 2.0 (`swagger`).
+Set `Accept: application/json` (the default) or `application/yaml`. The response contains the
+specification body with `Content-Type` and `Content-Disposition` headers.
+
+```bash
+aws apigateway get-export --rest-api-id <id> --stage-name dev --export-type oas30 \
+ --parameters extensions=apigateway --accepts application/json api.json
+```
+
+By default, integration and authorizer definitions are omitted, while the authorization-type marker
+remains in each security scheme. A protected API exported without authorizer definitions cannot be
+safely re-imported: Floci returns `BadRequestException` before changing resources. For an importable
+protected definition, include `extensions=authorizers` or `extensions=apigateway`.
+Only schemes referenced by an operation's effective security requirements need a definition;
+unused schemes do not prevent re-import. Explicit operation security overrides API-level security,
+including an empty security list that makes the operation public.
+
+Request `extensions=integrations` or `extensions=authorizers` for the respective definitions;
+`extensions=apigateway` includes both, request validators, customized gateway responses, API policy
+and binary media types. Exports include stored methods (including ANY),
+request parameters and JSON models, response headers, security requirements, and supported integration
+settings. Exported integration types and passthrough settings use OpenAPI's lowercase spelling;
+import normalizes them to management API enum values.
+
+New deployments retain an export snapshot. Undeployed edits do not change it, and exporting another
+stage uses that stage's deployment. Deployment description updates preserve the snapshot. Older
+persisted deployments without a snapshot must be redeployed before export; Floci returns an explicit
+`BadRequestException` rather than exporting the live definition.
+
+This exports Floci's stored configuration, not the original uploaded document. Unsupported metadata,
+Postman extensions and full documentation exports are outside this operation's scope. Non-JSON models are rejected. Swagger supports only one body schema per
+operation, so methods using different request models per content type cannot be exported as Swagger;
+use `oas30` instead. Swagger response headers do not retain the method-response required flag.
+Integration responses must have distinct selection patterns to fit OpenAPI's response map. Duplicate
+patterns (including multiple default responses) and the literal regex `default`, which is reserved
+in that map, return `BadRequestException` rather than silently discarding or changing a response.
### Integration Settings
diff --git a/docs/services/index.md b/docs/services/index.md
index 39735a6ed6..910f22a12d 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -20,7 +20,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [DynamoDB Streams](dynamodb.md#streams) | `POST /` + `X-Amz-Target: DynamoDBStreams_20120810.*` | JSON 1.1 | 4 |
| [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 |
-| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 79 |
+| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 80 |
| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane |
| [IAM](iam.md) | `POST /` with `Action=` param | Query | 167 |
| [STS](sts.md) | `POST /` with `Action=` param | Query | 7 |
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
index 2ca2d08e59..c8878968be 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
@@ -1,10 +1,12 @@
package io.github.hectorvent.floci.services.apigateway;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.io.JsonStringEncoder;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService.StoredMapping;
@@ -274,6 +276,35 @@ public class ApiGatewayController {
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
+ @GET
+ @Path("/restapis/{apiId}/stages/{stageName}/exports/{exportType}")
+ @Produces({MediaType.APPLICATION_JSON, "application/yaml"})
+ public Response getExport(@Context HttpHeaders headers, @PathParam("apiId") String apiId,
+ @PathParam("stageName") String stageName, @PathParam("exportType") String exportType,
+ @QueryParam("extensions") String extensions) {
+ String region = regionResolver.resolveRegion(headers);
+ ObjectNode document = service.exportRestApi(region, apiId, stageName, exportType, extensions);
+ String contentType = MediaType.APPLICATION_JSON;
+ for (MediaType acceptable : headers.getAcceptableMediaTypes()) {
+ if (acceptable.isCompatible(MediaType.APPLICATION_JSON_TYPE)) {
+ break;
+ }
+ if (acceptable.isCompatible(MediaType.valueOf("application/yaml"))) {
+ contentType = "application/yaml";
+ break;
+ }
+ }
+ try {
+ String body = "application/yaml".equals(contentType)
+ ? new YAMLMapper().writeValueAsString(document) : document.toString();
+ return Response.ok(body).type(contentType)
+ .header("Content-Disposition", "attachment; filename=\"" + apiId + "-" + exportType
+ + ("application/yaml".equals(contentType) ? ".yaml" : ".json") + "\"").build();
+ } catch (JsonProcessingException e) {
+ throw new IllegalStateException("Cannot serialize API export", e);
+ }
+ }
+
@GET
@Path("/restapis/{apiId}/stages/{stageName}")
public Response getStage(@Context HttpHeaders headers,
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
index 1bcc8b770c..190773f5a3 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.apigateway;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -10,6 +11,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsPartition;
import io.github.hectorvent.floci.core.common.AwsPartitions;
+import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.CloudFrontEdgeDomain;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
@@ -25,6 +27,7 @@ import io.github.hectorvent.floci.services.apigateway.model.Authorizer;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import io.github.hectorvent.floci.services.apigateway.model.Deployment;
+import io.github.hectorvent.floci.services.apigateway.model.DeploymentExportSnapshot;
import io.github.hectorvent.floci.services.apigateway.model.EndpointConfiguration;
import io.github.hectorvent.floci.services.apigateway.model.EndpointType;
import io.github.hectorvent.floci.services.apigateway.model.GatewayResponse;
@@ -68,6 +71,7 @@ import java.util.HashSet;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
@@ -775,7 +779,16 @@ public class ApiGatewayService implements ResourceProvider {
public Deployment createDeployment(String region, String apiId, Map<String, Object> request) {
getRestApi(region, apiId);
String description = (String) request.getOrDefault("description", "");
- Deployment deployment = new Deployment(shortId(10), description, System.currentTimeMillis() / 1000L);
+ String snapshot;
+ try {
+ snapshot = JSON.writeValueAsString(new DeploymentExportSnapshot(getRestApi(region, apiId),
+ getResources(region, apiId), getModels(region, apiId), getAuthorizers(region, apiId),
+ getRequestValidators(region, apiId), getGatewayResponses(region, apiId).stream()
+ .filter(response -> !response.isDefaultResponse()).toList()));
+ } catch (JsonProcessingException e) {
+ throw new IllegalStateException("Cannot capture REST API deployment", e);
+ }
+ Deployment deployment = new Deployment(shortId(10), description, System.currentTimeMillis() / 1000L, snapshot);
deploymentStore.put(deploymentKey(region, apiId, deployment.id()), deployment);
LOG.infov("Created deployment {0} for API {1}", deployment.id(), apiId);
@@ -851,13 +864,48 @@ public class ApiGatewayService implements ResourceProvider {
}
newDescription = value;
}
- Deployment updated = new Deployment(existing.id(), newDescription, existing.createdDate());
+ Deployment updated = new Deployment(existing.id(), newDescription, existing.createdDate(), existing.exportSnapshot());
deploymentStore.put(deploymentKey(region, apiId, deploymentId), updated);
return updated;
}
return existing;
}
+ public ObjectNode exportRestApi(String region, String apiId, String stageName, String exportType,
+ String extensions) {
+ Stage stage = getStage(region, apiId, stageName);
+ if (!"oas30".equals(exportType) && !"swagger".equals(exportType)) {
+ throw new AwsException("BadRequestException", "Invalid export type: " + exportType, 400);
+ }
+ Set<String> selected = extensions == null || extensions.isBlank()
+ ? Set.of() : new HashSet<>(List.of(extensions.split(",")));
+ if (!Set.of("integrations", "authorizers", "apigateway").containsAll(selected)) {
+ throw new AwsException("BadRequestException", "Unsupported export extensions: " + extensions, 400);
+ }
+ Deployment deployment = getDeployment(region, apiId, stage.getDeploymentId());
+ if (deployment.exportSnapshot() == null) {
+ throw new AwsException("BadRequestException",
+ "This deployment predates export snapshots. Redeploy the API before exporting it.", 400);
+ }
+ try {
+ DeploymentExportSnapshot snapshot = JSON.readValue(deployment.exportSnapshot(), DeploymentExportSnapshot.class);
+ boolean all = selected.contains("apigateway");
+ ObjectNode document = RestApiOpenApiExporter.export(snapshot, "swagger".equals(exportType),
+ all || selected.contains("integrations"), all || selected.contains("authorizers"), all);
+ String host = apiId + ".execute-api." + region + "." + AwsRegions.dnsSuffixFor(region);
+ if ("swagger".equals(exportType)) {
+ document.put("host", host);
+ document.put("basePath", "/" + stageName);
+ document.putArray("schemes").add("https");
+ } else {
+ document.putArray("servers").addObject().put("url", "https://" + host + "/" + stageName);
+ }
+ return document;
+ } catch (JsonProcessingException e) {
+ throw new IllegalStateException("Cannot read REST API deployment snapshot", e);
+ }
+ }
+
// ──────────────────────────── Stages ────────────────────────────
public Stage createStage(String region, String apiId, Map<String, Object> request) {
@@ -3646,12 +3694,20 @@ public class ApiGatewayService implements ResourceProvider {
if (openAPI.getComponents() == null || openAPI.getComponents().getSecuritySchemes() == null) {
return;
}
- for (var entry : openAPI.getComponents().getSecuritySchemes().entrySet()) {
+ Set<String> referencedSchemes = referencedSecuritySchemes(openAPI);
+ for (Map.Entry<String, SecurityScheme> entry : openAPI.getComponents().getSecuritySchemes().entrySet()) {
String schemeName = entry.getKey();
SecurityScheme scheme = entry.getValue();
- importedAuthorizationType(scheme, schemeName);
+ String authorizationType = importedAuthorizationType(scheme, schemeName);
Map<String, Object> authDef = importedAuthorizerDefinition(scheme, schemeName);
if (authDef == null) {
+ if (referencedSchemes.contains(schemeName)
+ && ("custom".equalsIgnoreCase(authorizationType)
+ || "cognito_user_pools".equalsIgnoreCase(authorizationType))) {
+ throw new AwsException("BadRequestException",
+ "Missing authorizer definition for security scheme " + schemeName
+ + ". Export with extensions=authorizers or extensions=apigateway before importing.", 400);
+ }
continue;
}
String type = importedAuthorizerType(authDef, schemeName);
@@ -3669,6 +3725,30 @@ public class ApiGatewayService implements ResourceProvider {
}
}
+ private Set<String> referencedSecuritySchemes(OpenAPI openAPI) {
+ Set<String> schemes = new HashSet<>();
+ if (openAPI.getPaths() == null) {
+ return schemes;
+ }
+ for (Map.Entry<String, PathItem> entry : openAPI.getPaths().entrySet()) {
+ PathItem path = entry.getValue();
+ List<Operation> operations = new ArrayList<>(path.readOperations());
+ Object anyMethod = path.getExtensions() == null
+ ? null : path.getExtensions().get("x-amazon-apigateway-any-method");
+ if (anyMethod != null) {
+ operations.add(parseAnyMethodOperation(entry.getKey(), anyMethod));
+ }
+ for (Operation operation : operations) {
+ List<SecurityRequirement> requirements = operation.getSecurity() != null
+ ? operation.getSecurity() : openAPI.getSecurity();
+ if (requirements != null) {
+ requirements.forEach(requirement -> schemes.addAll(requirement.keySet()));
+ }
+ }
+ }
+ return schemes;
+ }
+
@SuppressWarnings("unchecked")
private Map<String, Object> importedAuthorizerDefinition(SecurityScheme scheme, String schemeName) {
if (scheme == null || scheme.getExtensions() == null) {
@@ -3850,6 +3930,16 @@ public class ApiGatewayService implements ResourceProvider {
String defaultValidatorId = null;
Map<String, Object> topExtensions = openAPI.getExtensions();
if (topExtensions != null) {
+ RestApi api = getRestApi(region, apiId);
+ Object binaryTypes = topExtensions.get("x-amazon-apigateway-binary-media-types");
+ if (binaryTypes instanceof List<?> types) {
+ api.setBinaryMediaTypes(types.stream().filter(String.class::isInstance).map(String.class::cast).toList());
+ }
+ Object policy = topExtensions.get("x-amazon-apigateway-policy");
+ if (policy != null) {
+ api.setPolicy(JSON.valueToTree(policy).toString());
+ }
+ apiStore.put(apiKey(region, apiId), api);
Map<String, Object> validators = (Map<String, Object>) topExtensions
.get("x-amazon-apigateway-request-validators");
if (validators != null) {
@@ -4206,6 +4296,19 @@ public class ApiGatewayService implements ResourceProvider {
if (integrationExt != null) {
applyIntegration(region, apiId, resourceId, httpMethod, integrationExt);
}
+ if (operation.getResponses() != null) {
+ operation.getResponses().forEach((status, response) -> {
+ if (!status.matches("[1-5][0-9]{2}")) {
+ return;
+ }
+ Map<String, Boolean> headers = new HashMap<>();
+ if (response.getHeaders() != null) {
+ response.getHeaders().forEach((name, header) ->
+ headers.put("method.response.header." + name, Boolean.TRUE.equals(header.getRequired())));
+ }
+ putMethodResponse(region, apiId, resourceId, httpMethod, status, Map.of("responseParameters", headers));
+ });
+ }
}
private static final String PARAMETER_REF_PREFIX = "#/components/parameters/";
@@ -4291,10 +4394,12 @@ public class ApiGatewayService implements ResourceProvider {
private void applyIntegration(String region, String apiId, String resourceId,
String httpMethod, Map<String, Object> integrationExt) {
Map<String, Object> integrationRequest = new HashMap<>();
- integrationRequest.put("type", integrationExt.get("type"));
+ Object integrationType = integrationExt.get("type");
+ integrationRequest.put("type", integrationType instanceof String type ? type.toUpperCase(Locale.ROOT) : integrationType);
integrationRequest.put("httpMethod", integrationExt.get("httpMethod"));
integrationRequest.put("uri", integrationExt.get("uri"));
- integrationRequest.put("passthroughBehavior", integrationExt.get("passthroughBehavior"));
+ Object passthrough = integrationExt.get("passthroughBehavior");
+ integrationRequest.put("passthroughBehavior", passthrough instanceof String behavior ? behavior.toUpperCase(Locale.ROOT) : passthrough);
for (String field : List.of("contentHandling", "timeoutInMillis", "connectionType",
"connectionId", "credentials", "cacheNamespace", "cacheKeyParameters", "tlsConfig",
"responseTransferMode")) {
@@ -4325,6 +4430,7 @@ public class ApiGatewayService implements ResourceProvider {
irRequest.put("selectionPattern", pattern);
irRequest.put("responseParameters", respDef.get("responseParameters"));
irRequest.put("responseTemplates", respDef.get("responseTemplates"));
+ irRequest.put("contentHandling", respDef.get("contentHandling"));
putIntegrationResponse(region, apiId, resourceId, httpMethod, statusCode, irRequest);
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/OpenApiSchemaNativeSupport.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/OpenApiSchemaNativeSupport.java
new file mode 100644
index 0000000000..e8ed127499
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/OpenApiSchemaNativeSupport.java
@@ -0,0 +1,10 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+import io.swagger.models.Model;
+import io.swagger.models.properties.Property;
+import io.swagger.v3.oas.models.media.Schema;
+
+/** Registers the model hierarchies Jackson reads and writes during OpenAPI import. */
+@RegisterForReflection(targets = {Model.class, Property.class, Schema.class}, registerFullHierarchy = true)
+public class OpenApiSchemaNativeSupport {}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/RestApiOpenApiExporter.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/RestApiOpenApiExporter.java
new file mode 100644
index 0000000000..d5a4a17b09
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/RestApiOpenApiExporter.java
@@ -0,0 +1,299 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+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.AwsException;
+import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
+import io.github.hectorvent.floci.services.apigateway.model.Authorizer;
+import io.github.hectorvent.floci.services.apigateway.model.DeploymentExportSnapshot;
+import io.github.hectorvent.floci.services.apigateway.model.GatewayResponse;
+import io.github.hectorvent.floci.services.apigateway.model.Integration;
+import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse;
+import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
+import io.github.hectorvent.floci.services.apigateway.model.MethodResponse;
+import io.github.hectorvent.floci.services.apigateway.model.Model;
+import io.github.hectorvent.floci.services.apigateway.model.RequestValidator;
+
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.TreeMap;
+
+/** Serializes the supported REST configuration retained by a deployment. */
+final class RestApiOpenApiExporter {
+ private static final ObjectMapper JSON = new ObjectMapper();
+
+ private RestApiOpenApiExporter() {
+ }
+
+ static ObjectNode export(DeploymentExportSnapshot snapshot, boolean swagger,
+ boolean integrations, boolean authorizers, boolean apigateway) {
+ ObjectNode document = JSON.createObjectNode();
+ document.put(swagger ? "swagger" : "openapi", swagger ? "2.0" : "3.0.1");
+ ObjectNode info = document.putObject("info");
+ info.put("title", snapshot.api().getName());
+ info.put("version", "1.0");
+ put(info, "description", snapshot.api().getDescription());
+ ObjectNode components = swagger ? document : document.putObject("components");
+ ObjectNode schemas = components.putObject(swagger ? "definitions" : "schemas");
+ for (Model model : snapshot.models()) {
+ if (!"application/json".equals(model.getContentType())) {
+ throw new AwsException("BadRequestException", "Only found non-JSON body models for " + model.getName(), 400);
+ }
+ try {
+ JsonNode schema = JSON.readTree(model.getSchema());
+ if (schema == null || !schema.isObject()) {
+ throw new AwsException("BadRequestException", "Invalid JSON body model: " + model.getName(), 400);
+ }
+ schemas.set(model.getName(), schema);
+ } catch (JsonProcessingException | IllegalArgumentException e) {
+ throw new AwsException("BadRequestException", "Invalid JSON body model: " + model.getName(), 400);
+ }
+ }
+ ObjectNode securitySchemes = components.putObject(swagger ? "securityDefinitions" : "securitySchemes");
+ Map<String, String> authorizerNames = new HashMap<>();
+ for (Authorizer authorizer : snapshot.authorizers()) {
+ authorizerNames.put(authorizer.getId(), authorizer.getName());
+ ObjectNode scheme = securitySchemes.putObject(authorizer.getName());
+ scheme.put("type", "apiKey");
+ scheme.put("in", "header");
+ String source = authorizer.getIdentitySource();
+ scheme.put("name", source != null && source.startsWith("method.request.header.")
+ ? source.substring("method.request.header.".length()) : "Authorization");
+ scheme.put("x-amazon-apigateway-authtype", "COGNITO_USER_POOLS".equals(authorizer.getType())
+ ? "cognito_user_pools" : "custom");
+ if (authorizers) {
+ ObjectNode definition = scheme.putObject("x-amazon-apigateway-authorizer");
+ definition.put("type", authorizer.getType().toLowerCase(Locale.ROOT));
+ put(definition, "authorizerUri", authorizer.getAuthorizerUri());
+ put(definition, "identitySource", source);
+ if (authorizer.getAuthorizerResultTtlInSeconds() != null) {
+ definition.put("authorizerResultTtlInSeconds",
+ Integer.parseInt(authorizer.getAuthorizerResultTtlInSeconds()));
+ }
+ if (authorizer.getProviderARNs() != null) {
+ definition.set("providerARNs", JSON.valueToTree(authorizer.getProviderARNs()));
+ }
+ }
+ }
+ Map<String, String> validators = new HashMap<>();
+ if (apigateway && !snapshot.validators().isEmpty()) {
+ ObjectNode definitions = document.putObject("x-amazon-apigateway-request-validators");
+ for (RequestValidator validator : snapshot.validators()) {
+ validators.put(validator.getId(), validator.getName());
+ ObjectNode definition = definitions.putObject(validator.getName());
+ definition.put("validateRequestBody", validator.isValidateRequestBody());
+ definition.put("validateRequestParameters", validator.isValidateRequestParameters());
+ }
+ }
+ String iamScheme = availableName(securitySchemes, "sigv4");
+ String keyScheme = availableName(securitySchemes, "api_key");
+ ObjectNode paths = document.putObject("paths");
+ for (ApiGatewayResource resource : snapshot.resources().stream()
+ .sorted(Comparator.comparing(ApiGatewayResource::getPath)).toList()) {
+ if (resource.getResourceMethods().isEmpty()) {
+ continue;
+ }
+ ObjectNode path = paths.putObject(resource.getPath());
+ for (Map.Entry<String, MethodConfig> entry : new TreeMap<>(resource.getResourceMethods()).entrySet()) {
+ MethodConfig method = entry.getValue();
+ ObjectNode operation = path.putObject("ANY".equals(entry.getKey())
+ ? "x-amazon-apigateway-any-method" : entry.getKey().toLowerCase(Locale.ROOT));
+ exportParameters(operation, method, swagger);
+ exportResponses(operation, method, swagger);
+ ObjectNode requirement = JSON.createObjectNode();
+ if ("AWS_IAM".equals(method.getAuthorizationType())) {
+ ObjectNode scheme = securitySchemes.putObject(iamScheme);
+ scheme.put("type", "apiKey");
+ scheme.put("name", "Authorization");
+ scheme.put("in", "header");
+ scheme.put("x-amazon-apigateway-authtype", "awsSigv4");
+ requirement.putArray(iamScheme);
+ } else if ("CUSTOM".equals(method.getAuthorizationType())
+ || "COGNITO_USER_POOLS".equals(method.getAuthorizationType())) {
+ String name = authorizerNames.get(method.getAuthorizerId());
+ if (name == null) {
+ throw new AwsException("BadRequestException",
+ "Missing authorizer for protected method " + entry.getKey() + " " + resource.getPath(), 400);
+ }
+ requirement.set(name, JSON.valueToTree(method.getAuthorizationScopes()));
+ }
+ if (method.isApiKeyRequired()) {
+ ObjectNode scheme = securitySchemes.putObject(keyScheme);
+ scheme.put("type", "apiKey");
+ scheme.put("name", "x-api-key");
+ scheme.put("in", "header");
+ requirement.putArray(keyScheme);
+ }
+ if (!requirement.isEmpty()) {
+ operation.putArray("security").add(requirement);
+ }
+ put(operation, "x-amazon-apigateway-request-validator", validators.get(method.getRequestValidatorId()));
+ if (integrations && method.getMethodIntegration() != null) {
+ operation.set("x-amazon-apigateway-integration", exportIntegration(method.getMethodIntegration()));
+ }
+ }
+ }
+ if (apigateway) {
+ if (!snapshot.api().getBinaryMediaTypes().isEmpty()) {
+ document.set("x-amazon-apigateway-binary-media-types", JSON.valueToTree(snapshot.api().getBinaryMediaTypes()));
+ }
+ if (snapshot.api().getPolicy() != null) {
+ try {
+ document.set("x-amazon-apigateway-policy", JSON.readTree(snapshot.api().getPolicy()));
+ } catch (JsonProcessingException e) {
+ throw new AwsException("BadRequestException", "Invalid JSON API policy", 400);
+ }
+ }
+ ObjectNode responses = document.putObject("x-amazon-apigateway-gateway-responses");
+ for (GatewayResponse response : snapshot.gatewayResponses()) {
+ if (!response.isDefaultResponse()) {
+ ObjectNode definition = responses.putObject(response.getResponseType());
+ put(definition, "statusCode", response.getStatusCode());
+ definition.set("responseParameters", JSON.valueToTree(response.getResponseParameters()));
+ definition.set("responseTemplates", JSON.valueToTree(response.getResponseTemplates()));
+ }
+ }
+ }
+ rewriteSchemaReferences(document, swagger);
+ return document;
+ }
+
+ private static void exportParameters(ObjectNode operation, MethodConfig method, boolean swagger) {
+ ArrayNode parameters = operation.putArray("parameters");
+ for (Map.Entry<String, Boolean> entry : new TreeMap<>(method.getRequestParameters()).entrySet()) {
+ String[] parts = entry.getKey().split("\\.", 4);
+ if (parts.length != 4) {
+ continue;
+ }
+ ObjectNode parameter = parameters.addObject();
+ parameter.put("name", parts[3]);
+ String location = "querystring".equals(parts[2]) ? "query" : parts[2];
+ parameter.put("in", location);
+ parameter.put("required", "path".equals(location) || Boolean.TRUE.equals(entry.getValue()));
+ if (swagger) {
+ parameter.put("type", "string");
+ } else {
+ parameter.putObject("schema").put("type", "string");
+ }
+ }
+ if (!method.getRequestModels().isEmpty()) {
+ if (swagger) {
+ if (method.getRequestModels().values().stream().distinct().count() != 1) {
+ throw new AwsException("BadRequestException", "Swagger export requires one request body model per method", 400);
+ }
+ ObjectNode body = parameters.addObject();
+ body.put("name", "body");
+ body.put("in", "body");
+ body.putObject("schema").put("$ref", "#/components/schemas/" + method.getRequestModels().values().iterator().next());
+ operation.set("consumes", JSON.valueToTree(method.getRequestModels().keySet()));
+ } else {
+ ObjectNode content = operation.putObject("requestBody").putObject("content");
+ method.getRequestModels().forEach((type, name) ->
+ content.putObject(type).putObject("schema").put("$ref", "#/components/schemas/" + name));
+ }
+ }
+ }
+
+ private static void exportResponses(ObjectNode operation, MethodConfig method, boolean swagger) {
+ ObjectNode responses = operation.putObject("responses");
+ for (MethodResponse response : new TreeMap<>(method.getMethodResponses()).values()) {
+ ObjectNode definition = responses.putObject(response.statusCode());
+ definition.put("description", response.statusCode() + " response");
+ if (response.responseParameters() != null && !response.responseParameters().isEmpty()) {
+ ObjectNode headers = definition.putObject("headers");
+ response.responseParameters().forEach((name, required) -> {
+ String prefix = "method.response.header.";
+ if (name.startsWith(prefix)) {
+ ObjectNode header = headers.putObject(name.substring(prefix.length()));
+ if (swagger) {
+ header.put("type", "string");
+ } else {
+ header.putObject("schema").put("type", "string");
+ header.put("required", Boolean.TRUE.equals(required));
+ }
+ }
+ });
+ }
+ }
+ if (responses.isEmpty()) {
+ responses.putObject("default").put("description", "Default response");
+ }
+ }
+
+ private static ObjectNode exportIntegration(Integration integration) {
+ ObjectNode node = JSON.createObjectNode();
+ node.put("type", integration.getType().toLowerCase(Locale.ROOT));
+ put(node, "uri", integration.getUri());
+ put(node, "httpMethod", integration.getHttpMethod());
+ put(node, "credentials", integration.getCredentials());
+ put(node, "passthroughBehavior", integration.getPassthroughBehavior() != null
+ ? integration.getPassthroughBehavior().toLowerCase(Locale.ROOT) : null);
+ put(node, "contentHandling", integration.getContentHandling());
+ put(node, "connectionType", integration.getConnectionType());
+ put(node, "connectionId", integration.getConnectionId());
+ put(node, "cacheNamespace", integration.getCacheNamespace());
+ node.set("cacheKeyParameters", JSON.valueToTree(integration.getCacheKeyParameters()));
+ node.set("requestParameters", JSON.valueToTree(integration.getRequestParameters()));
+ node.set("requestTemplates", JSON.valueToTree(integration.getRequestTemplates()));
+ if (integration.getTimeoutInMillis() != null) {
+ node.put("timeoutInMillis", integration.getTimeoutInMillis());
+ }
+ put(node, "responseTransferMode", integration.getResponseTransferMode());
+ if (integration.getTlsConfig() != null) {
+ node.putObject("tlsConfig").put("insecureSkipVerification", integration.getTlsConfig().isInsecureSkipVerification());
+ }
+ ObjectNode responses = node.putObject("responses");
+ for (IntegrationResponse response : new TreeMap<>(integration.getIntegrationResponses()).values()) {
+ String pattern = response.selectionPattern();
+ if ("default".equals(pattern)) {
+ throw new AwsException("BadRequestException",
+ "Cannot export the reserved integration response selection pattern 'default'", 400);
+ }
+ String key = pattern == null || pattern.isEmpty() ? "default" : pattern;
+ if (responses.has(key)) {
+ throw new AwsException("BadRequestException",
+ "Cannot export duplicate integration response selection pattern '" + key + "'", 400);
+ }
+ ObjectNode definition = responses.putObject(key);
+ definition.put("statusCode", response.statusCode());
+ definition.set("responseParameters", JSON.valueToTree(response.responseParameters()));
+ definition.set("responseTemplates", JSON.valueToTree(response.responseTemplates()));
+ put(definition, "contentHandling", response.contentHandling());
+ }
+ return node;
+ }
+
+ private static void rewriteSchemaReferences(JsonNode node, boolean swagger) {
+ if (node instanceof ObjectNode object) {
+ JsonNode ref = object.get("$ref");
+ String source = swagger ? "#/components/schemas/" : "#/definitions/";
+ String target = swagger ? "#/definitions/" : "#/components/schemas/";
+ if (ref != null && ref.isTextual() && ref.asText().startsWith(source)) {
+ object.put("$ref", ref.asText().replace(source, target));
+ }
+ }
+ for (JsonNode child : node) {
+ rewriteSchemaReferences(child, swagger);
+ }
+ }
+
+ private static String availableName(ObjectNode schemes, String preferred) {
+ String name = preferred;
+ int suffix = 1;
+ while (schemes.has(name)) {
+ name = preferred + "_" + suffix++;
+ }
+ return name;
+ }
+
+ private static void put(ObjectNode node, String field, String value) {
+ if (value != null) {
+ node.put(field, value);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/SwaggerParserNativeSupport.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/SwaggerParserNativeSupport.java
new file mode 100644
index 0000000000..180d5b8dc7
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/SwaggerParserNativeSupport.java
@@ -0,0 +1,8 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+import io.swagger.v3.parser.converter.SwaggerConverter;
+
+/** Keeps the Swagger 2.0 parser provider available for OpenAPIParser's ServiceLoader. */
+@RegisterForReflection(targets = SwaggerConverter.class, methods = false, fields = false, ignoreNested = true)
+public class SwaggerParserNativeSupport {}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Deployment.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Deployment.java
index 9b3a501f48..dc481023a8 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Deployment.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Deployment.java
@@ -8,6 +8,10 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
public record Deployment(
String id,
String description,
- long createdDate
+ long createdDate,
+ String exportSnapshot
) {
+ public Deployment(String id, String description, long createdDate) {
+ this(id, description, createdDate, null);
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/DeploymentExportSnapshot.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/DeploymentExportSnapshot.java
new file mode 100644
index 0000000000..d654775824
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/DeploymentExportSnapshot.java
@@ -0,0 +1,18 @@
+package io.github.hectorvent.floci.services.apigateway.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.List;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+@RegisterForReflection
+public record DeploymentExportSnapshot(
+ RestApi api,
+ List<ApiGatewayResource> resources,
+ List<Model> models,
+ List<Authorizer> authorizers,
+ List<RequestValidator> validators,
+ List<GatewayResponse> gatewayResponses
+) {
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index f639b9608d..d4c8c60bd5 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -35,6 +35,13 @@ quarkus:
# Enables the pre-shutdown phase so stop hooks run before the HTTP server stops.
# No 'delay' value is set - observers run synchronously, no artificial sleep is introduced.
delay-enabled: true
+ index-dependency:
+ swagger-models-v2:
+ group-id: io.swagger
+ artifact-id: swagger-models
+ swagger-models-v3:
+ group-id: io.swagger.core.v3
+ artifact-id: swagger-models
native:
# quarkus-jdbc-mysql used to force this. Without it the image has only UTF-8, UTF-16,
# ISO-8859-1 and US-ASCII, which breaks latin1 MySQL columns and non-UTF-8 mail bodies.
@@ -73,6 +80,8 @@ quarkus:
# DriverManager finds the JDBC drivers through ServiceLoader, and the MySQL
# driver reads its time zone table at connect time.
- META-INF/services/java.sql.Driver
+ # OpenAPIParser discovers the Swagger 2.0 converter through ServiceLoader.
+ - META-INF/services/io.swagger.v3.parser.core.extensions.SwaggerParserExtension
- com/mysql/cj/util/TimeZoneMapping.properties
# snappy-java registers 27 JNI libraries, one per platform. Only the one
# for the running platform loads, so 23 are dropped. Linux x86_64 and
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExportIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExportIntegrationTest.java
new file mode 100644
index 0000000000..d3603679ae
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExportIntegrationTest.java
@@ -0,0 +1,193 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
+import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
+import io.github.hectorvent.floci.services.apigateway.model.Authorizer;
+import io.github.hectorvent.floci.services.apigateway.model.Deployment;
+import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
+import io.github.hectorvent.floci.services.apigateway.model.RequestValidator;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.Response;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.*;
+
+@QuarkusTest
+class ApiGatewayExportIntegrationTest {
+ private static final String REGION = "us-east-1";
+ private static final ObjectMapper JSON = new ObjectMapper();
+ private static final String TEMPLATE = "{\"quote\":\"a\\\"b\",\"path\":\"$input.path('$')\"}";
+
+ @Inject
+ ApiGatewayService service;
+ private String apiId;
+ private String resourceId;
+ private String deploymentId;
+ private final List<String> imported = new ArrayList<>();
+
+ @BeforeEach
+ void createDeployedApi() {
+ apiId = service.createRestApi(REGION, Map.of("name", "export-fixture", "description", "Synthetic export",
+ "binaryMediaTypes", List.of("application/octet-stream"),
+ "policy", "{\"Version\":\"2012-10-17\",\"Statement\":[]}")).getId();
+ String rootId = service.getResources(REGION, apiId).get(0).getId();
+ resourceId = service.createResource(REGION, apiId, rootId, Map.of("pathPart", "widgets")).getId();
+ service.createModel(REGION, apiId, Map.of("name", "Widget", "contentType", "application/json",
+ "schema", "{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"}}}"));
+ RequestValidator validator = service.createRequestValidator(REGION, apiId,
+ Map.of("name", "body-and-parameters", "validateRequestBody", true, "validateRequestParameters", true));
+ service.putMethod(REGION, apiId, resourceId, "POST", Map.of("authorizationType", "AWS_IAM", "apiKeyRequired", true,
+ "requestValidatorId", validator.getId(), "requestModels", Map.of("application/json", "Widget"),
+ "requestParameters", Map.of("method.request.header.X-Trace", true, "method.request.querystring.limit", false)));
+ service.putIntegration(REGION, apiId, resourceId, "POST", Map.of("type", "MOCK", "timeoutInMillis", 9000,
+ "requestTemplates", Map.of("application/json", TEMPLATE)));
+ service.putMethodResponse(REGION, apiId, resourceId, "POST", "201",
+ Map.of("responseParameters", Map.of("method.response.header.X-Trace", false)));
+ service.putIntegrationResponse(REGION, apiId, resourceId, "POST", "201", Map.of("selectionPattern", "",
+ "responseParameters", Map.of("method.response.header.X-Trace", "'trace'"),
+ "responseTemplates", Map.of("application/json", TEMPLATE), "contentHandling", "CONVERT_TO_TEXT"));
+ Authorizer authorizer = service.createAuthorizer(REGION, apiId, Map.of("name", "TokenAuth", "type", "TOKEN",
+ "identitySource", "method.request.header.Authorization", "authorizerResultTtlInSeconds", 0,
+ "authorizerUri", "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:auth/invocations"));
+ service.putMethod(REGION, apiId, rootId, "ANY", Map.of("authorizationType", "CUSTOM", "authorizerId", authorizer.getId()));
+ service.putIntegration(REGION, apiId, rootId, "ANY", Map.of("type", "MOCK"));
+ service.putGatewayResponse(REGION, apiId, "DEFAULT_4XX", Map.of("responseTemplates", Map.of("application/json", TEMPLATE)));
+ service.putMethod(REGION, apiId, resourceId, "GET", Map.of("authorizationType", "NONE"));
+ service.putIntegration(REGION, apiId, resourceId, "GET", Map.of("type", "MOCK",
+ "requestTemplates", Map.of("application/json", "{\"statusCode\":200}")));
+ service.putMethodResponse(REGION, apiId, resourceId, "GET", "200", Map.of());
+ service.putIntegrationResponse(REGION, apiId, resourceId, "GET", "200",
+ Map.of("responseTemplates", Map.of("application/json", "{\"exported\":true}")));
+ deploymentId = service.createDeployment(REGION, apiId, Map.of("stageName", "dev")).id();
+ }
+
+ @AfterEach
+ void cleanup() {
+ imported.forEach(id -> service.deleteRestApi(REGION, id));
+ service.deleteRestApi(REGION, apiId);
+ }
+
+ @ParameterizedTest
+ @CsvSource({"oas30,application/json", "swagger,application/json", "oas30,application/yaml", "swagger,application/yaml"})
+ void exportedStageReimportsSupportedConfiguration(String type, String accepts) throws Exception {
+ Response response = given().accept(accepts).queryParam("extensions", "apigateway")
+ .get(exportPath("dev", type)).then().statusCode(200)
+ .header("Content-Type", containsString(accepts)).header("Content-Disposition", containsString("attachment"))
+ .extract().response();
+ JsonNode document = parse(response.asString(), accepts);
+ assertEquals(type.equals("swagger") ? "2.0" : "3.0.1", document.path(type.equals("swagger") ? "swagger" : "openapi").asText());
+ assertEquals(TEMPLATE, document.at("/paths/~1widgets/post/x-amazon-apigateway-integration/requestTemplates/application~1json").asText());
+ assertTrue(document.at("/paths/~1/x-amazon-apigateway-any-method").isObject());
+ String restoredId = given().contentType(accepts).queryParam("mode", "import").body(response.asByteArray())
+ .post("/restapis").then().statusCode(201).extract().path("id");
+ imported.add(restoredId);
+ ApiGatewayResource widgets = service.getResources(REGION, restoredId).stream()
+ .filter(resource -> "/widgets".equals(resource.getPath())).findFirst().orElseThrow();
+ MethodConfig method = widgets.getResourceMethods().get("POST");
+ assertEquals(List.of("application/octet-stream"), service.getRestApi(REGION, restoredId).getBinaryMediaTypes());
+ assertEquals(JSON.readTree(service.getRestApi(REGION, apiId).getPolicy()),
+ JSON.readTree(service.getRestApi(REGION, restoredId).getPolicy()));
+ assertEquals("AWS_IAM", method.getAuthorizationType());
+ assertTrue(method.isApiKeyRequired());
+ assertEquals(Map.of("method.request.header.X-Trace", true, "method.request.querystring.limit", false), method.getRequestParameters());
+ assertEquals(Map.of("application/json", "Widget"), method.getRequestModels());
+ assertEquals("body-and-parameters", service.getRequestValidator(REGION, restoredId, method.getRequestValidatorId()).getName());
+ assertEquals(Map.of("method.response.header.X-Trace", false), method.getMethodResponses().get("201").responseParameters());
+ assertEquals(TEMPLATE, method.getMethodIntegration().getRequestTemplates().get("application/json"));
+ assertEquals(9000, method.getMethodIntegration().getTimeoutInMillis());
+ assertEquals("CONVERT_TO_TEXT", method.getMethodIntegration().getIntegrationResponses().get("201").contentHandling());
+ ApiGatewayResource root = service.getResources(REGION, restoredId).stream()
+ .filter(resource -> "/".equals(resource.getPath())).findFirst().orElseThrow();
+ MethodConfig any = root.getResourceMethods().get("ANY");
+ assertEquals("CUSTOM", any.getAuthorizationType());
+ assertEquals("TokenAuth", service.getAuthorizer(REGION, restoredId, any.getAuthorizerId()).getName());
+ assertEquals(TEMPLATE, service.getGatewayResponse(REGION, restoredId, "DEFAULT_4XX").getResponseTemplates().get("application/json"));
+ service.createDeployment(REGION, restoredId, Map.of("stageName", "dev"));
+ given().accept("application/json").get("/restapis/" + restoredId + "/dev/_user_request_/widgets")
+ .then().statusCode(200).body("exported", equalTo(true));
+ assertTrue(JSON.readTree(service.getModel(REGION, restoredId, "Widget").getSchema()).path("properties").has("name"));
+ }
+
+ @Test
+ void extensionSelectionAndDefaultJsonAreRespected() throws Exception {
+ JsonNode basic = JSON.readTree(given().get(exportPath("dev", "oas30")).then().statusCode(200).extract().asString());
+ assertFalse(basic.at("/paths/~1widgets/post").has("x-amazon-apigateway-integration"));
+ assertFalse(basic.at("/components/securitySchemes/TokenAuth").has("x-amazon-apigateway-authorizer"));
+ assertFalse(basic.has("x-amazon-apigateway-request-validators"));
+ JsonNode integrations = JSON.readTree(given().queryParam("extensions", "integrations")
+ .get(exportPath("dev", "oas30")).then().statusCode(200).extract().asString());
+ assertTrue(integrations.at("/paths/~1widgets/post").has("x-amazon-apigateway-integration"));
+ assertFalse(integrations.at("/components/securitySchemes/TokenAuth").has("x-amazon-apigateway-authorizer"));
+ JsonNode auth = JSON.readTree(given().queryParam("extensions", "authorizers")
+ .get(exportPath("dev", "oas30")).then().statusCode(200).extract().asString());
+ assertTrue(auth.at("/components/securitySchemes/TokenAuth").has("x-amazon-apigateway-authorizer"));
+ assertFalse(auth.at("/paths/~1widgets/post").has("x-amazon-apigateway-integration"));
+ }
+
+ @Test
+ void exportUsesSelectedDeploymentAndSurvivesDescriptionPatch() throws Exception {
+ service.updateDeployment(REGION, apiId, deploymentId, List.of(Map.of("op", "replace", "path", "/description", "value", "new description")));
+ service.updateModel(REGION, apiId, "Widget", List.of(Map.of("op", "replace", "path", "/schema", "value", "{\"type\":\"integer\"}")));
+ assertEquals("object", JSON.readTree(given().queryParam("extensions", "apigateway").get(exportPath("dev", "oas30"))
+ .then().statusCode(200).extract().asString()).at("/components/schemas/Widget/type").asText());
+ service.deleteMethod(REGION, apiId, resourceId, "POST");
+ assertTrue(JSON.readTree(given().get(exportPath("dev", "oas30")).then().statusCode(200).extract().asString())
+ .at("/paths/~1widgets/post").isObject());
+ service.deleteMethod(REGION, apiId, resourceId, "GET");
+ service.createDeployment(REGION, apiId, Map.of("stageName", "next"));
+ assertFalse(JSON.readTree(given().get(exportPath("next", "oas30")).then().statusCode(200).extract().asString())
+ .path("paths").has("/widgets"));
+ service.updateStage(REGION, apiId, "dev", List.of(Map.of("op", "replace", "path", "/deploymentId", "value",
+ service.getStage(REGION, apiId, "next").getDeploymentId())));
+ assertFalse(JSON.readTree(given().get(exportPath("dev", "oas30")).then().statusCode(200).extract().asString())
+ .path("paths").has("/widgets"));
+ }
+
+ @Test
+ void invalidFormatsAndMissingResourcesReturnManagementErrors() {
+ given().get(exportPath("dev", "invalid")).then().statusCode(400);
+ given().queryParam("extensions", "invalid").get(exportPath("dev", "oas30")).then().statusCode(400);
+ given().get(exportPath("missing", "oas30")).then().statusCode(404);
+ given().get("/restapis/missing/stages/dev/exports/oas30").then().statusCode(404);
+ }
+
+ @Test
+ void deploymentSnapshotSurvivesJacksonStorageRoundTrip() throws Exception {
+ Deployment original = service.getDeployment(REGION, apiId, deploymentId);
+ Deployment restored = JSON.readValue(JSON.writeValueAsString(original), Deployment.class);
+ assertEquals(original.exportSnapshot(), restored.exportSnapshot());
+ Deployment legacy = JSON.readValue("{\"id\":\"old\",\"description\":\"old\",\"createdDate\":1}", Deployment.class);
+ assertNull(legacy.exportSnapshot());
+ }
+
+ @Test
+ void nonJsonModelsFailAtExportWithoutPreventingDeployment() {
+ service.createModel(REGION, apiId, Map.of("name", "XmlBody", "contentType", "application/xml", "schema", "{}"));
+ service.createDeployment(REGION, apiId, Map.of("stageName", "xml"));
+ given().get(exportPath("xml", "oas30")).then().statusCode(400).body("message", containsString("non-JSON"));
+ given().get("/restapis/" + apiId + "/deployments/" + deploymentId).then().statusCode(200)
+ .body("exportSnapshot", org.hamcrest.Matchers.nullValue());
+ }
+
+ private String exportPath(String stage, String type) {
+ return "/restapis/" + apiId + "/stages/" + stage + "/exports/" + type;
+ }
+
+ private JsonNode parse(String body, String type) throws Exception {
+ return type.equals("application/yaml") ? new YAMLMapper().readTree(body) : JSON.readTree(body);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExportServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExportServiceTest.java
new file mode 100644
index 0000000000..51dad207f9
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExportServiceTest.java
@@ -0,0 +1,206 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.config.TlsCertificateManager;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.apigateway.model.Authorizer;
+import io.github.hectorvent.floci.services.apigateway.model.Deployment;
+import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+class ApiGatewayExportServiceTest {
+ private static final String REGION = "us-east-1";
+ private AccountAwareStorageBackend<Deployment> deployments;
+ private ApiGatewayService service;
+
+ @BeforeEach
+ void setup() {
+ deployments = AccountAwareStorageBackend.inMemory("000000000000");
+ StorageFactory factory = mock(StorageFactory.class);
+ when(factory.create(anyString(), anyString(), any())).thenAnswer(invocation ->
+ "apigateway-deployments.json".equals(invocation.getArgument(1))
+ ? deployments : AccountAwareStorageBackend.inMemory("000000000000"));
+ service = new ApiGatewayService(factory, mock(EmulatorConfig.class), mock(TlsCertificateManager.class),
+ new RegionResolver(REGION, "000000000000"));
+ }
+
+ @Test
+ void legacyDeploymentRequiresRedeploymentRatherThanExportingLiveMethods() {
+ String apiId = service.createRestApi(REGION, Map.of("name", "legacy")).getId();
+ deployments.put(REGION + "::" + apiId + "::old", new Deployment("old", "legacy", 1));
+ service.createStage(REGION, apiId, Map.of("stageName", "dev", "deploymentId", "old"));
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.exportRestApi(REGION, apiId, "dev", "oas30", null));
+ assertTrue(error.getMessage().contains("Redeploy"));
+ service.createDeployment(REGION, apiId, Map.of("stageName", "dev"));
+ assertNotNull(service.exportRestApi(REGION, apiId, "dev", "oas30", null));
+ }
+
+ @Test
+ void generatedSecurityNamesDoNotOverwriteAuthorizers() {
+ String apiId = service.createRestApi(REGION, Map.of("name", "scheme-collision")).getId();
+ String rootId = service.getResources(REGION, apiId).get(0).getId();
+ Authorizer authorizer = service.createAuthorizer(REGION, apiId, Map.of("name", "sigv4", "type", "TOKEN",
+ "authorizerUri", "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:auth/invocations"));
+ service.putMethod(REGION, apiId, rootId, "GET", Map.of("authorizationType", "CUSTOM", "authorizerId", authorizer.getId()));
+ service.putMethod(REGION, apiId, rootId, "POST", Map.of("authorizationType", "AWS_IAM"));
+ service.createDeployment(REGION, apiId, Map.of("stageName", "dev"));
+ JsonNode exported = service.exportRestApi(REGION, apiId, "dev", "oas30", "apigateway");
+ assertTrue(exported.at("/components/securitySchemes/sigv4").has("x-amazon-apigateway-authorizer"));
+ assertEquals("awsSigv4", exported.at("/components/securitySchemes/sigv4_1/x-amazon-apigateway-authtype").asText());
+ assertTrue(exported.at("/paths/~1/get/security/0").has("sigv4"));
+ assertTrue(exported.at("/paths/~1/post/security/0").has("sigv4_1"));
+ }
+ @ParameterizedTest
+ @CsvSource({"TOKEN,oas30", "TOKEN,swagger", "COGNITO_USER_POOLS,oas30", "COGNITO_USER_POOLS,swagger"})
+ void incompleteAuthorizerExportCannotBeImportedAsApiKey(String kind, String format) {
+ String apiId = protectedApi(kind);
+ JsonNode document = service.exportRestApi(REGION, apiId, "dev", format, null);
+ String schemes = "swagger".equals(format) ? "securityDefinitions" : "components/securitySchemes";
+ assertEquals("TOKEN".equals(kind) ? "custom" : "cognito_user_pools",
+ document.at("/" + schemes + "/Protected/x-amazon-apigateway-authtype").asText());
+ assertFalse(document.at("/" + schemes + "/Protected").has("x-amazon-apigateway-authorizer"));
+ int before = service.getRestApis(REGION).size();
+ AwsException rejected = assertThrows(AwsException.class,
+ () -> service.importRestApi(REGION, document.toString()));
+ assertTrue(rejected.getMessage().contains("authorizer definition"));
+ assertEquals(before, service.getRestApis(REGION).size());
+ assertThrows(AwsException.class,
+ () -> service.putRestApi(REGION, apiId, "overwrite", document.toString()));
+ MethodConfig original = service.getResources(REGION, apiId).get(0).getResourceMethods().get("GET");
+ assertEquals("TOKEN".equals(kind) ? "CUSTOM" : kind, original.getAuthorizationType());
+ assertFalse(original.isApiKeyRequired());
+ }
+
+ @ParameterizedTest
+ @CsvSource({"TOKEN,oas30,authorizers", "TOKEN,swagger,apigateway",
+ "COGNITO_USER_POOLS,oas30,apigateway", "COGNITO_USER_POOLS,swagger,authorizers"})
+ void fullAuthorizerExportPreservesAuthorizationAndScopes(String kind, String format, String extensions) {
+ String apiId = protectedApi(kind);
+ JsonNode document = service.exportRestApi(REGION, apiId, "dev", format, extensions);
+ String restoredId = service.importRestApi(REGION, document.toString()).getId();
+ MethodConfig method = service.getResources(REGION, restoredId).get(0).getResourceMethods().get("GET");
+ assertEquals("TOKEN".equals(kind) ? "CUSTOM" : kind, method.getAuthorizationType());
+ assertFalse(method.isApiKeyRequired());
+ assertEquals("TOKEN".equals(kind) ? List.of() : List.of("widgets/read", "widgets/write"), method.getAuthorizationScopes());
+ Authorizer original = service.getAuthorizers(REGION, apiId).get(0);
+ Authorizer restored = service.getAuthorizer(REGION, restoredId, method.getAuthorizerId());
+ assertEquals(original.getType(), restored.getType());
+ assertEquals(original.getProviderARNs(), restored.getProviderARNs());
+ assertEquals(original.getAuthorizerUri(), restored.getAuthorizerUri());
+ assertEquals(original.getIdentitySource(), restored.getIdentitySource());
+ }
+
+ @ParameterizedTest
+ @CsvSource(value = {"oas30|", "swagger|", "oas30|4[0-9]{2}", "swagger|4[0-9]{2}",
+ "oas30|default", "swagger|default"}, delimiter = '|')
+ void duplicateResponsePatternsFailExplicitly(String format, String configuredPattern) {
+ String apiId = service.createRestApi(REGION, Map.of("name", "duplicate-responses")).getId();
+ String rootId = service.getResources(REGION, apiId).get(0).getId();
+ service.putMethod(REGION, apiId, rootId, "GET", Map.of("authorizationType", "NONE"));
+ service.putIntegration(REGION, apiId, rootId, "GET", Map.of("type", "MOCK"));
+ String pattern = configuredPattern == null ? "" : configuredPattern;
+ service.putIntegrationResponse(REGION, apiId, rootId, "GET", "200",
+ Map.of("selectionPattern", pattern, "responseTemplates", Map.of("application/json", "first")));
+ service.putIntegrationResponse(REGION, apiId, rootId, "GET", "400",
+ Map.of("selectionPattern", pattern, "responseTemplates", Map.of("application/json", "second")));
+ service.createDeployment(REGION, apiId, Map.of("stageName", "dev"));
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.exportRestApi(REGION, apiId, "dev", format, "integrations"));
+ assertTrue(error.getMessage().contains("selection pattern"));
+ assertEquals(2, service.getIntegration(REGION, apiId, rootId, "GET").getIntegrationResponses().size());
+ }
+
+ @ParameterizedTest
+ @CsvSource({"CUSTOM,oas30", "COGNITO_USER_POOLS,swagger"})
+ void missingStoredAuthorizerCannotProduceAnUnprotectedExport(String authorization, String format) {
+ String apiId = service.createRestApi(REGION, Map.of("name", "missing-authorizer")).getId();
+ String rootId = service.getResources(REGION, apiId).get(0).getId();
+ service.putMethod(REGION, apiId, rootId, "GET", Map.of("authorizationType", authorization));
+ service.createDeployment(REGION, apiId, Map.of("stageName", "dev"));
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.exportRestApi(REGION, apiId, "dev", format, "authorizers"));
+ assertTrue(error.getMessage().contains("Missing authorizer for protected method"));
+ }
+
+ @ParameterizedTest
+ @CsvSource({"TOKEN,oas30", "TOKEN,swagger", "COGNITO_USER_POOLS,oas30", "COGNITO_USER_POOLS,swagger"})
+ void unusedAuthorizerDoesNotBlockDefaultExportImportOrOverwrite(String kind, String format) {
+ String apiId = protectedApi(kind);
+ String rootId = service.getResources(REGION, apiId).get(0).getId();
+ service.putMethod(REGION, apiId, rootId, "GET", Map.of("authorizationType", "NONE"));
+ service.createDeployment(REGION, apiId, Map.of("stageName", "dev"));
+ JsonNode document = service.exportRestApi(REGION, apiId, "dev", format, null);
+ String restoredId = service.importRestApi(REGION, document.toString()).getId();
+ MethodConfig restored = service.getResources(REGION, restoredId).get(0).getResourceMethods().get("GET");
+ assertEquals("NONE", restored.getAuthorizationType());
+ assertFalse(restored.isApiKeyRequired());
+ service.putRestApi(REGION, apiId, "overwrite", document.toString());
+ assertEquals("NONE", service.getResources(REGION, apiId).get(0).getResourceMethods().get("GET").getAuthorizationType());
+ }
+
+ @ParameterizedTest
+ @CsvSource({"get,false", "get,true", "x-amazon-apigateway-any-method,false", "x-amazon-apigateway-any-method,true"})
+ void incompleteAuthorizerCheckUsesEffectiveOperationSecurity(String verb, boolean overrideSecurity) {
+ String document = """
+ {
+ "openapi": "3.0.1", "info": {"title": "user-definition", "version": "1"},
+ "components": {"securitySchemes": {"Unused": {
+ "type": "apiKey", "in": "header", "name": "Authorization",
+ "x-amazon-apigateway-authtype": "custom"
+ }}},
+ "security": [{"Unused": []}],
+ "paths": {"/": {"%s": {
+ %s
+ "responses": {"200": {"description": "OK"}}
+ }}}
+ }
+ """.formatted(verb, overrideSecurity ? "\"security\": []," : "");
+ if (overrideSecurity) {
+ String apiId = service.importRestApi(REGION, document).getId();
+ MethodConfig method = service.getResources(REGION, apiId).get(0).getResourceMethods()
+ .get("get".equals(verb) ? "GET" : "ANY");
+ assertEquals("NONE", method.getAuthorizationType());
+ assertFalse(method.isApiKeyRequired());
+ } else {
+ AwsException rejected = assertThrows(AwsException.class, () -> service.importRestApi(REGION, document));
+ assertTrue(rejected.getMessage().contains("authorizer definition"));
+ }
+ }
+
+ private String protectedApi(String kind) {
+ String apiId = service.createRestApi(REGION, Map.of("name", "protected-export")).getId();
+ String rootId = service.getResources(REGION, apiId).get(0).getId();
+ Map<String, Object> request = new HashMap<>();
+ request.put("name", "Protected");
+ request.put("type", kind);
+ request.put("identitySource", "method.request.header.Authorization");
+ if ("TOKEN".equals(kind)) {
+ request.put("authorizerUri", "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:auth/invocations");
+ } else {
+ request.put("providerARNs", List.of("arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_fixture"));
+ }
+ Authorizer authorizer = service.createAuthorizer(REGION, apiId, request);
+ service.putMethod(REGION, apiId, rootId, "GET", Map.of("authorizationType", "TOKEN".equals(kind) ? "CUSTOM" : kind,
+ "authorizerId", authorizer.getId(), "authorizationScopes", "TOKEN".equals(kind)
+ ? List.of() : List.of("widgets/read", "widgets/write")));
+ service.createDeployment(REGION, apiId, Map.of("stageName", "dev"));
+ return apiId;
+ }
+
+}