Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(cloudformation): CodeBuild/CodePipeline CFN provisioning (#2685)

Sam Fakhreddineac94232910e4
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 5c66f2add4..5b507bbeb0 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -58,7 +58,7 @@ cross-resource references.
| SQS | `Queue`, `QueuePolicy` (accepted; policy not enforced) |
| SNS | `Topic`, `Subscription` |
| DynamoDB | `Table`, `GlobalTable` |
-| Lambda | `Function` (Zip via S3/inline `ZipFile`, and Image), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into) |
+| Lambda | `Function` (Zip via S3/inline `ZipFile`, and Image), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into). Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work |
| IAM | `Role`, `User`, `AccessKey`, `Policy`, `ManagedPolicy`, `InstanceProfile` |
| Organizations | `Organization`, `OrganizationalUnit`, `Account`, `Policy`, `ResourcePolicy` |
| SSM | `Parameter` |
@@ -75,6 +75,8 @@ cross-resource references.
| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account` |
| API Gateway v2 | `Api`, `Route`, `Integration`, `Stage`, `Deployment` |
| Step Functions | `StateMachine` |
+| CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` |
+| CodeBuild | `Project` |
| Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` |
| Cognito | `UserPool`, `UserPoolClient` |
| EventBridge | `Rule`, `EventBus`, `EventBusPolicy` |
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 d9be15757d..d2fb915a47 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
@@ -2875,19 +2875,7 @@ public class CloudFormationResourceProvisioner {
private record LambdaCodeSpec(Map<String, Object> request, String identity) {}
private static String sourceToZipBase64(String source, String handler, String runtime) {
- String module = handler.contains(".") ? handler.substring(0, handler.lastIndexOf('.')) : "index";
- String ext = runtime.startsWith("python") ? ".py" : ".js";
- try {
- var baos = new ByteArrayOutputStream();
- try (var zos = new ZipOutputStream(baos)) {
- zos.putNextEntry(new ZipEntry(module + ext));
- zos.write(source.getBytes(StandardCharsets.UTF_8));
- zos.closeEntry();
- }
- return Base64.getEncoder().encodeToString(baos.toByteArray());
- } catch (Exception e) {
- throw new RuntimeException("Failed to create zip from ZipFile source", e);
- }
+ return InlineZipPackager.sourceToZipBase64(source, handler, runtime);
}
private static String defaultHandlerZipBase64() {
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/InlineZipPackager.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/InlineZipPackager.java
new file mode 100644
index 0000000000..3dea9992ad
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/InlineZipPackager.java
@@ -0,0 +1,132 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+/**
+ * Builds the deployment package for a Lambda function declared with CloudFormation's
+ * inline {@code ZipFile} property.
+ *
+ * <p>Matches the real service's special-casing of that code path: AWS injects the
+ * {@code cfn-response} (Node.js) / {@code cfnresponse} (Python) module into ZipFile
+ * packages so custom-resource handlers can send their CloudFormation callbacks, and
+ * Solutions-style templates (e.g. Landing Zone Accelerator's installer) rely on it.
+ * Lives outside {@code CloudFormationResourceProvisioner} so the eventual Lambda
+ * provisioner extraction can take it along unchanged.</p>
+ */
+final class InlineZipPackager {
+
+ /**
+ * The cfn-response module for Node.js. Unlike AWS's canonical module this one honors
+ * the ResponseURL's protocol and port, because Floci's ResponseURL is plain http on
+ * the emulator's port.
+ */
+ private static final String CFN_RESPONSE_JS = """
+ exports.SUCCESS = "SUCCESS";
+ exports.FAILED = "FAILED";
+ exports.send = function (event, context, responseStatus, responseData, physicalResourceId, noEcho) {
+ var responseBody = JSON.stringify({
+ Status: responseStatus,
+ Reason: "See the details in CloudWatch Log Stream: " + context.logStreamName,
+ PhysicalResourceId: physicalResourceId || context.logStreamName,
+ StackId: event.StackId,
+ RequestId: event.RequestId,
+ LogicalResourceId: event.LogicalResourceId,
+ NoEcho: noEcho || false,
+ Data: responseData
+ });
+ console.log("Response body:\\n", responseBody);
+ var url = require("url");
+ var parsedUrl = url.parse(event.ResponseURL);
+ var isHttps = parsedUrl.protocol === "https:";
+ var transport = isHttps ? require("https") : require("http");
+ var options = {
+ hostname: parsedUrl.hostname,
+ port: parsedUrl.port || (isHttps ? 443 : 80),
+ path: parsedUrl.path,
+ method: "PUT",
+ headers: { "content-type": "", "content-length": Buffer.byteLength(responseBody) }
+ };
+ var request = transport.request(options, function (response) {
+ console.log("Status code: " + response.statusCode);
+ context.done();
+ });
+ request.on("error", function (error) {
+ console.log("send(..) failed executing request(..): " + error);
+ context.done();
+ });
+ request.write(responseBody);
+ request.end();
+ };
+ """;
+
+ /** The Python counterpart AWS injects as {@code cfnresponse}. */
+ private static final String CFN_RESPONSE_PY = """
+ import http.client
+ import json
+ import urllib.parse
+
+ SUCCESS = "SUCCESS"
+ FAILED = "FAILED"
+
+ def send(event, context, responseStatus, responseData, physicalResourceId=None,
+ noEcho=False, reason=None):
+ response_url = event['ResponseURL']
+ response_body = json.dumps({
+ 'Status': responseStatus,
+ 'Reason': reason or "See the details in CloudWatch Log Stream: "
+ + context.log_stream_name,
+ 'PhysicalResourceId': physicalResourceId or context.log_stream_name,
+ 'StackId': event['StackId'],
+ 'RequestId': event['RequestId'],
+ 'LogicalResourceId': event['LogicalResourceId'],
+ 'NoEcho': noEcho,
+ 'Data': responseData,
+ })
+ print("Response body:", response_body)
+ body_bytes = response_body.encode('utf-8')
+ parsed = urllib.parse.urlparse(response_url)
+ conn_class = http.client.HTTPSConnection if parsed.scheme == 'https' \\
+ else http.client.HTTPConnection
+ conn = conn_class(parsed.hostname, parsed.port)
+ path = parsed.path + ('?' + parsed.query if parsed.query else '')
+ conn.request('PUT', path, body=body_bytes,
+ headers={'content-type': '', 'content-length': str(len(body_bytes))})
+ response = conn.getresponse()
+ print("Status code:", response.status)
+ """;
+
+ private InlineZipPackager() {}
+
+ static String sourceToZipBase64(String source, String handler, String runtime) {
+ String module = handler.contains(".") ? handler.substring(0, handler.lastIndexOf('.')) : "index";
+ String ext = runtime.startsWith("python") ? ".py" : ".js";
+ try {
+ var baos = new ByteArrayOutputStream();
+ try (var zos = new ZipOutputStream(baos)) {
+ zos.putNextEntry(new ZipEntry(module + ext));
+ zos.write(source.getBytes(StandardCharsets.UTF_8));
+ zos.closeEntry();
+ if (runtime.startsWith("nodejs")) {
+ zos.putNextEntry(new ZipEntry("node_modules/cfn-response/package.json"));
+ zos.write("{\"name\":\"cfn-response\",\"main\":\"cfn-response.js\"}"
+ .getBytes(StandardCharsets.UTF_8));
+ zos.closeEntry();
+ zos.putNextEntry(new ZipEntry("node_modules/cfn-response/cfn-response.js"));
+ zos.write(CFN_RESPONSE_JS.getBytes(StandardCharsets.UTF_8));
+ zos.closeEntry();
+ } else if (runtime.startsWith("python")) {
+ zos.putNextEntry(new ZipEntry("cfnresponse.py"));
+ zos.write(CFN_RESPONSE_PY.getBytes(StandardCharsets.UTF_8));
+ zos.closeEntry();
+ }
+ }
+ return Base64.getEncoder().encodeToString(baos.toByteArray());
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to create zip from ZipFile source", e);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodeBuildCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodeBuildCfnProvisioner.java
new file mode 100644
index 0000000000..c7cc13d408
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodeBuildCfnProvisioner.java
@@ -0,0 +1,114 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+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.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.codebuild.CodeBuildJsonHandler;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for CodeBuild: {@code AWS::CodeBuild::Project}.
+ *
+ * <p>CloudFormation properties are PascalCase while the CodeBuild API is camelCase; the
+ * recursive first-letter-lowercase transform maps them, with one irregular field —
+ * {@code BuildSpec} is {@code buildspec} (all lowercase) on the wire.</p>
+ */
+@ApplicationScoped
+public class CodeBuildCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final Logger LOG = Logger.getLogger(CodeBuildCfnProvisioner.class);
+
+ private final CodeBuildJsonHandler codeBuildJsonHandler;
+ private final RegionResolver regionResolver;
+ private final ObjectMapper mapper;
+
+ @Inject
+ public CodeBuildCfnProvisioner(CodeBuildJsonHandler codeBuildJsonHandler,
+ RegionResolver regionResolver, ObjectMapper mapper) {
+ this.codeBuildJsonHandler = codeBuildJsonHandler;
+ this.regionResolver = regionResolver;
+ this.mapper = mapper;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of("AWS::CodeBuild::Project");
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ ObjectNode request = (ObjectNode) lowerKeys(ctx.engine().resolveNode(props));
+ boolean update = r.getPhysicalId() != null && !r.getPhysicalId().isBlank();
+ String name = request.path("name").asText(null);
+ if (name == null || name.isBlank()) {
+ name = update ? r.getPhysicalId() : ctx.generatePhysicalName(r.getLogicalId(), 150, false);
+ request.put("name", name);
+ }
+
+ JsonNode response = handle(update ? "UpdateProject" : "CreateProject",
+ request, ctx.region(), ctx.accountId());
+
+ r.setPhysicalId(name);
+ r.getAttributes().put("Arn",
+ response.path("project").path("arn").asText(
+ "arn:aws:codebuild:" + ctx.region() + ":" + ctx.accountId() + ":project/" + name));
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ try {
+ handle("DeleteProject", mapper.createObjectNode().put("name", physicalId),
+ region, regionResolver.getAccountId());
+ } catch (AwsException e) {
+ LOG.debugv("CodeBuild CFN delete of {0} tolerated: {1}", physicalId, e.getMessage());
+ }
+ }
+
+ private JsonNode handle(String action, ObjectNode request, String region, String account) {
+ try {
+ jakarta.ws.rs.core.Response response =
+ codeBuildJsonHandler.handle(action, request, region, account);
+ try {
+ // The handler returns Response.ok(Map.of(...)) for every JSON action, never a
+ // JsonNode directly, so the entity must be converted rather than downcast.
+ Object entity = response.getEntity();
+ return entity instanceof JsonNode node ? node : mapper.valueToTree(entity);
+ } finally {
+ response.close();
+ }
+ } catch (AwsException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new AwsException("InternalFailure",
+ "CodeBuild " + action + " failed: " + e.getMessage(), 500);
+ }
+ }
+
+ private JsonNode lowerKeys(JsonNode node) {
+ if (node instanceof ObjectNode objectNode) {
+ ObjectNode result = mapper.createObjectNode();
+ objectNode.fields().forEachRemaining(entry -> {
+ String key = entry.getKey();
+ String lowered = "BuildSpec".equals(key)
+ ? "buildspec"
+ : key.isEmpty() ? key : Character.toLowerCase(key.charAt(0)) + key.substring(1);
+ result.set(lowered, lowerKeys(entry.getValue()));
+ });
+ return result;
+ }
+ if (node instanceof ArrayNode arrayNode) {
+ ArrayNode result = mapper.createArrayNode();
+ arrayNode.forEach(entry -> result.add(lowerKeys(entry)));
+ return result;
+ }
+ return node;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodePipelineCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodePipelineCfnProvisioner.java
new file mode 100644
index 0000000000..debce2e14e
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodePipelineCfnProvisioner.java
@@ -0,0 +1,275 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+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.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.codepipeline.CodePipelineService;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for CodePipeline: {@code AWS::CodePipeline::Pipeline},
+ * {@code AWS::CodePipeline::CustomActionType}, and {@code AWS::CodePipeline::Webhook}.
+ *
+ * <p>CloudFormation properties are PascalCase while the CodePipeline API is camelCase;
+ * a recursive first-letter-lowercase transform is lossless for this resource schema, so
+ * the resolved properties become the API request directly.</p>
+ */
+@ApplicationScoped
+public class CodePipelineCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final Logger LOG = Logger.getLogger(CodePipelineCfnProvisioner.class);
+
+ private final CodePipelineService codePipelineService;
+ private final RegionResolver regionResolver;
+ private final ObjectMapper mapper;
+
+ @Inject
+ public CodePipelineCfnProvisioner(CodePipelineService codePipelineService,
+ RegionResolver regionResolver, ObjectMapper mapper) {
+ this.codePipelineService = codePipelineService;
+ this.regionResolver = regionResolver;
+ this.mapper = mapper;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of("AWS::CodePipeline::Pipeline",
+ "AWS::CodePipeline::CustomActionType",
+ "AWS::CodePipeline::Webhook");
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ switch (r.getResourceType()) {
+ case "AWS::CodePipeline::Pipeline" -> provisionPipeline(r, props, ctx);
+ case "AWS::CodePipeline::CustomActionType" -> provisionCustomActionType(r, props, ctx);
+ case "AWS::CodePipeline::Webhook" -> provisionWebhook(r, props, ctx);
+ default -> throw new IllegalStateException(
+ "CodePipelineCfnProvisioner cannot handle " + r.getResourceType());
+ }
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ String account = regionResolver.getAccountId();
+ try {
+ switch (resourceType) {
+ case "AWS::CodePipeline::Pipeline" -> codePipelineService.handle("DeletePipeline",
+ mapper.createObjectNode().put("name", physicalId), region, account);
+ case "AWS::CodePipeline::CustomActionType" -> {
+ String[] parts = physicalId.split("\\|");
+ codePipelineService.handle("DeleteCustomActionType", mapper.createObjectNode()
+ .put("category", parts[0])
+ .put("provider", parts.length > 2 ? parts[2] : "")
+ .put("version", parts.length > 3 ? parts[3] : "1"),
+ region, account);
+ }
+ case "AWS::CodePipeline::Webhook" -> codePipelineService.handle("DeleteWebhook",
+ mapper.createObjectNode().put("name", physicalId), region, account);
+ default -> { }
+ }
+ } catch (AwsException e) {
+ LOG.debugv("CodePipeline CFN delete of {0} {1} tolerated: {2}",
+ resourceType, physicalId, e.getMessage());
+ }
+ }
+
+ private static final String DISABLED_STAGES_ATTR = "__FlociCodePipelineDisabledStages";
+
+ private void provisionPipeline(StackResource r, JsonNode props, ProvisionContext ctx) {
+ ObjectNode declaration = (ObjectNode) lowerKeys(ctx.engine().resolveNode(props));
+ JsonNode transitions = declaration.remove("disableInboundStageTransitions");
+ JsonNode tags = declaration.remove("tags");
+ declaration.remove("restartExecutionOnUpdate");
+
+ String previousPhysicalId = r.getPhysicalId();
+ boolean update = previousPhysicalId != null && !previousPhysicalId.isBlank();
+ String explicitName = declaration.path("name").asText(null);
+ // Name is part of a pipeline's identity -- CodePipeline has no rename operation, so a
+ // template Name that differs from the tracked physical ID is a replacement, not an
+ // in-place update (UpdatePipeline would otherwise target/overwrite the wrong pipeline).
+ boolean rename = update && explicitName != null && !explicitName.isBlank()
+ && !explicitName.equals(previousPhysicalId);
+ boolean create = !update || rename;
+ String name = explicitName != null && !explicitName.isBlank()
+ ? explicitName
+ : (update ? previousPhysicalId : ctx.generatePhysicalName(r.getLogicalId(), 100, false));
+ if (explicitName == null || explicitName.isBlank()) {
+ declaration.put("name", name);
+ }
+
+ ObjectNode request = mapper.createObjectNode();
+ request.set("pipeline", declaration);
+ JsonNode response;
+ if (create) {
+ if (tags != null && tags.isArray() && !tags.isEmpty()) {
+ request.set("tags", tags);
+ }
+ response = codePipelineService.handle("CreatePipeline", request, ctx.region(), ctx.accountId());
+ } else {
+ response = codePipelineService.handle("UpdatePipeline", request, ctx.region(), ctx.accountId());
+ }
+
+ java.util.Set<String> desiredDisabledStages = new java.util.LinkedHashSet<>();
+ if (transitions != null && transitions.isArray()) {
+ for (JsonNode transition : transitions) {
+ desiredDisabledStages.add(transition.path("stageName").asText());
+ }
+ }
+ try {
+ // DisableInboundStageTransitions is declarative, but only for the stages CloudFormation
+ // itself disabled: a stage disabled externally (e.g. a manual gate) and never listed here
+ // must be left alone. Re-enable only stages this resource previously disabled and has now
+ // dropped from the list, tracked via DISABLED_STAGES_ATTR across deployments.
+ if (!create) {
+ String previouslyManaged = r.getAttributes().get(DISABLED_STAGES_ATTR);
+ Iterable<String> candidateStages;
+ if (previouslyManaged != null) {
+ candidateStages = previouslyManaged.isBlank()
+ ? java.util.List.of() : java.util.Arrays.asList(previouslyManaged.split(","));
+ } else {
+ // A resource stored before DISABLED_STAGES_ATTR existed has no record of what it
+ // previously disabled. Fall back to reconciling every declared stage rather than
+ // skipping reconciliation outright, which would leave a removed entry disabled
+ // forever after this one legacy update.
+ java.util.List<String> declaredStages = new java.util.ArrayList<>();
+ if (declaration.path("stages").isArray()) {
+ for (JsonNode stage : declaration.path("stages")) {
+ declaredStages.add(stage.path("name").asText());
+ }
+ }
+ candidateStages = declaredStages;
+ }
+ for (String stageName : candidateStages) {
+ if (!desiredDisabledStages.contains(stageName)) {
+ codePipelineService.handle("EnableStageTransition", mapper.createObjectNode()
+ .put("pipelineName", name)
+ .put("stageName", stageName)
+ .put("transitionType", "Inbound"),
+ ctx.region(), ctx.accountId());
+ }
+ }
+ }
+ for (String stageName : desiredDisabledStages) {
+ JsonNode transition = null;
+ for (JsonNode candidate : transitions) {
+ if (stageName.equals(candidate.path("stageName").asText())) {
+ transition = candidate;
+ break;
+ }
+ }
+ codePipelineService.handle("DisableStageTransition", mapper.createObjectNode()
+ .put("pipelineName", name)
+ .put("stageName", stageName)
+ .put("transitionType", "Inbound")
+ .put("reason", transition.path("reason").asText("Disabled by CloudFormation")),
+ ctx.region(), ctx.accountId());
+ }
+ } catch (RuntimeException e) {
+ if (create) {
+ // The pipeline was just created (fresh, or as a rename's replacement) and stage
+ // reconciliation then failed. CloudFormation reverts this resource to its previous
+ // physicalId on a failed update, so the half-provisioned pipeline must be torn down
+ // now, or a corrected retry hits PipelineNameInUseException on the same name.
+ try {
+ codePipelineService.handle("DeletePipeline",
+ mapper.createObjectNode().put("name", name), ctx.region(), ctx.accountId());
+ } catch (RuntimeException cleanupFailure) {
+ e.addSuppressed(cleanupFailure);
+ }
+ }
+ throw e;
+ }
+ r.getAttributes().put(DISABLED_STAGES_ATTR, String.join(",", desiredDisabledStages));
+
+ if (rename) {
+ delete("AWS::CodePipeline::Pipeline", previousPhysicalId, ctx.region());
+ }
+ r.setPhysicalId(name);
+ r.getAttributes().put("Version",
+ String.valueOf(response.path("pipeline").path("version").asInt(1)));
+ }
+
+ private void provisionCustomActionType(StackResource r, JsonNode props, ProvisionContext ctx) {
+ ObjectNode request = (ObjectNode) lowerKeys(ctx.engine().resolveNode(props));
+ request.remove("tags");
+ String physicalId = request.path("category").asText() + "|Custom|"
+ + request.path("provider").asText() + "|" + request.path("version").asText("1");
+ String previousPhysicalId = r.getPhysicalId();
+ // Category/Provider/Version are this resource's identity — CodePipeline has no update
+ // operation for a custom action type, so a change to any of them is a replacement:
+ // create the new identity, then best-effort delete the old one it superseded.
+ if (previousPhysicalId == null || previousPhysicalId.isBlank()
+ || !previousPhysicalId.equals(physicalId)) {
+ codePipelineService.handle("CreateCustomActionType", request, ctx.region(), ctx.accountId());
+ if (previousPhysicalId != null && !previousPhysicalId.isBlank()) {
+ delete("AWS::CodePipeline::CustomActionType", previousPhysicalId, ctx.region());
+ }
+ }
+ r.setPhysicalId(physicalId);
+ }
+
+ private void provisionWebhook(StackResource r, JsonNode props, ProvisionContext ctx) {
+ ObjectNode webhook = (ObjectNode) lowerKeys(ctx.engine().resolveNode(props));
+ JsonNode registerNode = webhook.remove("registerWithThirdParty");
+ boolean register = registerNode != null && registerNode.asBoolean(false);
+ String previousPhysicalId = r.getPhysicalId();
+ boolean update = previousPhysicalId != null && !previousPhysicalId.isBlank();
+ String name = webhook.path("name").asText(null);
+ boolean rename = update && name != null && !name.isBlank() && !name.equals(previousPhysicalId);
+ if (name == null || name.isBlank()) {
+ name = update ? previousPhysicalId : ctx.generatePhysicalName(r.getLogicalId(), 100, false);
+ webhook.put("name", name);
+ }
+ JsonNode response = codePipelineService.handle("PutWebhook",
+ mapper.createObjectNode().set("webhook", webhook), ctx.region(), ctx.accountId());
+ if (register) {
+ codePipelineService.handle("RegisterWebhookWithThirdParty",
+ mapper.createObjectNode().put("webhookName", name), ctx.region(), ctx.accountId());
+ }
+ // Name is this resource's identity; PutWebhook upserts under the new name unconditionally,
+ // so a rename must also clean up the webhook the stack previously owned or it's orphaned.
+ if (rename) {
+ delete("AWS::CodePipeline::Webhook", previousPhysicalId, ctx.region());
+ }
+ r.setPhysicalId(name);
+ r.getAttributes().put("Url", response.path("webhook").path("url").asText(""));
+ }
+
+ /**
+ * Recursively lowercases the first letter of every object key — except inside
+ * {@code Configuration} maps, whose keys are opaque provider-defined strings
+ * ({@code Owner}, {@code Repo}, {@code ProjectName}, ...) that the action executors
+ * match verbatim.
+ */
+ private JsonNode lowerKeys(JsonNode node) {
+ if (node instanceof ObjectNode objectNode) {
+ ObjectNode result = mapper.createObjectNode();
+ objectNode.fields().forEachRemaining(entry -> {
+ String key = entry.getKey();
+ if ("Configuration".equals(key)) {
+ result.set("configuration", entry.getValue().deepCopy());
+ return;
+ }
+ String lowered = key.isEmpty()
+ ? key : Character.toLowerCase(key.charAt(0)) + key.substring(1);
+ result.set(lowered, lowerKeys(entry.getValue()));
+ });
+ return result;
+ }
+ if (node instanceof ArrayNode arrayNode) {
+ ArrayNode result = mapper.createArrayNode();
+ arrayNode.forEach(entry -> result.add(lowerKeys(entry)));
+ return result;
+ }
+ return node;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CodePipelineCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CodePipelineCfnIntegrationTest.java
new file mode 100644
index 0000000000..a8e82d808b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CodePipelineCfnIntegrationTest.java
@@ -0,0 +1,120 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * Provisions an {@code AWS::CodePipeline::Pipeline} through a CloudFormation stack and
+ * asserts the specific {@code Ref} and {@code Fn::GetAtt} values — a status-only
+ * assertion would pass even for an unmapped type stubbed as a successful no-op.
+ */
+@QuarkusTest
+class CodePipelineCfnIntegrationTest {
+
+ private static final String CFN_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260808/us-east-1/cloudformation/aws4_request";
+ private static final String STACK = "codepipeline-cfn-it";
+
+ private static final String TEMPLATE = """
+ {
+ "Resources": {
+ "Pipeline": {
+ "Type": "AWS::CodePipeline::Pipeline",
+ "Properties": {
+ "Name": "cfn-provisioned-pipeline",
+ "RoleArn": "arn:aws:iam::000000000000:role/cp",
+ "ArtifactStore": {"Type": "S3", "Location": "cfn-artifacts"},
+ "Stages": [
+ {
+ "Name": "Gate",
+ "Actions": [
+ {
+ "Name": "HumanGate",
+ "ActionTypeId": {"Category": "Approval", "Owner": "AWS",
+ "Provider": "Manual", "Version": "1"},
+ "RunOrder": 1
+ }
+ ]
+ },
+ {
+ "Name": "Release",
+ "Actions": [
+ {
+ "Name": "ReleaseGate",
+ "ActionTypeId": {"Category": "Approval", "Owner": "AWS",
+ "Provider": "Manual", "Version": "1"},
+ "RunOrder": 1
+ }
+ ]
+ }
+ ]
+ }
+ }
+ },
+ "Outputs": {
+ "PipelineRef": {"Value": {"Ref": "Pipeline"}},
+ "PipelineVersion": {"Value": {"Fn::GetAtt": ["Pipeline", "Version"]}}
+ }
+ }
+ """;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void pipelineStackExposesRefAndVersionAndCreatesThePipeline() {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", STACK)
+ .formParam("TemplateBody", TEMPLATE)
+ .when().post("/").then().statusCode(200);
+
+ String stacks = given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", STACK)
+ .when().post("/").then().statusCode(200).extract().asString();
+
+ assertEquals("cfn-provisioned-pipeline", outputValue(stacks, "PipelineRef"));
+ assertEquals("1", outputValue(stacks, "PipelineVersion"));
+
+ given()
+ .header("X-Amz-Target", "CodePipeline_20150709.GetPipeline")
+ .contentType("application/x-amz-json-1.1")
+ .body("{\"name\": \"cfn-provisioned-pipeline\"}")
+ .when().post("/").then()
+ .statusCode(200)
+ .body("pipeline.name", equalTo("cfn-provisioned-pipeline"))
+ .body("pipeline.stages[0].name", equalTo("Gate"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DeleteStack")
+ .formParam("StackName", STACK)
+ .when().post("/").then().statusCode(200);
+
+ given()
+ .header("X-Amz-Target", "CodePipeline_20150709.GetPipeline")
+ .contentType("application/x-amz-json-1.1")
+ .body("{\"name\": \"cfn-provisioned-pipeline\"}")
+ .when().post("/").then()
+ .statusCode(400);
+ }
+
+ private static String outputValue(String xml, String key) {
+ return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/InlineZipCfnResponseModuleTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/InlineZipCfnResponseModuleTest.java
new file mode 100644
index 0000000000..c1da0f9fc8
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/InlineZipCfnResponseModuleTest.java
@@ -0,0 +1,63 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Inline {@code ZipFile} Lambda packages must carry the cfn-response module AWS injects
+ * for that code path — custom-resource handlers in AWS Solutions templates (e.g. Landing
+ * Zone Accelerator's installer stack) {@code require('cfn-response')} / {@code import
+ * cfnresponse} and fail at init without it.
+ */
+class InlineZipCfnResponseModuleTest {
+
+ private static Map<String, String> unzip(String base64) throws Exception {
+ Map<String, String> entries = new HashMap<>();
+ try (ZipInputStream zis = new ZipInputStream(
+ new ByteArrayInputStream(Base64.getDecoder().decode(base64)))) {
+ ZipEntry entry;
+ while ((entry = zis.getNextEntry()) != null) {
+ entries.put(entry.getName(), new String(zis.readAllBytes(), StandardCharsets.UTF_8));
+ }
+ }
+ return entries;
+ }
+
+ @Test
+ void nodeZipCarriesRequirableCfnResponseModule() throws Exception {
+ Map<String, String> entries = unzip(InlineZipPackager.sourceToZipBase64(
+ "exports.handler = async () => {};", "index.handler", "nodejs22.x"));
+
+ assertEquals("exports.handler = async () => {};", entries.get("index.js"));
+ assertTrue(entries.containsKey("node_modules/cfn-response/package.json"));
+ String module = entries.get("node_modules/cfn-response/cfn-response.js");
+ assertTrue(module.contains("exports.send"));
+ // Floci's ResponseURL is plain http on the emulator port, so the module must
+ // pick the transport and port from the URL instead of hardcoding https:443.
+ assertTrue(module.contains("require(\"http\")"));
+ assertTrue(module.contains("parsedUrl.port"));
+ }
+
+ @Test
+ void pythonZipCarriesCfnresponseModule() throws Exception {
+ Map<String, String> entries = unzip(InlineZipPackager.sourceToZipBase64(
+ "def handler(event, context):\n pass\n", "index.handler", "python3.12"));
+
+ assertTrue(entries.containsKey("index.py"));
+ String module = entries.get("cfnresponse.py");
+ assertTrue(module.contains("def send("));
+ assertTrue(module.contains("HTTPConnection"));
+ assertFalse(entries.containsKey("node_modules/cfn-response/cfn-response.js"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/InlineZipPackagerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/InlineZipPackagerTest.java
new file mode 100644
index 0000000000..9cd9560744
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/InlineZipPackagerTest.java
@@ -0,0 +1,45 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.util.Base64;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** The injected {@code cfnresponse} shim, packaged alongside inline Python custom-resource code. */
+class InlineZipPackagerTest {
+
+ @Test
+ void pythonCallbackBodyIsUtf8EncodedBeforeSendingOverHttp() throws Exception {
+ String zipBase64 = InlineZipPackager.sourceToZipBase64(
+ "def handler(event, context):\n pass\n", "index.handler", "python3.12");
+
+ String cfnResponsePy = readZipEntry(zipBase64, "cfnresponse.py");
+
+ // http.client encodes a str body as latin-1 by default, raising UnicodeEncodeError for any
+ // response payload (e.g. a non-Latin-1 Reason or Data value) outside that range. The body
+ // passed to conn.request must already be UTF-8 encoded bytes, not the raw str.
+ assertTrue(cfnResponsePy.contains("response_body.encode('utf-8')")
+ || cfnResponsePy.contains("response_body.encode(\"utf-8\")"),
+ "cfnresponse.py must UTF-8 encode the response body before conn.request:\n" + cfnResponsePy);
+ }
+
+ private static String readZipEntry(String zipBase64, String entryName) throws Exception {
+ byte[] zipBytes = Base64.getDecoder().decode(zipBase64);
+ try (var zis = new ZipInputStream(new ByteArrayInputStream(zipBytes))) {
+ ZipEntry entry;
+ while ((entry = zis.getNextEntry()) != null) {
+ if (entry.getName().equals(entryName)) {
+ var out = new ByteArrayOutputStream();
+ zis.transferTo(out);
+ return out.toString(java.nio.charset.StandardCharsets.UTF_8);
+ }
+ }
+ }
+ throw new AssertionError("Zip entry not found: " + entryName);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodeBuildCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodeBuildCfnProvisionerTest.java
new file mode 100644
index 0000000000..87d65fa26a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodeBuildCfnProvisionerTest.java
@@ -0,0 +1,117 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.codebuild.CodeBuildJsonHandler;
+import jakarta.ws.rs.core.Response;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.HashMap;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/** The CodeBuild CFN provisioner in isolation, with the handler mocked. */
+class CodeBuildCfnProvisionerTest {
+
+ private final CodeBuildJsonHandler handler = mock(CodeBuildJsonHandler.class);
+ private final ObjectMapper mapper = new ObjectMapper();
+ private final CodeBuildCfnProvisioner provisioner =
+ new CodeBuildCfnProvisioner(handler, mock(RegionResolver.class), mapper);
+
+ private ProvisionContext ctx() {
+ var engine = mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine.class);
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ return new ProvisionContext(engine, "us-east-1", "000000000000", "cfn-stack");
+ }
+
+ @Test
+ void projectPropertiesAreLoweredIncludingIrregularBuildspec() throws Exception {
+ ObjectNode project = mapper.createObjectNode();
+ project.putObject("project").put("arn",
+ "arn:aws:codebuild:us-east-1:000000000000:project/installer");
+ when(handler.handle(eq("CreateProject"), any(), eq("us-east-1"), eq("000000000000")))
+ .thenReturn(Response.ok(project).build());
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("Name", "installer");
+ props.put("ServiceRole", "arn:aws:iam::000000000000:role/build");
+ ObjectNode source = props.putObject("Source");
+ source.put("Type", "CODEPIPELINE");
+ source.put("BuildSpec", "version: 0.2");
+ props.putObject("Artifacts").put("Type", "CODEPIPELINE");
+ ObjectNode environment = props.putObject("Environment");
+ environment.put("ComputeType", "BUILD_GENERAL1_MEDIUM");
+ environment.put("Image", "aws/codebuild/standard:7.0");
+ environment.putArray("EnvironmentVariables").addObject()
+ .put("Name", "PREFIX").put("Value", "AWSAccelerator").put("Type", "PLAINTEXT");
+
+ StackResource r = new StackResource();
+ r.setLogicalId("Installer");
+ r.setResourceType("AWS::CodeBuild::Project");
+ r.setAttributes(new HashMap<>());
+ provisioner.provision(r, props, ctx());
+
+ ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
+ verify(handler).handle(eq("CreateProject"), request.capture(), eq("us-east-1"), eq("000000000000"));
+ JsonNode sent = request.getValue();
+ assertEquals("installer", sent.path("name").asText());
+ assertEquals("CODEPIPELINE", sent.path("source").path("type").asText());
+ assertEquals("version: 0.2", sent.path("source").path("buildspec").asText());
+ assertEquals("BUILD_GENERAL1_MEDIUM", sent.path("environment").path("computeType").asText());
+ assertEquals("PREFIX", sent.path("environment").path("environmentVariables")
+ .get(0).path("name").asText());
+
+ assertEquals("installer", r.getPhysicalId());
+ assertEquals("arn:aws:codebuild:us-east-1:000000000000:project/installer",
+ r.getAttributes().get("Arn"));
+ }
+
+ @Test
+ void existingPhysicalIdRoutesToUpdateProject() throws Exception {
+ when(handler.handle(eq("UpdateProject"), any(), any(), any()))
+ .thenReturn(Response.ok(mapper.createObjectNode()).build());
+ StackResource r = new StackResource();
+ r.setLogicalId("Installer");
+ r.setResourceType("AWS::CodeBuild::Project");
+ r.setAttributes(new HashMap<>());
+ r.setPhysicalId("installer");
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("Name", "installer");
+ provisioner.provision(r, props, ctx());
+
+ verify(handler).handle(eq("UpdateProject"), any(), eq("us-east-1"), eq("000000000000"));
+ }
+
+ @Test
+ void mapEntityFromHandlerIsConvertedNotDropped() throws Exception {
+ // The real handler returns Response.ok(Map.of(...)) — a Map/POJO entity, never a JsonNode —
+ // so a plain instanceof check silently drops the project and falls back to the guessed ARN.
+ java.util.Map<String, Object> project = new java.util.HashMap<>();
+ project.put("arn", "arn:aws:codebuild:us-east-1:000000000000:project/from-handler");
+ java.util.Map<String, Object> entity = java.util.Map.of("project", project);
+ when(handler.handle(eq("CreateProject"), any(), eq("us-east-1"), eq("000000000000")))
+ .thenReturn(Response.ok(entity).build());
+
+ ObjectNode props = mapper.createObjectNode();
+ props.put("Name", "installer");
+ StackResource r = new StackResource();
+ r.setLogicalId("Installer");
+ r.setResourceType("AWS::CodeBuild::Project");
+ r.setAttributes(new HashMap<>());
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("arn:aws:codebuild:us-east-1:000000000000:project/from-handler",
+ r.getAttributes().get("Arn"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodePipelineCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodePipelineCfnProvisionerTest.java
new file mode 100644
index 0000000000..c4271acdf3
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CodePipelineCfnProvisionerTest.java
@@ -0,0 +1,337 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.codepipeline.CodePipelineService;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.HashMap;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.argThat;
+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 CodePipeline CFN provisioner in isolation, with the service mocked. */
+class CodePipelineCfnProvisionerTest {
+
+ private final CodePipelineService service = mock(CodePipelineService.class);
+ private final ObjectMapper mapper = new ObjectMapper();
+ private final CodePipelineCfnProvisioner provisioner =
+ new CodePipelineCfnProvisioner(service, mock(RegionResolver.class), mapper);
+
+ private ProvisionContext ctx() {
+ var engine = mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine.class);
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ return new ProvisionContext(engine, "us-east-1", "000000000000", "cfn-stack");
+ }
+
+ private StackResource resource(String type) {
+ StackResource r = new StackResource();
+ r.setLogicalId("MyResource");
+ r.setResourceType(type);
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+
+ private ObjectNode pipelineProps(String name) {
+ ObjectNode props = mapper.createObjectNode();
+ if (name != null) {
+ props.put("Name", name);
+ }
+ props.put("RoleArn", "arn:aws:iam::000000000000:role/cp");
+ props.putObject("ArtifactStore").put("Type", "S3").put("Location", "bucket");
+ ObjectNode stage = props.putArray("Stages").addObject();
+ stage.put("Name", "Gate");
+ ObjectNode action = stage.putArray("Actions").addObject();
+ action.put("Name", "HumanGate");
+ action.putObject("ActionTypeId")
+ .put("Category", "Approval").put("Owner", "AWS").put("Provider", "Manual").put("Version", "1");
+ action.putObject("Configuration")
+ .put("ProjectName", "installer-build").put("Owner", "awslabs");
+ return props;
+ }
+
+ @Test
+ void pipelinePropertiesAreLoweredAndVersionExposedForGetAtt() {
+ when(service.handle(eq("CreatePipeline"), any(), eq("us-east-1"), eq("000000000000")))
+ .thenReturn(mapper.createObjectNode().set("pipeline",
+ mapper.createObjectNode().put("version", 1)));
+ StackResource r = resource("AWS::CodePipeline::Pipeline");
+
+ provisioner.provision(r, pipelineProps("the-pipeline"), ctx());
+
+ ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
+ verify(service).handle(eq("CreatePipeline"), request.capture(), eq("us-east-1"), eq("000000000000"));
+ JsonNode declaration = request.getValue().path("pipeline");
+ assertEquals("the-pipeline", declaration.path("name").asText());
+ assertEquals("arn:aws:iam::000000000000:role/cp", declaration.path("roleArn").asText());
+ assertEquals("S3", declaration.path("artifactStore").path("type").asText());
+ JsonNode action = declaration.path("stages").get(0).path("actions").get(0);
+ assertEquals("Approval", action.path("actionTypeId").path("category").asText());
+ // Configuration keys are provider-defined strings the executors match verbatim —
+ // they must survive the PascalCase→camelCase transform untouched.
+ assertEquals("installer-build", action.path("configuration").path("ProjectName").asText());
+ assertEquals("awslabs", action.path("configuration").path("Owner").asText());
+
+ assertEquals("the-pipeline", r.getPhysicalId());
+ assertEquals("1", r.getAttributes().get("Version"));
+ }
+
+ @Test
+ void pipelineWithoutNameGetsGeneratedPhysicalName() {
+ when(service.handle(eq("CreatePipeline"), any(), any(), any()))
+ .thenReturn(mapper.createObjectNode().set("pipeline",
+ mapper.createObjectNode().put("version", 1)));
+ StackResource r = resource("AWS::CodePipeline::Pipeline");
+
+ provisioner.provision(r, pipelineProps(null), ctx());
+
+ assertTrue(r.getPhysicalId().startsWith("cfn-stack-MyResource-"));
+ }
+
+ @Test
+ void existingPhysicalIdRoutesToUpdatePipeline() {
+ when(service.handle(eq("UpdatePipeline"), any(), any(), any()))
+ .thenReturn(mapper.createObjectNode().set("pipeline",
+ mapper.createObjectNode().put("version", 2)));
+ StackResource r = resource("AWS::CodePipeline::Pipeline");
+ r.setPhysicalId("the-pipeline");
+
+ provisioner.provision(r, pipelineProps("the-pipeline"), ctx());
+
+ verify(service).handle(eq("UpdatePipeline"), any(), eq("us-east-1"), eq("000000000000"));
+ assertEquals("2", r.getAttributes().get("Version"));
+ }
+
+ @Test
+ void disabledInboundTransitionsAreApplied() {
+ when(service.handle(eq("CreatePipeline"), any(), any(), any()))
+ .thenReturn(mapper.createObjectNode().set("pipeline",
+ mapper.createObjectNode().put("version", 1)));
+ ObjectNode props = pipelineProps("gated");
+ props.putArray("DisableInboundStageTransitions").addObject()
+ .put("StageName", "Gate").put("Reason", "hold");
+ StackResource r = resource("AWS::CodePipeline::Pipeline");
+
+ provisioner.provision(r, props, ctx());
+
+ ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
+ verify(service).handle(eq("DisableStageTransition"), request.capture(), any(), any());
+ assertEquals("Gate", request.getValue().path("stageName").asText());
+ assertEquals("hold", request.getValue().path("reason").asText());
+ }
+
+ @Test
+ void webhookExposesUrlForGetAtt() {
+ when(service.handle(eq("PutWebhook"), any(), any(), any()))
+ .thenReturn(mapper.createObjectNode().set("webhook", mapper.createObjectNode()
+ .put("url", "http://localhost:4566/codepipeline/webhooks/hook")));
+ ObjectNode props = mapper.createObjectNode();
+ props.put("Name", "hook");
+ props.put("TargetPipeline", "the-pipeline");
+ props.put("TargetAction", "Source");
+ StackResource r = resource("AWS::CodePipeline::Webhook");
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("hook", r.getPhysicalId());
+ assertEquals("http://localhost:4566/codepipeline/webhooks/hook", r.getAttributes().get("Url"));
+ }
+
+ @Test
+ void customActionTypeBuildsCompositePhysicalId() {
+ when(service.handle(eq("CreateCustomActionType"), any(), any(), any()))
+ .thenReturn(mapper.createObjectNode());
+ ObjectNode props = mapper.createObjectNode();
+ props.put("Category", "Build");
+ props.put("Provider", "MyBuilder");
+ props.put("Version", "2");
+ StackResource r = resource("AWS::CodePipeline::CustomActionType");
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("Build|Custom|MyBuilder|2", r.getPhysicalId());
+ }
+
+ @Test
+ void customActionTypeIdentityChangeCreatesNewAndDeletesOld() {
+ when(service.handle(eq("CreateCustomActionType"), any(), any(), any()))
+ .thenReturn(mapper.createObjectNode());
+ ObjectNode props = mapper.createObjectNode();
+ props.put("Category", "Build");
+ props.put("Provider", "MyBuilder");
+ props.put("Version", "3");
+ StackResource r = resource("AWS::CodePipeline::CustomActionType");
+ // Previously provisioned under Version "2" — an update to Version "3" changes identity.
+ r.setPhysicalId("Build|Custom|MyBuilder|2");
+
+ provisioner.provision(r, props, ctx());
+
+ verify(service).handle(eq("CreateCustomActionType"), any(), eq("us-east-1"), eq("000000000000"));
+ ArgumentCaptor<JsonNode> deleteRequest = ArgumentCaptor.forClass(JsonNode.class);
+ verify(service).handle(eq("DeleteCustomActionType"), deleteRequest.capture(), any(), any());
+ assertEquals("Build", deleteRequest.getValue().path("category").asText());
+ assertEquals("MyBuilder", deleteRequest.getValue().path("provider").asText());
+ assertEquals("2", deleteRequest.getValue().path("version").asText());
+ assertEquals("Build|Custom|MyBuilder|3", r.getPhysicalId());
+ }
+
+ @Test
+ void removedTransitionRestrictionIsReEnabledOnUpdate() {
+ when(service.handle(eq("UpdatePipeline"), any(), any(), any()))
+ .thenReturn(mapper.createObjectNode().set("pipeline",
+ mapper.createObjectNode().put("version", 2)));
+ // Previously deployed by this stack with "Gate" disabled; this update's template no
+ // longer lists it, so it must be re-enabled (tracked via the stack-owned attribute,
+ // never an externally-disabled stage this resource never claimed).
+ ObjectNode props = pipelineProps("gated");
+ StackResource r = resource("AWS::CodePipeline::Pipeline");
+ r.setPhysicalId("gated");
+ r.getAttributes().put("__FlociCodePipelineDisabledStages", "Gate");
+
+ provisioner.provision(r, props, ctx());
+
+ ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
+ verify(service).handle(eq("EnableStageTransition"), request.capture(), eq("us-east-1"), eq("000000000000"));
+ assertEquals("Gate", request.getValue().path("stageName").asText());
+ }
+
+ @Test
+ void registerWithThirdPartyReadsResolvedValueNotRawIntrinsic() {
+ when(service.handle(eq("PutWebhook"), any(), any(), any()))
+ .thenReturn(mapper.createObjectNode().set("webhook",
+ mapper.createObjectNode().put("url", "http://localhost/hook")));
+ ObjectNode props = mapper.createObjectNode();
+ props.put("Name", "hook");
+ props.put("TargetPipeline", "the-pipeline");
+ props.put("TargetAction", "Source");
+ // Simulate an unresolved intrinsic (e.g. Fn::If) that only resolves to true —
+ // raw props must never be consulted directly for this boolean.
+ props.putObject("RegisterWithThirdParty").put("Fn::If", "SomeCondition");
+ StackResource r = resource("AWS::CodePipeline::Webhook");
+ var engine = mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine.class);
+ when(engine.resolveNode(any())).thenAnswer(inv -> {
+ ObjectNode resolved = ((ObjectNode) inv.getArgument(0)).deepCopy();
+ resolved.put("RegisterWithThirdParty", true);
+ return resolved;
+ });
+ ProvisionContext ctx = new ProvisionContext(engine, "us-east-1", "000000000000", "cfn-stack");
+
+ provisioner.provision(r, props, ctx);
+
+ verify(service).handle(eq("RegisterWebhookWithThirdParty"), any(), any(), any());
+ }
+
+ @Test
+ void externallyDisabledStageIsNeverReEnabled() {
+ when(service.handle(eq("UpdatePipeline"), any(), any(), any()))
+ .thenReturn(mapper.createObjectNode().set("pipeline",
+ mapper.createObjectNode().put("version", 2)));
+ // This stack has run the tracking code since it was created and never disabled "Gate"
+ // itself (empty, non-null attribute) -- some outside actor (a manual gate, a human)
+ // disabled it, and an unrelated update must not touch it.
+ ObjectNode props = pipelineProps("gated");
+ StackResource r = resource("AWS::CodePipeline::Pipeline");
+ r.setPhysicalId("gated");
+ r.getAttributes().put("__FlociCodePipelineDisabledStages", "");
+
+ provisioner.provision(r, props, ctx());
+
+ verify(service, never()).handle(eq("EnableStageTransition"), any(), any(), any());
+ }
+
+ @Test
+ void legacyResourcePredatingTrackingAttributeReconcilesAllDeclaredStages() {
+ when(service.handle(eq("UpdatePipeline"), any(), any(), any()))
+ .thenReturn(mapper.createObjectNode().set("pipeline",
+ mapper.createObjectNode().put("version", 2)));
+ // A resource stored by a provisioner version predating DISABLED_STAGES_ATTR has no
+ // tracking attribute at all -- the very first post-upgrade update must still reconcile
+ // (fall back to every declared stage) instead of leaving a removed entry stuck disabled.
+ ObjectNode props = pipelineProps("gated");
+ StackResource r = resource("AWS::CodePipeline::Pipeline");
+ r.setPhysicalId("gated");
+
+ provisioner.provision(r, props, ctx());
+
+ ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
+ verify(service).handle(eq("EnableStageTransition"), request.capture(), eq("us-east-1"), eq("000000000000"));
+ assertEquals("Gate", request.getValue().path("stageName").asText());
+ }
+
+ @Test
+ void failedTransitionReconciliationDeletesTheNewlyCreatedReplacementPipeline() {
+ when(service.handle(eq("CreatePipeline"), any(), any(), any()))
+ .thenReturn(mapper.createObjectNode().set("pipeline",
+ mapper.createObjectNode().put("version", 1)));
+ when(service.handle(eq("DisableStageTransition"), any(), any(), any()))
+ .thenThrow(new RuntimeException("boom"));
+ StackResource r = resource("AWS::CodePipeline::Pipeline");
+ r.setPhysicalId("old-name");
+ ObjectNode props = pipelineProps("new-name");
+ props.putArray("DisableInboundStageTransitions").addObject()
+ .put("StageName", "Gate").put("Reason", "hold");
+
+ RuntimeException thrown = org.junit.jupiter.api.Assertions.assertThrows(RuntimeException.class,
+ () -> provisioner.provision(r, props, ctx()));
+ assertEquals("boom", thrown.getMessage());
+
+ ArgumentCaptor<JsonNode> deleteRequest = ArgumentCaptor.forClass(JsonNode.class);
+ verify(service).handle(eq("DeletePipeline"), deleteRequest.capture(), any(), any());
+ assertEquals("new-name", deleteRequest.getValue().path("name").asText());
+ // The old pipeline must survive an aborted replacement -- it's still the resource
+ // CloudFormation will keep tracking after reverting this failed update.
+ verify(service, never()).handle(eq("DeletePipeline"),
+ argThat(n -> "old-name".equals(n.path("name").asText())), any(), any());
+ }
+
+ @Test
+ void pipelineRenameReplacesRatherThanUpdatingWrongResource() {
+ when(service.handle(eq("CreatePipeline"), any(), any(), any()))
+ .thenReturn(mapper.createObjectNode().set("pipeline",
+ mapper.createObjectNode().put("version", 1)));
+ StackResource r = resource("AWS::CodePipeline::Pipeline");
+ r.setPhysicalId("old-name");
+
+ provisioner.provision(r, pipelineProps("new-name"), ctx());
+
+ verify(service, never()).handle(eq("UpdatePipeline"), any(), any(), any());
+ ArgumentCaptor<JsonNode> createRequest = ArgumentCaptor.forClass(JsonNode.class);
+ verify(service).handle(eq("CreatePipeline"), createRequest.capture(), any(), any());
+ assertEquals("new-name", createRequest.getValue().path("pipeline").path("name").asText());
+ ArgumentCaptor<JsonNode> deleteRequest = ArgumentCaptor.forClass(JsonNode.class);
+ verify(service).handle(eq("DeletePipeline"), deleteRequest.capture(), any(), any());
+ assertEquals("old-name", deleteRequest.getValue().path("name").asText());
+ assertEquals("new-name", r.getPhysicalId());
+ }
+
+ @Test
+ void webhookRenameDeletesTheOldNameInsteadOfOrphaningIt() {
+ when(service.handle(eq("PutWebhook"), any(), any(), any()))
+ .thenReturn(mapper.createObjectNode().set("webhook",
+ mapper.createObjectNode().put("url", "http://localhost/new-hook")));
+ ObjectNode props = mapper.createObjectNode();
+ props.put("Name", "new-hook");
+ props.put("TargetPipeline", "the-pipeline");
+ props.put("TargetAction", "Source");
+ StackResource r = resource("AWS::CodePipeline::Webhook");
+ r.setPhysicalId("old-hook");
+
+ provisioner.provision(r, props, ctx());
+
+ ArgumentCaptor<JsonNode> deleteRequest = ArgumentCaptor.forClass(JsonNode.class);
+ verify(service).handle(eq("DeleteWebhook"), deleteRequest.capture(), any(), any());
+ assertEquals("old-hook", deleteRequest.getValue().path("name").asText());
+ assertEquals("new-hook", r.getPhysicalId());
+ }
+}