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

Move the six coupled REST API Gateway types (RestApi, Resource, Method, Deployment, Stage, Authorizer) out of the CloudFormationResourceProvisioner monolith into a new ApiGatewayRestApiCfnProvisioner. The shared OpenAPI Body and BodyS3Location resolver, used by both AWS::ApiGateway::RestApi and AWS::ApiGatewayV2::Api, is extracted into OpenApiDocuments so the monolith's V2 arm reuses it rather than keeping a copy. With the v1 arms gone, the monolith no longer needs its apiGatewayService dependency, so that constructor parameter is dropped.

The move preserves Ref, but it is not a pure move for Fn::GetAtt: it also resolves four keys the monolith never populated. Once a type is owned by a registry provisioner, CfnSchemaCoverageTest requires every readOnly attribute to be published or recorded as a gap, so the new provisioner sets RestApiId, ResourceId, AuthorizerId and DeploymentId, which previously resolved to the literal "Logical.Attr". RootResourceId was already set. The inventory tsv, fixture wiring and a focused unit test cover the six types.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-18 23:39:14 -04:00
1 parent 21beccceb1
commit 25fc8e452f
6 files changed
+491 -230

No files matched your search

@@ -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;
@@ -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;
}
}
@@ -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) {
}
}