Skip to content

armgit / floci

Public Imported from GitHub
0

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

refactor(cloudformation): move ApiGateway v1 core types into ApiGatewayRestApiCfnProvisioner (#3885)

Hector Ventura25fc8e452f7a
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
index 877a84d424..c4595c77d0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.OpenApiDocuments;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ReplacementCleanup;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
@@ -24,7 +25,6 @@ import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion;
import io.github.hectorvent.floci.services.pipes.model.DesiredState;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.model.Parameter;
-import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.apigatewayv2.model.*;
import io.github.hectorvent.floci.config.EmulatorConfig;
@@ -105,12 +105,6 @@ public class CloudFormationResourceProvisioner {
* {@code CfnResourceInventoryTest}.
*/
static final Set<String> LEGACY_SWITCH_TYPES = Set.of(
- "AWS::ApiGateway::Authorizer",
- "AWS::ApiGateway::Deployment",
- "AWS::ApiGateway::Method",
- "AWS::ApiGateway::Resource",
- "AWS::ApiGateway::RestApi",
- "AWS::ApiGateway::Stage",
"AWS::ApiGatewayV2::Api",
"AWS::ApiGatewayV2::Authorizer",
"AWS::ApiGatewayV2::Deployment",
@@ -140,7 +134,6 @@ public class CloudFormationResourceProvisioner {
private final S3Service s3Service;
private final LambdaService lambdaService;
private final IamService iamService;
- private final ApiGatewayService apiGatewayService;
private final ApiGatewayV2Service apiGatewayV2Service;
private final LambdaLayerService lambdaLayerService;
private final ObjectMapper objectMapper;
@@ -158,7 +151,6 @@ public class CloudFormationResourceProvisioner {
public CloudFormationResourceProvisioner(S3Service s3Service,
LambdaService lambdaService,
IamService iamService,
- ApiGatewayService apiGatewayService,
ApiGatewayV2Service apiGatewayV2Service,
LambdaLayerService lambdaLayerService,
ObjectMapper objectMapper,
@@ -172,7 +164,6 @@ public class CloudFormationResourceProvisioner {
this.s3Service = s3Service;
this.lambdaService = lambdaService;
this.iamService = iamService;
- this.apiGatewayService = apiGatewayService;
this.apiGatewayV2Service = apiGatewayV2Service;
this.lambdaLayerService = lambdaLayerService;
this.objectMapper = objectMapper;
@@ -240,12 +231,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::IAM::ManagedPolicy" ->
provisionIamManagedPolicy(resource, properties, engine, accountId, stackName);
case "AWS::IAM::InstanceProfile" -> provisionInstanceProfile(resource, properties, engine, accountId, stackName);
- case "AWS::ApiGateway::RestApi" -> provisionApiGatewayRestApi(resource, properties, engine, region, accountId, stackName);
- case "AWS::ApiGateway::Resource" -> provisionApiGatewayResource(resource, properties, engine, region);
- case "AWS::ApiGateway::Authorizer" -> provisionApiGatewayAuthorizer(resource, properties, engine, region);
- case "AWS::ApiGateway::Method" -> provisionApiGatewayMethod(resource, properties, engine, region);
- case "AWS::ApiGateway::Deployment" -> provisionApiGatewayDeployment(resource, properties, engine, region);
- case "AWS::ApiGateway::Stage" -> provisionApiGatewayStage(resource, properties, engine, region);
case "AWS::ApiGatewayV2::Api" -> provisionApiGatewayV2Api(resource, properties, engine, region, accountId, stackName);
case "AWS::ApiGatewayV2::Authorizer" -> provisionApiGatewayV2Authorizer(resource, properties, engine, region);
case "AWS::ApiGatewayV2::Route" -> provisionApiGatewayV2Route(resource, properties, engine, region);
@@ -466,7 +451,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::IAM::ManagedPolicy" -> deletePolicySafe(physicalId);
case "AWS::IAM::InstanceProfile" -> iamService.deleteInstanceProfile(physicalId);
// No bus context on the type/physicalId path (e.g. CREATE-rollback); targets the default bus.
- case "AWS::ApiGateway::RestApi" -> apiGatewayService.deleteRestApi(region, physicalId);
case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId);
case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region);
case "AWS::EKS::Cluster" -> eksService.deleteCluster(physicalId);
@@ -1713,156 +1697,6 @@ public class CloudFormationResourceProvisioner {
// ── ApiGateway (V1) ──────────────────────────────────────────────────────
- private void provisionApiGatewayRestApi(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region, String accountId, String stackName) {
- String name = resolveOptional(props, "Name", engine);
- if (name == null || name.isBlank()) {
- name = generatePhysicalName(stackName, r.getLogicalId(), 255, false);
- }
- String description = resolveOptional(props, "Description", engine);
- Map<String, Object> req = new HashMap<>();
- req.put("name", name);
- req.put("description", description);
-
- if (props.has("EndpointConfiguration")) {
- JsonNode epNode = props.get("EndpointConfiguration");
- Map<String, Object> epReq = new HashMap<>();
- epReq.put("types", resolveStringListOrEmpty(epNode, "Types", engine));
- epReq.put("vpcEndpointIds", resolveStringListOrEmpty(epNode, "VpcEndpointIds", engine));
- req.put("endpointConfiguration", epReq);
- }
-
- var api = apiGatewayService.createRestApi(region, req);
- r.setPhysicalId(api.getId());
- r.getAttributes().put("RootResourceId", apiGatewayService.getResources(region, api.getId()).get(0).getId());
-
- // A declared Body or BodyS3Location is the whole OpenAPI document: measured against real
- // AWS, us-east-1, create-change-set, it becomes the RestApi's Body with no synthesized
- // AWS::ApiGateway::Resource or AWS::ApiGateway::Method, so the working OpenAPI
- // materializer (putRestApi + applyOpenApiSpec) is the only place that turns it into
- // resources and methods. The same probe's processed template keeps a declared Name and
- // Description in their own properties even when Body.info carries a different title or
- // description, but putRestApi overwrites both from the document's info, so the resolved
- // Name and Description (null when Description is undeclared, clearing what putRestApi
- // just set) are re-applied immediately after.
- JsonNode openApiDocument = resolveOpenApiDocument(props, engine);
- if (openApiDocument != null) {
- apiGatewayService.putRestApi(region, api.getId(), "overwrite", openApiDocument.toString());
- apiGatewayService.updateRestApi(region, api.getId(),
- List.of(replacePatchOp("/name", name), replacePatchOp("/description", description)));
- }
- }
-
- /**
- * A {@code replace} patch operation for {@link ApiGatewayService#updateRestApi}, allowing a
- * {@code null} value ({@code Map.of} rejects one) so an undeclared property can still be
- * cleared rather than left at whatever {@code putRestApi} last wrote to it.
- */
- private Map<String, String> replacePatchOp(String path, String value) {
- Map<String, String> op = new HashMap<>();
- op.put("op", "replace");
- op.put("path", path);
- op.put("value", value);
- return op;
- }
-
- private void provisionApiGatewayResource(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region) {
- String apiId = resolveOptional(props, "RestApiId", engine);
- String parentId = resolveOptional(props, "ParentId", engine);
- String pathPart = resolveOptional(props, "PathPart", engine);
-
- Map<String, Object> req = new HashMap<>();
- req.put("pathPart", pathPart);
-
- var res = apiGatewayService.createResource(region, apiId, parentId, req);
- r.setPhysicalId(res.getId());
- }
-
- private void provisionApiGatewayAuthorizer(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region) {
- String apiId = resolveOptional(props, "RestApiId", engine);
- Map<String, Object> req = new HashMap<>();
- req.put("name", resolveOptional(props, "Name", engine));
- req.put("type", resolveOptional(props, "Type", engine));
- req.put("authorizerUri", resolveOptional(props, "AuthorizerUri", engine));
- req.put("identitySource", resolveOptional(props, "IdentitySource", engine));
- String ttl = resolveOptional(props, "AuthorizerResultTtlInSeconds", engine);
- if (ttl != null) {
- req.put("authorizerResultTtlInSeconds", ttl);
- }
- var authorizer = apiGatewayService.createAuthorizer(region, apiId, req);
- r.setPhysicalId(authorizer.getId());
- }
-
- private void provisionApiGatewayMethod(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region) {
- String apiId = resolveOptional(props, "RestApiId", engine);
- String resourceId = resolveOptional(props, "ResourceId", engine);
- String httpMethod = resolveOptional(props, "HttpMethod", engine);
-
- Map<String, Object> req = new HashMap<>();
- req.put("authorizationType", resolveOrDefault(props, "AuthorizationType", engine, "NONE"));
- String authorizerId = resolveOptional(props, "AuthorizerId", engine);
- if (authorizerId != null) {
- req.put("authorizerId", authorizerId);
- }
- req.put("apiKeyRequired", Boolean.parseBoolean(resolveOrDefault(props, "ApiKeyRequired", engine, "false")));
-
- apiGatewayService.putMethod(region, apiId, resourceId, httpMethod, req);
- r.setPhysicalId(apiId + "-" + resourceId + "-" + httpMethod);
-
- // Provision integration if present
- if (props != null && props.has("Integration")) {
- JsonNode integNode = engine.resolveNode(props.get("Integration"));
- Map<String, Object> integReq = new HashMap<>();
- integReq.put("type", resolveOptional(integNode, "Type", engine));
- integReq.put("httpMethod", resolveOptional(integNode, "IntegrationHttpMethod", engine));
- integReq.put("uri", resolveOptional(integNode, "Uri", engine));
-
- apiGatewayService.putIntegration(region, apiId, resourceId, httpMethod, integReq);
- }
- }
-
- private void provisionApiGatewayDeployment(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region) {
- String apiId = resolveOptional(props, "RestApiId", engine);
- Map<String, Object> req = new HashMap<>();
- req.put("description", resolveOptional(props, "Description", engine));
-
- var deployment = apiGatewayService.createDeployment(region, apiId, req);
- r.setPhysicalId(deployment.id());
-
- // AWS::ApiGateway::Deployment accepts an inline StageName: when present, AWS creates that
- // stage pointing at this deployment, with no separate AWS::ApiGateway::Stage resource.
- String stageName = resolveOptional(props, "StageName", engine);
- if (stageName != null && !stageName.isBlank()) {
- Map<String, Object> stageReq = new HashMap<>();
- stageReq.put("stageName", stageName);
- stageReq.put("deploymentId", deployment.id());
- JsonNode stageDescription = props != null ? props.get("StageDescription") : null;
- if (stageDescription != null && stageDescription.has("Description")) {
- stageReq.put("description", resolveOptional(stageDescription, "Description", engine));
- }
- apiGatewayService.createStage(region, apiId, stageReq);
- }
- }
-
- private void provisionApiGatewayStage(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region) {
- String apiId = resolveOptional(props, "RestApiId", engine);
- String stageName = resolveOptional(props, "StageName", engine);
- String deploymentId = resolveOptional(props, "DeploymentId", engine);
-
- Map<String, Object> req = new HashMap<>();
- req.put("stageName", stageName);
- req.put("deploymentId", deploymentId);
- req.put("description", resolveOptional(props, "Description", engine));
-
- var stage = apiGatewayService.createStage(region, apiId, req);
- r.setPhysicalId(stageName);
- }
-
// ── ApiGatewayV2 (HTTP/WebSocket) ────────────────────────────────────────
private void provisionApiGatewayV2Api(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
@@ -1906,7 +1740,7 @@ public class CloudFormationResourceProvisioner {
*/
private void reconcileApiGatewayV2BodyRoutes(StackResource r, String region, String apiId, JsonNode props,
CloudFormationTemplateEngine engine) {
- JsonNode body = resolveOpenApiDocument(props, engine);
+ JsonNode body = OpenApiDocuments.resolve(props, engine, s3Service, objectMapper);
ApiGatewayV2BodyResourceState previous = null;
try {
previous = snapshotApiGatewayV2BodyResources(r, region, apiId);
@@ -1942,59 +1776,6 @@ public class CloudFormationResourceProvisioner {
replacement.authorizerIds());
}
- private JsonNode resolveOpenApiDocument(JsonNode props, CloudFormationTemplateEngine engine) {
- if (props == null) {
- return null;
- }
- if (props.hasNonNull("Body")) {
- return engine.resolveNode(props.get("Body"));
- }
- if (!props.hasNonNull("BodyS3Location")) {
- return null;
- }
-
- JsonNode location = engine.resolveNode(props.get("BodyS3Location"));
- OpenApiBodyS3Location bodyS3Location = parseOpenApiBodyS3Location(location);
-
- try {
- byte[] document = s3Service.getObject(bodyS3Location.bucket(), bodyS3Location.key(),
- bodyS3Location.version()).getData();
- String content = new String(document, StandardCharsets.UTF_8).trim();
- if (content.startsWith("{") || content.startsWith("[")) {
- return objectMapper.readTree(content);
- }
- return new CloudFormationYamlParser(objectMapper).parse(content);
- } catch (AwsException e) {
- throw e;
- } catch (Exception e) {
- throw new AwsException("ValidationException",
- "Unable to parse OpenAPI document from s3://" + bodyS3Location.bucket() + "/"
- + bodyS3Location.key(), 400);
- }
- }
-
- private OpenApiBodyS3Location parseOpenApiBodyS3Location(JsonNode location) {
- if (location != null && location.isTextual()) {
- String uri = location.asText();
- if (uri.startsWith("s3://")) {
- String withoutScheme = uri.substring("s3://".length());
- int slash = withoutScheme.indexOf('/');
- if (slash > 0 && slash < withoutScheme.length() - 1) {
- return new OpenApiBodyS3Location(withoutScheme.substring(0, slash),
- withoutScheme.substring(slash + 1), null);
- }
- }
- } else if (location != null && location.isObject()) {
- String bucket = textOrNull(location, "Bucket");
- String key = textOrNull(location, "Key");
- if (bucket != null && !bucket.isBlank() && key != null && !key.isBlank()) {
- return new OpenApiBodyS3Location(bucket, key, textOrNull(location, "Version"));
- }
- }
- throw new AwsException("ValidationException",
- "BodyS3Location must resolve to a non-empty S3 location", 400);
- }
-
/**
* CloudFormation's ApiGatewayV2 {@code Body} is an OpenAPI document. Materialize each
* declared HTTP operation as the route that API Gateway V2 serves, including its OpenAPI
@@ -2468,8 +2249,6 @@ public class CloudFormationResourceProvisioner {
private record OpenApiAuthorizerBinding(String authorizationType, String authorizerId) {}
- private record OpenApiBodyS3Location(String bucket, String key, String version) {}
-
private static final class ApiGatewayV2BodyMaterializationException extends RuntimeException {
private final ApiGatewayV2BodyResources resources;
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java
new file mode 100644
index 0000000000..e231578f98
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java
@@ -0,0 +1,234 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
+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.RestApi;
+import io.github.hectorvent.floci.services.apigateway.model.Stage;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.s3.S3Service;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for the REST API Gateway core types. RestApi, Resource, Method,
+ * Deployment, Stage and Authorizer are one coupled family (a resource belongs to an api, a method
+ * to a resource, a stage to a deployment), so they share one provisioner over {@link
+ * ApiGatewayService}. RestApi also accepts an OpenAPI {@code Body}/{@code BodyS3Location}, resolved
+ * through {@link OpenApiDocuments} (shared with {@code AWS::ApiGatewayV2::Api}), which is why
+ * {@link S3Service} and {@link ObjectMapper} are injected.
+ */
+@ApplicationScoped
+public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final String REST_API = "AWS::ApiGateway::RestApi";
+ private static final String RESOURCE = "AWS::ApiGateway::Resource";
+ private static final String METHOD = "AWS::ApiGateway::Method";
+ private static final String DEPLOYMENT = "AWS::ApiGateway::Deployment";
+ private static final String STAGE = "AWS::ApiGateway::Stage";
+ private static final String AUTHORIZER = "AWS::ApiGateway::Authorizer";
+
+ private final ApiGatewayService apiGatewayService;
+ private final S3Service s3Service;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public ApiGatewayRestApiCfnProvisioner(ApiGatewayService apiGatewayService, S3Service s3Service,
+ ObjectMapper objectMapper) {
+ this.apiGatewayService = apiGatewayService;
+ this.s3Service = s3Service;
+ this.objectMapper = objectMapper;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(REST_API, RESOURCE, METHOD, DEPLOYMENT, STAGE, AUTHORIZER);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ switch (r.getResourceType()) {
+ case REST_API -> provisionRestApi(r, props, ctx);
+ case RESOURCE -> provisionResource(r, props, ctx);
+ case METHOD -> provisionMethod(r, props, ctx);
+ case DEPLOYMENT -> provisionDeployment(r, props, ctx);
+ case STAGE -> provisionStage(r, props, ctx);
+ case AUTHORIZER -> provisionAuthorizer(r, props, ctx);
+ default -> throw new IllegalStateException("Unhandled type: " + r.getResourceType());
+ }
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ // Only the RestApi has a backing delete; deleting it cascades to its resources, methods,
+ // deployments, stages and authorizers, so the child types own no separate delete, the same
+ // as the legacy switch (their delete fell through to a no-op).
+ if (REST_API.equals(resourceType)) {
+ apiGatewayService.deleteRestApi(region, physicalId);
+ }
+ }
+
+ private void provisionRestApi(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String region = ctx.region();
+ CloudFormationTemplateEngine engine = ctx.engine();
+ String name = ctx.resolveOptional(props, "Name");
+ if (name == null || name.isBlank()) {
+ name = ctx.generatePhysicalName(r.getLogicalId(), 255, false);
+ }
+ String description = ctx.resolveOptional(props, "Description");
+ Map<String, Object> req = new HashMap<>();
+ req.put("name", name);
+ req.put("description", description);
+
+ if (props != null && props.has("EndpointConfiguration")) {
+ JsonNode epNode = props.get("EndpointConfiguration");
+ Map<String, Object> epReq = new HashMap<>();
+ epReq.put("types", ctx.resolveStringList(epNode, "Types"));
+ epReq.put("vpcEndpointIds", ctx.resolveStringList(epNode, "VpcEndpointIds"));
+ req.put("endpointConfiguration", epReq);
+ }
+
+ RestApi api = apiGatewayService.createRestApi(region, req);
+ r.setPhysicalId(api.getId());
+ r.getAttributes().put("RestApiId", api.getId());
+ r.getAttributes().put("RootResourceId",
+ apiGatewayService.getResources(region, api.getId()).get(0).getId());
+
+ // A declared Body or BodyS3Location is the whole OpenAPI document. Measured on real AWS
+ // it becomes the RestApi's Body with no synthesized Resource or Method, so putRestApi plus
+ // applyOpenApiSpec is the only place that turns it into resources and methods. putRestApi
+ // overwrites Name and Description from the document's info, so the declared Name and
+ // Description (null clearing an undeclared Description) are re-applied immediately after.
+ JsonNode openApiDocument = OpenApiDocuments.resolve(props, engine, s3Service, objectMapper);
+ if (openApiDocument != null) {
+ apiGatewayService.putRestApi(region, api.getId(), "overwrite", openApiDocument.toString());
+ apiGatewayService.updateRestApi(region, api.getId(),
+ List.of(replacePatchOp("/name", name), replacePatchOp("/description", description)));
+ }
+ }
+
+ /**
+ * A {@code replace} patch operation for {@link ApiGatewayService#updateRestApi}, allowing a
+ * {@code null} value ({@code Map.of} rejects one) so an undeclared property can still be
+ * cleared rather than left at whatever {@code putRestApi} last wrote to it.
+ */
+ private Map<String, String> replacePatchOp(String path, String value) {
+ Map<String, String> op = new HashMap<>();
+ op.put("op", "replace");
+ op.put("path", path);
+ op.put("value", value);
+ return op;
+ }
+
+ private void provisionResource(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String apiId = ctx.resolveOptional(props, "RestApiId");
+ String parentId = ctx.resolveOptional(props, "ParentId");
+ String pathPart = ctx.resolveOptional(props, "PathPart");
+
+ Map<String, Object> req = new HashMap<>();
+ req.put("pathPart", pathPart);
+
+ ApiGatewayResource res = apiGatewayService.createResource(ctx.region(), apiId, parentId, req);
+ r.setPhysicalId(res.getId());
+ r.getAttributes().put("ResourceId", res.getId());
+ }
+
+ private void provisionAuthorizer(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String apiId = ctx.resolveOptional(props, "RestApiId");
+ Map<String, Object> req = new HashMap<>();
+ req.put("name", ctx.resolveOptional(props, "Name"));
+ req.put("type", ctx.resolveOptional(props, "Type"));
+ req.put("authorizerUri", ctx.resolveOptional(props, "AuthorizerUri"));
+ req.put("identitySource", ctx.resolveOptional(props, "IdentitySource"));
+ String ttl = ctx.resolveOptional(props, "AuthorizerResultTtlInSeconds");
+ if (ttl != null) {
+ req.put("authorizerResultTtlInSeconds", ttl);
+ }
+ Authorizer authorizer = apiGatewayService.createAuthorizer(ctx.region(), apiId, req);
+ r.setPhysicalId(authorizer.getId());
+ r.getAttributes().put("AuthorizerId", authorizer.getId());
+ }
+
+ private void provisionMethod(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String region = ctx.region();
+ CloudFormationTemplateEngine engine = ctx.engine();
+ String apiId = ctx.resolveOptional(props, "RestApiId");
+ String resourceId = ctx.resolveOptional(props, "ResourceId");
+ String httpMethod = ctx.resolveOptional(props, "HttpMethod");
+
+ Map<String, Object> req = new HashMap<>();
+ req.put("authorizationType", resolveOrDefault(ctx, props, "AuthorizationType", "NONE"));
+ String authorizerId = ctx.resolveOptional(props, "AuthorizerId");
+ if (authorizerId != null) {
+ req.put("authorizerId", authorizerId);
+ }
+ req.put("apiKeyRequired", Boolean.parseBoolean(resolveOrDefault(ctx, props, "ApiKeyRequired", "false")));
+
+ apiGatewayService.putMethod(region, apiId, resourceId, httpMethod, req);
+ r.setPhysicalId(apiId + "-" + resourceId + "-" + httpMethod);
+
+ if (props != null && props.has("Integration")) {
+ JsonNode integNode = engine.resolveNode(props.get("Integration"));
+ Map<String, Object> integReq = new HashMap<>();
+ integReq.put("type", ctx.resolveOptional(integNode, "Type"));
+ integReq.put("httpMethod", ctx.resolveOptional(integNode, "IntegrationHttpMethod"));
+ integReq.put("uri", ctx.resolveOptional(integNode, "Uri"));
+
+ apiGatewayService.putIntegration(region, apiId, resourceId, httpMethod, integReq);
+ }
+ }
+
+ private void provisionDeployment(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String region = ctx.region();
+ String apiId = ctx.resolveOptional(props, "RestApiId");
+ Map<String, Object> req = new HashMap<>();
+ req.put("description", ctx.resolveOptional(props, "Description"));
+
+ Deployment deployment = apiGatewayService.createDeployment(region, apiId, req);
+ r.setPhysicalId(deployment.id());
+ r.getAttributes().put("DeploymentId", deployment.id());
+
+ // AWS::ApiGateway::Deployment accepts an inline StageName: when present, AWS creates that
+ // stage pointing at this deployment, with no separate AWS::ApiGateway::Stage resource.
+ String stageName = ctx.resolveOptional(props, "StageName");
+ if (stageName != null && !stageName.isBlank()) {
+ Map<String, Object> stageReq = new HashMap<>();
+ stageReq.put("stageName", stageName);
+ stageReq.put("deploymentId", deployment.id());
+ JsonNode stageDescription = props != null ? props.get("StageDescription") : null;
+ if (stageDescription != null && stageDescription.has("Description")) {
+ stageReq.put("description", ctx.resolveOptional(stageDescription, "Description"));
+ }
+ apiGatewayService.createStage(region, apiId, stageReq);
+ }
+ }
+
+ private void provisionStage(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String apiId = ctx.resolveOptional(props, "RestApiId");
+ String stageName = ctx.resolveOptional(props, "StageName");
+ String deploymentId = ctx.resolveOptional(props, "DeploymentId");
+
+ Map<String, Object> req = new HashMap<>();
+ req.put("stageName", stageName);
+ req.put("deploymentId", deploymentId);
+ req.put("description", ctx.resolveOptional(props, "Description"));
+
+ apiGatewayService.createStage(ctx.region(), apiId, req);
+ r.setPhysicalId(stageName);
+ }
+
+ /** Resolves an optional property, falling back to {@code defaultValue} when absent or blank. */
+ private static String resolveOrDefault(ProvisionContext ctx, JsonNode props, String name, String defaultValue) {
+ String value = ctx.resolveOptional(props, name);
+ return value != null && !value.isBlank() ? value : defaultValue;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/OpenApiDocuments.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/OpenApiDocuments.java
new file mode 100644
index 0000000000..1a52b1a02c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/OpenApiDocuments.java
@@ -0,0 +1,88 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationYamlParser;
+import io.github.hectorvent.floci.services.s3.S3Service;
+
+import java.nio.charset.StandardCharsets;
+
+/**
+ * Resolves the OpenAPI document a CloudFormation API Gateway resource declares through its
+ * {@code Body} (inline) or {@code BodyS3Location} (an object in S3). Shared by
+ * {@code AWS::ApiGateway::RestApi} and {@code AWS::ApiGatewayV2::Api}, which both accept the same
+ * two properties, so the resolution lives here rather than being duplicated per provisioner.
+ */
+public final class OpenApiDocuments {
+
+ private OpenApiDocuments() {
+ }
+
+ /**
+ * The declared OpenAPI document as a resolved JSON tree, or {@code null} when the resource
+ * declares neither {@code Body} nor {@code BodyS3Location}. A JSON or YAML body in S3 is
+ * fetched and parsed; a malformed one raises a {@code ValidationException}.
+ */
+ public static JsonNode resolve(JsonNode props, CloudFormationTemplateEngine engine,
+ S3Service s3Service, ObjectMapper objectMapper) {
+ if (props == null) {
+ return null;
+ }
+ if (props.hasNonNull("Body")) {
+ return engine.resolveNode(props.get("Body"));
+ }
+ if (!props.hasNonNull("BodyS3Location")) {
+ return null;
+ }
+
+ JsonNode location = engine.resolveNode(props.get("BodyS3Location"));
+ S3Location bodyS3Location = parseLocation(location);
+
+ try {
+ byte[] document = s3Service.getObject(bodyS3Location.bucket(), bodyS3Location.key(),
+ bodyS3Location.version()).getData();
+ String content = new String(document, StandardCharsets.UTF_8).trim();
+ if (content.startsWith("{") || content.startsWith("[")) {
+ return objectMapper.readTree(content);
+ }
+ return new CloudFormationYamlParser(objectMapper).parse(content);
+ } catch (AwsException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new AwsException("ValidationException",
+ "Unable to parse OpenAPI document from s3://" + bodyS3Location.bucket() + "/"
+ + bodyS3Location.key(), 400);
+ }
+ }
+
+ private static S3Location parseLocation(JsonNode location) {
+ if (location != null && location.isTextual()) {
+ String uri = location.asText();
+ if (uri.startsWith("s3://")) {
+ String withoutScheme = uri.substring("s3://".length());
+ int slash = withoutScheme.indexOf('/');
+ if (slash > 0 && slash < withoutScheme.length() - 1) {
+ return new S3Location(withoutScheme.substring(0, slash),
+ withoutScheme.substring(slash + 1), null);
+ }
+ }
+ } else if (location != null && location.isObject()) {
+ String bucket = textOrNull(location, "Bucket");
+ String key = textOrNull(location, "Key");
+ if (bucket != null && !bucket.isBlank() && key != null && !key.isBlank()) {
+ return new S3Location(bucket, key, textOrNull(location, "Version"));
+ }
+ }
+ throw new AwsException("ValidationException",
+ "BodyS3Location must resolve to a non-empty S3 location", 400);
+ }
+
+ private static String textOrNull(JsonNode node, String field) {
+ return node != null && node.hasNonNull(field) ? node.path(field).asText() : null;
+ }
+
+ private record S3Location(String bucket, String key, String version) {
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
index bcf0c5150b..be2d979424 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
@@ -33,6 +33,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayUsagePlanCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayDomainCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayGatewayResponseCfnProvisioner;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayRestApiCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingGroupCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingScalingPolicyCfnProvisioner;
@@ -303,6 +304,7 @@ final class CfnProvisionerFixture {
discovered.add(new ApiGatewayUsagePlanCfnProvisioner(apiGatewayService));
discovered.add(new ApiGatewayDomainCfnProvisioner(apiGatewayService));
discovered.add(new ApiGatewayGatewayResponseCfnProvisioner(apiGatewayService));
+ discovered.add(new ApiGatewayRestApiCfnProvisioner(apiGatewayService, s3Service, objectMapper));
}
if (autoScalingService != null) {
discovered.add(new AutoScalingGroupCfnProvisioner(autoScalingService));
@@ -684,7 +686,6 @@ final class CfnProvisionerFixture {
s3Service,
lambdaService,
iamService,
- apiGatewayService,
apiGatewayV2Service,
lambdaLayerService,
objectMapper,
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisionerTest.java
new file mode 100644
index 0000000000..ade5b731c8
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisionerTest.java
@@ -0,0 +1,159 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
+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.RestApi;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.s3.S3Service;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * The REST API Gateway core types in isolation: the physical id and the exact Fn::GetAtt keys each
+ * publishes, the inline-stage shortcut on a Deployment, and that only the RestApi deletes.
+ */
+class ApiGatewayRestApiCfnProvisionerTest {
+
+ private final ApiGatewayService api = mock(ApiGatewayService.class);
+ private final S3Service s3 = mock(S3Service.class);
+ private final ApiGatewayRestApiCfnProvisioner provisioner =
+ new ApiGatewayRestApiCfnProvisioner(api, s3, new ObjectMapper());
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ void restApiPublishesIdAndRootResourceId() throws Exception {
+ RestApi created = new RestApi();
+ created.setId("api-1");
+ when(api.createRestApi(eq("us-east-1"), anyMap())).thenReturn(created);
+ ApiGatewayResource root = new ApiGatewayResource();
+ root.setId("root-1");
+ when(api.getResources("us-east-1", "api-1")).thenReturn(List.of(root));
+
+ StackResource r = resource("AWS::ApiGateway::RestApi", "Api");
+ provisioner.provision(r, props("{\"Name\": \"shop\"}"), ctx());
+
+ assertEquals("api-1", r.getPhysicalId());
+ assertEquals(Set.of("RestApiId", "RootResourceId"), r.getAttributes().keySet());
+ assertEquals("api-1", r.getAttributes().get("RestApiId"));
+ assertEquals("root-1", r.getAttributes().get("RootResourceId"));
+ verify(api, never()).putRestApi(anyString(), anyString(), anyString(), anyString());
+ }
+
+ @Test
+ void resourcePublishesResourceId() throws Exception {
+ ApiGatewayResource res = new ApiGatewayResource();
+ res.setId("res-1");
+ when(api.createResource(eq("us-east-1"), eq("api-1"), eq("root-1"), anyMap())).thenReturn(res);
+
+ StackResource r = resource("AWS::ApiGateway::Resource", "Res");
+ provisioner.provision(r, props("""
+ {"RestApiId": "api-1", "ParentId": "root-1", "PathPart": "orders"}
+ """), ctx());
+
+ assertEquals("res-1", r.getPhysicalId());
+ assertEquals("res-1", r.getAttributes().get("ResourceId"));
+ }
+
+ @Test
+ void authorizerPublishesAuthorizerId() throws Exception {
+ Authorizer authorizer = new Authorizer();
+ authorizer.setId("auth-1");
+ when(api.createAuthorizer(eq("us-east-1"), eq("api-1"), anyMap())).thenReturn(authorizer);
+
+ StackResource r = resource("AWS::ApiGateway::Authorizer", "Auth");
+ provisioner.provision(r, props("""
+ {"RestApiId": "api-1", "Name": "jwt", "Type": "TOKEN"}
+ """), ctx());
+
+ assertEquals("auth-1", r.getPhysicalId());
+ assertEquals("auth-1", r.getAttributes().get("AuthorizerId"));
+ }
+
+ @Test
+ void methodUsesTheCompositePhysicalIdAndProvisionsItsIntegration() throws Exception {
+ StackResource r = resource("AWS::ApiGateway::Method", "Get");
+ provisioner.provision(r, props("""
+ {"RestApiId": "api-1", "ResourceId": "res-1", "HttpMethod": "GET",
+ "Integration": {"Type": "AWS_PROXY", "IntegrationHttpMethod": "POST", "Uri": "arn:..."}}
+ """), ctx());
+
+ assertEquals("api-1-res-1-GET", r.getPhysicalId());
+ verify(api).putMethod(eq("us-east-1"), eq("api-1"), eq("res-1"), eq("GET"), anyMap());
+ verify(api).putIntegration(eq("us-east-1"), eq("api-1"), eq("res-1"), eq("GET"), anyMap());
+ }
+
+ @Test
+ void deploymentPublishesDeploymentIdAndCreatesTheInlineStage() throws Exception {
+ when(api.createDeployment(eq("us-east-1"), eq("api-1"), anyMap()))
+ .thenReturn(new Deployment("dep-1", null, 0L));
+
+ StackResource r = resource("AWS::ApiGateway::Deployment", "Dep");
+ provisioner.provision(r, props("""
+ {"RestApiId": "api-1", "StageName": "prod"}
+ """), ctx());
+
+ assertEquals("dep-1", r.getPhysicalId());
+ assertEquals("dep-1", r.getAttributes().get("DeploymentId"));
+ verify(api).createStage(eq("us-east-1"), eq("api-1"), anyMap());
+ }
+
+ @Test
+ void stageUsesTheStageNameAsPhysicalId() throws Exception {
+ StackResource r = resource("AWS::ApiGateway::Stage", "Stage");
+ provisioner.provision(r, props("""
+ {"RestApiId": "api-1", "StageName": "prod", "DeploymentId": "dep-1"}
+ """), ctx());
+
+ assertEquals("prod", r.getPhysicalId());
+ verify(api).createStage(eq("us-east-1"), eq("api-1"), anyMap());
+ }
+
+ @Test
+ void deleteRemovesOnlyTheRestApi() {
+ provisioner.delete("AWS::ApiGateway::RestApi", "api-1", "us-east-1");
+ verify(api).deleteRestApi("us-east-1", "api-1");
+
+ provisioner.delete("AWS::ApiGateway::Method", "api-1-res-1-GET", "us-east-1");
+ verify(api, never()).deleteRestApi("us-east-1", "api-1-res-1-GET");
+ }
+
+ private ProvisionContext ctx() {
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null ? null : node.asText();
+ });
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
+ }
+
+ private JsonNode props(String json) throws Exception {
+ return mapper.readTree(json);
+ }
+
+ private static StackResource resource(String type, String logicalId) {
+ StackResource r = new StackResource();
+ r.setLogicalId(logicalId);
+ r.setResourceType(type);
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index 6f277db75b..ed8250c0fb 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -1,14 +1,14 @@
AWS::ApiGateway::Account ApiGatewayAccountCfnProvisioner
AWS::ApiGateway::ApiKey ApiGatewayApiKeyCfnProvisioner
-AWS::ApiGateway::Authorizer LEGACY_SWITCH
+AWS::ApiGateway::Authorizer ApiGatewayRestApiCfnProvisioner
AWS::ApiGateway::BasePathMapping ApiGatewayDomainCfnProvisioner
-AWS::ApiGateway::Deployment LEGACY_SWITCH
+AWS::ApiGateway::Deployment ApiGatewayRestApiCfnProvisioner
AWS::ApiGateway::DomainName ApiGatewayDomainCfnProvisioner
AWS::ApiGateway::GatewayResponse ApiGatewayGatewayResponseCfnProvisioner
-AWS::ApiGateway::Method LEGACY_SWITCH
-AWS::ApiGateway::Resource LEGACY_SWITCH
-AWS::ApiGateway::RestApi LEGACY_SWITCH
-AWS::ApiGateway::Stage LEGACY_SWITCH
+AWS::ApiGateway::Method ApiGatewayRestApiCfnProvisioner
+AWS::ApiGateway::Resource ApiGatewayRestApiCfnProvisioner
+AWS::ApiGateway::RestApi ApiGatewayRestApiCfnProvisioner
+AWS::ApiGateway::Stage ApiGatewayRestApiCfnProvisioner
AWS::ApiGateway::UsagePlan ApiGatewayUsagePlanCfnProvisioner
AWS::ApiGateway::UsagePlanKey ApiGatewayUsagePlanCfnProvisioner
AWS::ApiGatewayV2::Api LEGACY_SWITCH