Light, fluffy, and always free - The AWS Local Emulator alternative
feat(codepipeline): emit EventBridge state-change events and SNS approval notifications (#4616)
Sam Fakhreddinea833551d03de
diff --git a/docs/services/codepipeline.md b/docs/services/codepipeline.mdindex 1de95679a1..9fcee353ec 100644--- a/docs/services/codepipeline.md+++ b/docs/services/codepipeline.md@@ -72,6 +72,21 @@ as `Approved` or `Rejected`, limits `result.summary` to 512 characters, returns`InvalidApprovalTokenException` for unknown tokens, and returns`ApprovalAlreadyCompletedException` if the same approval token is reused after completion.+## Events and notifications++Executions publish the real `aws.codepipeline` state-change events to the **default+EventBridge bus**: `CodePipeline Pipeline Execution State Change` (STARTED, SUCCEEDED,+FAILED, STOPPING, STOPPED, RESUMED), `CodePipeline Stage Execution State Change`, and+`CodePipeline Action Execution State Change`, with the pipeline ARN in `resources` and+the documented detail fields. EventBridge rules matching `{"source":+["aws.codepipeline"]}` deliver them to any configured target. Publishing is best-effort+and never fails the execution.++A Manual approval action whose configuration sets `NotificationArn` publishes the+approval-needed message (subject `APPROVAL NEEDED: AWS CodePipeline ...`, JSON body with+the approval token, `expires` as an ISO-8601 timestamp, `consoleLink`, `approvalReviewLink`,+`CustomData` and `ExternalEntityLink`) to that SNS topic when it starts waiting. The subject is truncated to SNS's 100-character limit.+## Configuration| Variable | Default | Description |diff --git a/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineEventPublisher.java b/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineEventPublisher.javanew file mode 100644index 0000000000..07151ff063--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineEventPublisher.java@@ -0,0 +1,180 @@+package io.github.hectorvent.floci.services.codepipeline;++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.AwsArnUtils;+import io.github.hectorvent.floci.core.common.RequestScopes;+import io.github.hectorvent.floci.services.codepipeline.model.CodePipelineExecution;+import io.github.hectorvent.floci.services.codepipeline.model.CodePipelineExecution.ActionExecution;+import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;+import io.github.hectorvent.floci.services.sns.SnsService;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.time.Instant;+import java.time.ZoneOffset;+import java.time.format.DateTimeFormatter;+import java.util.HashMap;+import java.util.List;+import java.util.Map;++/**+ * Publishes the {@code aws.codepipeline} state-change events (pipeline, stage, and action)+ * to the default EventBridge bus, and the SNS approval-needed notification, matching the+ * shapes real CodePipeline emits. All publishing is best-effort: a failing delivery never+ * fails the pipeline execution.+ */+@ApplicationScoped+public class CodePipelineEventPublisher {++ private static final Logger LOG = Logger.getLogger(CodePipelineEventPublisher.class);+ private static final int MAX_SNS_SUBJECT_LENGTH = 100;+ private static final String CONSOLE_URL = "https://console.aws.amazon.com/codepipeline/home";+ /** The approval message's {@code expires} is to the minute, e.g. 2016-07-07T20:22Z. */+ private static final DateTimeFormatter MINUTE_FORMAT =+ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm'Z'").withZone(ZoneOffset.UTC);++ private final EventBridgeService eventBridgeService;+ private final SnsService snsService;+ private final ObjectMapper mapper;++ @Inject+ public CodePipelineEventPublisher(EventBridgeService eventBridgeService,+ SnsService snsService, ObjectMapper mapper) {+ this.eventBridgeService = eventBridgeService;+ this.snsService = snsService;+ this.mapper = mapper;+ }++ public void pipelineStateChange(CodePipelineExecution execution, String state) {+ ObjectNode detail = baseDetail(execution);+ detail.put("state", state);+ detail.put("execution-mode", execution.getExecutionMode());+ if (execution.getStartTime() != null) {+ detail.put("start-time", isoTimestamp(execution.getStartTime()));+ }+ publish(execution, "CodePipeline Pipeline Execution State Change", detail);+ }++ public void stageStateChange(CodePipelineExecution execution, String stageName, String state) {+ ObjectNode detail = baseDetail(execution);+ detail.put("stage", stageName);+ detail.put("state", state);+ publish(execution, "CodePipeline Stage Execution State Change", detail);+ }++ public void actionStateChange(CodePipelineExecution execution, ActionExecution action, String state) {+ ObjectNode detail = baseDetail(execution);+ detail.put("stage", action.getStageName());+ detail.put("action", action.getActionName());+ detail.put("state", state);+ detail.put("region", execution.getRegion());+ detail.putObject("type")+ .put("owner", action.getOwner())+ .put("provider", action.getProvider())+ .put("category", action.getCategory())+ .put("version", "1");+ if (action.getExternalExecutionId() != null || action.getSummary() != null+ || action.getErrorDetails() != null) {+ ObjectNode result = detail.putObject("execution-result");+ if (action.getExternalExecutionId() != null) {+ result.put("external-execution-id", action.getExternalExecutionId());+ }+ if (action.getSummary() != null) {+ result.put("external-execution-summary", action.getSummary());+ }+ if (action.getErrorDetails() != null) {+ Object code = action.getErrorDetails().get("code");+ if (code != null) {+ result.put("error-code", code.toString());+ }+ }+ }+ publish(execution, "CodePipeline Action Execution State Change", detail);+ }++ /**+ * The SNS notification a Manual approval action sends when it starts waiting.+ *+ * <p>Runs on a worker thread with no request context, so the publish is wrapped in+ * {@link RequestScopes#runAs} to resolve the topic in the pipeline's own account.+ * The subject is truncated to the 100 characters SNS allows.</p>+ */+ public void approvalNeeded(CodePipelineExecution execution, ActionExecution action,+ String notificationArn, String customData,+ String externalEntityLink, double expires) {+ try {+ ObjectNode message = mapper.createObjectNode();+ String consoleLink = CONSOLE_URL + "?region=" + execution.getRegion()+ + "#/view/" + execution.getPipelineName();+ message.put("region", execution.getRegion());+ message.put("consoleLink", consoleLink);+ ObjectNode approval = message.putObject("approval");+ approval.put("pipelineName", execution.getPipelineName());+ approval.put("stageName", action.getStageName());+ approval.put("actionName", action.getActionName());+ approval.put("token", action.getToken());+ approval.put("expires", MINUTE_FORMAT.format(Instant.ofEpochSecond((long) expires)));+ approval.put("approvalReviewLink", consoleLink + "/" + action.getStageName()+ + "/" + action.getActionName() + "/approve/" + action.getToken());+ if (customData != null && !customData.isBlank()) {+ approval.put("customData", customData);+ }+ if (externalEntityLink != null && !externalEntityLink.isBlank()) {+ approval.put("externalEntityLink", externalEntityLink);+ }+ String subject = "APPROVAL NEEDED: AWS CodePipeline " + execution.getPipelineName()+ + " for stage " + action.getStageName()+ + " action " + action.getActionName();+ String truncated = subject.length() > MAX_SNS_SUBJECT_LENGTH+ ? subject.substring(0, MAX_SNS_SUBJECT_LENGTH) : subject;+ RequestScopes.runAs(execution.getAccountId(), () -> snsService.publish(+ notificationArn, null, message.toString(), truncated, execution.getRegion()));+ } catch (Exception e) {+ LOG.warnv("CodePipeline approval notification to {0} skipped: {1}",+ notificationArn, e.getMessage());+ }+ }++ /** Epoch seconds (with fraction) as the ISO-8601 UTC timestamp CodePipeline emits, e.g. 2023-10-26T13:31:39.604Z. */+ private static String isoTimestamp(double epochSeconds) {+ return Instant.ofEpochMilli(Math.round(epochSeconds * 1000)).toString();+ }++ private ObjectNode baseDetail(CodePipelineExecution execution) {+ ObjectNode detail = mapper.createObjectNode();+ detail.put("pipeline", execution.getPipelineName());+ detail.put("execution-id", execution.getPipelineExecutionId());+ if (execution.getPipelineVersion() != null) {+ detail.put("version", execution.getPipelineVersion());+ }+ return detail;+ }++ private void publish(CodePipelineExecution execution, String detailType, ObjectNode detail) {+ try {+ Map<String, Object> entry = new HashMap<>();+ entry.put("Source", "aws.codepipeline");+ entry.put("DetailType", detailType);+ entry.put("Detail", detail.toString());+ entry.put("EventBusName", "default");+ entry.put("Region", execution.getRegion());+ // Always emit Resources (possibly empty): EventBridge pattern matching reads the+ // key unconditionally for rules with a "resources" filter.+ ArrayNode resources = mapper.createArrayNode();+ resources.add(AwsArnUtils.Arn.of("codepipeline", execution.getRegion(),+ execution.getAccountId(), execution.getPipelineName()).toString());+ entry.put("Resources", resources);+ // This runs on a pipeline-execution worker thread with no request context, so the+ // two-argument overload would fall back to the default (management) account and a+ // member account's EventBridge rules would never see the event. Name the bus's+ // account explicitly.+ eventBridgeService.putEvents(List.of(entry), execution.getRegion(),+ execution.getAccountId());+ } catch (Exception e) {+ LOG.warnv("CodePipeline event {0} not published: {1}", detailType, e.getMessage());+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java b/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.javaindex 0afe7d1c12..09484faea2 100644--- a/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java+++ b/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java@@ -109,6 +109,7 @@ public class CodePipelineService {private final CodeDeployService codeDeployService;private final LambdaService lambdaService;private final S3Service s3Service;+ private final CodePipelineEventPublisher eventPublisher;private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();private final ScheduledExecutorService sourcePoller = Executors.newSingleThreadScheduledExecutor();private final KeyedLockPool pipelineLocks = new KeyedLockPool();@@ -134,18 +135,35 @@ public class CodePipelineService {CodeBuildService codeBuildService, CodeDeployService codeDeployService,LambdaService lambdaService, S3Service s3Service) {this(storageFactory, mapper, codeBuildService, codeDeployService, lambdaService, s3Service,- DEFAULT_SOURCE_POLL_INTERVAL_MS);+ detachedEventPublisher(mapper), DEFAULT_SOURCE_POLL_INTERVAL_MS);}- @Injectpublic CodePipelineService(StorageFactory storageFactory, ObjectMapper mapper,CodeBuildService codeBuildService, CodeDeployService codeDeployService,LambdaService lambdaService, S3Service s3Service,EmulatorConfig config) {this(storageFactory, mapper, codeBuildService, codeDeployService, lambdaService, s3Service,+ config, detachedEventPublisher(mapper));+ }++ @Inject+ public CodePipelineService(StorageFactory storageFactory, ObjectMapper mapper,+ CodeBuildService codeBuildService, CodeDeployService codeDeployService,+ LambdaService lambdaService, S3Service s3Service,+ EmulatorConfig config, CodePipelineEventPublisher eventPublisher) {+ this(storageFactory, mapper, codeBuildService, codeDeployService, lambdaService, s3Service,+ eventPublisher,resolveSourcePollInterval(config.services().codepipeline().sourcePollIntervalMs()));}+ /**+ * A publisher with no EventBridge or SNS behind it, for the constructors built without CDI.+ * Publishing is best-effort, so each event is logged as undeliverable and dropped.+ */+ private static CodePipelineEventPublisher detachedEventPublisher(ObjectMapper mapper) {+ return new CodePipelineEventPublisher(null, null, mapper);+ }+/*** A zero or negative interval would make {@code scheduleWithFixedDelay} throw from the startup* observer and stop the whole emulator becoming ready. A misconfigured value is not worth@@ -164,7 +182,7 @@ public class CodePipelineService {private CodePipelineService(StorageFactory storageFactory, ObjectMapper mapper,CodeBuildService codeBuildService, CodeDeployService codeDeployService,LambdaService lambdaService, S3Service s3Service,- long sourcePollIntervalMs) {+ CodePipelineEventPublisher eventPublisher, long sourcePollIntervalMs) {this.pipelineStore = storageFactory.create("codepipeline", "codepipeline-pipelines.json", new TypeReference<Map<String, CodePipelinePipeline>>() {});this.executionStore = storageFactory.create(@@ -176,6 +194,7 @@ public class CodePipelineService {this.codeDeployService = codeDeployService;this.lambdaService = lambdaService;this.s3Service = s3Service;+ this.eventPublisher = eventPublisher;this.sourcePollIntervalMs = sourcePollIntervalMs;}@@ -243,6 +262,7 @@ public class CodePipelineService {execution.setActionExecutions(new ArrayList<>());execution.setStageExecutionStatuses(new LinkedHashMap<>());putExecution(execution);+ eventPublisher.pipelineStateChange(execution, "RESUMED");executor.submit(() -> runExecution(pipeline, execution));}, () -> {execution.setStatus("Failed");@@ -561,6 +581,7 @@ public class CodePipelineService {"The pipeline has reached the limit for concurrent pipeline executions", 400);}applyExecutionMode(execution);+ eventPublisher.pipelineStateChange(execution, "STARTED");try {executor.submit(() -> runExecution(pipeline, execution));} catch (RejectedExecutionException exception) {@@ -568,6 +589,7 @@ public class CodePipelineService {execution.setStatusSummary("Pipeline execution could not be scheduled.");execution.setLastUpdateTime(now());putExecution(execution);+ eventPublisher.pipelineStateChange(execution, "FAILED");throw new AwsException("ConflictException","Your request cannot be handled because the pipeline is busy handling ongoing activities. "+ "Try again later.", 400);@@ -622,6 +644,7 @@ public class CodePipelineService {});}putExecution(execution);+ eventPublisher.pipelineStateChange(execution, "STOPPING");return mapper.createObjectNode().put("pipelineExecutionId", execution.getPipelineExecutionId());}@@ -1220,18 +1243,22 @@ public class CodePipelineService {execution.getStageExecutionStatuses().put(stageName, "InProgress");execution.setLastUpdateTime(now());putExecution(execution);+ eventPublisher.stageStateChange(execution, stageName, "STARTED");runStage(pipeline, execution, stage);if ("Failed".equals(execution.getStatus())) {execution.getStageExecutionStatuses().put(stageName, "Failed");+ eventPublisher.stageStateChange(execution, stageName, "FAILED");return;}if (finishIfStopped(execution)) {+ eventPublisher.stageStateChange(execution, stageName, "STOPPED");return;}execution.getStageExecutionStatuses().put(stageName, "Succeeded");execution.setCurrentStage(null);execution.setLastUpdateTime(now());putExecution(execution);+ eventPublisher.stageStateChange(execution, stageName, "SUCCEEDED");}execution.setStatus("Succeeded");execution.setStatusSummary("Pipeline execution succeeded.");@@ -1259,6 +1286,15 @@ public class CodePipelineService {activeRuns.remove(runKey(execution));}});+ String terminalState = switch (execution.getStatus()) {+ case "Succeeded" -> "SUCCEEDED";+ case "Failed" -> "FAILED";+ case "Stopped" -> "STOPPED";+ default -> null;+ };+ if (terminalState != null) {+ eventPublisher.pipelineStateChange(execution, terminalState);+ }}// Failed and stopped executions keep their artifacts so a stage retry can reuse them. Once a newer@@ -1349,6 +1385,7 @@ public class CodePipelineService {execution.getActionExecutions().add(state);putExecution(execution);}+ eventPublisher.actionStateChange(execution, state, "STARTED");try {executeProvider(pipeline, execution, action, state);if ("InProgress".equals(state.getStatus())) {@@ -1368,6 +1405,15 @@ public class CodePipelineService {} finally {state.setLastUpdateTime(now());putExecution(execution);+ String terminalState = switch (state.getStatus()) {+ case "Succeeded" -> "SUCCEEDED";+ case "Failed" -> "FAILED";+ case "Abandoned" -> "ABANDONED";+ default -> null;+ };+ if (terminalState != null) {+ eventPublisher.actionStateChange(execution, state, terminalState);+ }}}@@ -1377,7 +1423,7 @@ public class CodePipelineService {String owner = state.getOwner();String provider = state.getProvider();if ("Approval".equals(category) && "Manual".equals(provider)) {- waitForApproval(execution, state);+ waitForApproval(execution, action, state);return;}if ("Source".equals(category) && "GitHub".equals(provider) && "ThirdParty".equals(owner)@@ -1827,10 +1873,18 @@ public class CodePipelineService {state.setExternalExecutionId(result.path("pipelineExecutionId").asText());}- private void waitForApproval(CodePipelineExecution execution, ActionExecution state) throws InterruptedException {+ private void waitForApproval(CodePipelineExecution execution, JsonNode action,+ ActionExecution state) throws InterruptedException {state.setToken(UUID.randomUUID().toString());state.setSummary("Waiting for approval.");putExecution(execution);+ String notificationArn = action.path("configuration").path("NotificationArn").asText(null);+ if (notificationArn != null && !notificationArn.isBlank()) {+ eventPublisher.approvalNeeded(execution, state, notificationArn,+ action.path("configuration").path("CustomData").asText(null),+ action.path("configuration").path("ExternalEntityLink").asText(null),+ now() + TimeUnit.DAYS.toSeconds(7));+ }while ("InProgress".equals(state.getStatus()) && !execution.isStopRequested()) {TimeUnit.MILLISECONDS.sleep(POLL_INTERVAL_MS);}diff --git a/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineEventPublisherTest.java b/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineEventPublisherTest.javanew file mode 100644index 0000000000..d28311dc51--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineEventPublisherTest.java@@ -0,0 +1,104 @@+package io.github.hectorvent.floci.services.codepipeline;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.codepipeline.model.CodePipelineExecution;+import io.github.hectorvent.floci.services.codepipeline.model.CodePipelineExecution.ActionExecution;+import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;+import io.github.hectorvent.floci.services.sns.SnsService;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.ArgumentCaptor;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;++import java.util.List;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.verify;++/**+ * Unit tests for {@link CodePipelineEventPublisher#actionStateChange}'s execution-result+ * shape, pinned at the entry handed to {@code eventBridgeService.putEvents} so a regression+ * in the optional-field guards is caught even though the event delivery itself is best-effort.+ */+@ExtendWith(MockitoExtension.class)+class CodePipelineEventPublisherTest {++ private static final ObjectMapper MAPPER = new ObjectMapper();++ @Mock private EventBridgeService eventBridgeService;+ @Mock private SnsService snsService;++ @Test+ @SuppressWarnings("unchecked")+ void summaryAloneStillProducesAnExecutionResultBlock() throws Exception {+ CodePipelineEventPublisher publisher =+ new CodePipelineEventPublisher(eventBridgeService, snsService, MAPPER);++ CodePipelineExecution execution = new CodePipelineExecution();+ execution.setRegion("us-east-1");+ ActionExecution action = new ActionExecution();+ action.setStageName("Build");+ action.setActionName("Compile");+ action.setOwner("AWS");+ action.setProvider("CodeBuild");+ action.setCategory("Build");+ action.setSummary("Build succeeded.");++ publisher.actionStateChange(execution, action, "SUCCEEDED");++ ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);+ verify(eventBridgeService).putEvents(captor.capture(), any(), any());+ JsonNode detail = MAPPER.readTree((String) captor.getValue().get(0).get("Detail"));+ assertEquals("Build succeeded.",+ detail.path("execution-result").path("external-execution-summary").asText());+ assertFalse(detail.path("execution-result").has("external-execution-id"));+ }++ @Test+ @SuppressWarnings("unchecked")+ void missingErrorCodeIsOmittedRatherThanTheLiteralStringNull() throws Exception {+ CodePipelineEventPublisher publisher =+ new CodePipelineEventPublisher(eventBridgeService, snsService, MAPPER);++ CodePipelineExecution execution = new CodePipelineExecution();+ execution.setRegion("us-east-1");+ ActionExecution action = new ActionExecution();+ action.setStageName("Build");+ action.setActionName("Compile");+ action.setOwner("AWS");+ action.setProvider("CodeBuild");+ action.setCategory("Build");+ action.setErrorDetails(Map.of("message", "boom"));++ publisher.actionStateChange(execution, action, "FAILED");++ ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);+ verify(eventBridgeService).putEvents(captor.capture(), any(), any());+ JsonNode detail = MAPPER.readTree((String) captor.getValue().get(0).get("Detail"));+ assertFalse(detail.path("execution-result").has("error-code"));+ }++ @Test+ @SuppressWarnings("unchecked")+ void startTimeKeepsTheMillisecondsOfTheStoredStartTime() throws Exception {+ // Catches: start-time truncated to whole seconds, up to 999 ms before the stored start.+ CodePipelineEventPublisher publisher =+ new CodePipelineEventPublisher(eventBridgeService, snsService, MAPPER);++ CodePipelineExecution execution = new CodePipelineExecution();+ execution.setRegion("us-east-1");+ execution.setStartTime(1700000000.604);++ publisher.pipelineStateChange(execution, "STARTED");++ ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);+ verify(eventBridgeService).putEvents(captor.capture(), any(), any());+ JsonNode detail = MAPPER.readTree((String) captor.getValue().get(0).get("Detail"));+ assertEquals("2023-11-14T22:13:20.604Z", detail.path("start-time").asText());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineEventsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineEventsIntegrationTest.javanew file mode 100644index 0000000000..5ade762419--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineEventsIntegrationTest.java@@ -0,0 +1,259 @@+package io.github.hectorvent.floci.services.codepipeline;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;+import io.github.hectorvent.floci.services.eventbridge.model.RuleState;+import io.github.hectorvent.floci.services.eventbridge.model.Target;+import io.github.hectorvent.floci.services.sns.SnsService;+import io.github.hectorvent.floci.services.sns.model.Topic;+import io.github.hectorvent.floci.services.sqs.SqsService;+import io.github.hectorvent.floci.services.sqs.model.Message;+import io.github.hectorvent.floci.services.sqs.model.Queue;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.specification.RequestSpecification;+import jakarta.inject.Inject;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.Map;+import java.util.concurrent.TimeUnit;++import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.junit.jupiter.api.Assertions.fail;++/**+ * End-to-end proof that pipeline executions emit {@code aws.codepipeline} events onto the+ * default EventBridge bus: a rule with an SQS target receives the pipeline state-change+ * event for an execution started over the wire.+ */+@QuarkusTest+class CodePipelineEventsIntegrationTest {++ private static final String REGION = "us-east-1";+ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";+ private static final String ISO_TIMESTAMP = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,9})?Z";+ private static final String MINUTE_TIMESTAMP = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}Z";+ private static final String TARGET_PREFIX = "CodePipeline_20150709.";++ @Inject+ SqsService sqsService;+ @Inject+ SnsService snsService;+ @Inject+ EventBridgeService eventBridgeService;++ private final ObjectMapper mapper = new ObjectMapper();++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ private static RequestSpecification call(String action) {+ return given().header("X-Amz-Target", TARGET_PREFIX + action).contentType(CONTENT_TYPE);+ }++ @Test+ void pipelineStateChangeEventReachesSqsThroughEventBridgeRule() throws Exception {+ Queue queue = sqsService.createQueue("cp-events-it", Map.of(), REGION);+ eventBridgeService.putRule("cp-events-it-rule", "default",+ "{\"source\":[\"aws.codepipeline\"]}", null, RuleState.ENABLED,+ null, null, Map.of(), REGION);+ eventBridgeService.putTargets("cp-events-it-rule", "default",+ List.of(new Target("cp-events-it-target",+ "arn:aws:sqs:us-east-1:000000000000:cp-events-it", null, null)),+ REGION);++ call("CreatePipeline")+ .body("""+ {+ "pipeline": {+ "name": "events-it",+ "roleArn": "arn:aws:iam::000000000000:role/cp",+ "artifactStore": {"type": "S3", "location": "cp-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+ }+ ]+ }+ ]+ }+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(200);++ String executionId = call("StartPipelineExecution")+ .body("""+ { "name": "events-it" }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().path("pipelineExecutionId");++ JsonNode started = awaitEvent("CodePipeline Pipeline Execution State Change", "STARTED");+ assertEquals("events-it", started.path("detail").path("pipeline").asText());+ assertEquals(executionId, started.path("detail").path("execution-id").asText());+ assertEquals("aws.codepipeline", started.path("source").asText());+ // Catches: start-time emitted as epoch seconds instead of an ISO-8601 timestamp.+ assertTrue(started.path("detail").path("start-time").asText().matches(ISO_TIMESTAMP));+ assertTrue(started.path("resources").get(0).asText()+ .endsWith(":codepipeline:us-east-1:000000000000:events-it"));++ call("StopPipelineExecution")+ .body("""+ { "pipelineName": "events-it", "pipelineExecutionId": "%s", "abandon": true }+ """.formatted(executionId))+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }++ @Test+ void approvalNotificationOnTheTopicMatchesTheUserGuideShape() throws Exception {+ // Catches: approval message with non-ISO expires, no externalEntityLink, missing or wrong consoleLink and approvalReviewLink,+ // or a subject over 100 characters that SNS rejects and silently drops the notification.+ Topic topic = snsService.createTopic("cp-approval-it", Map.of(), Map.of(), REGION);+ sqsService.createQueue("cp-approval-it-q", Map.of(), REGION);+ snsService.subscribe(topic.getTopicArn(), "sqs",+ "arn:aws:sqs:us-east-1:000000000000:cp-approval-it-q", REGION, Map.of());+ String pipelineName = "approval-it-" + "p".repeat(70);++ call("CreatePipeline")+ .body("""+ {+ "pipeline": {+ "name": "%s",+ "roleArn": "arn:aws:iam::000000000000:role/cp",+ "artifactStore": {"type": "S3", "location": "cp-artifacts"},+ "stages": [+ {+ "name": "Gate",+ "actions": [+ {+ "name": "HumanGateWithALongActionName",+ "actionTypeId": {"category": "Approval", "owner": "AWS",+ "provider": "Manual", "version": "1"},+ "runOrder": 1,+ "configuration": {+ "NotificationArn": "%s",+ "CustomData": "ship it",+ "ExternalEntityLink": "http://example.com/review"+ }+ }+ ]+ },+ {+ "name": "Release",+ "actions": [+ {+ "name": "ReleaseGate",+ "actionTypeId": {"category": "Approval", "owner": "AWS",+ "provider": "Manual", "version": "1"},+ "runOrder": 1+ }+ ]+ }+ ]+ }+ }+ """.formatted(pipelineName, topic.getTopicArn()))+ .when()+ .post("/")+ .then()+ .statusCode(200);++ String executionId = call("StartPipelineExecution")+ .body("{ \"name\": \"" + pipelineName + "\" }")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().path("pipelineExecutionId");++ String queueUrl = sqsService.getQueueUrl("cp-approval-it-q", REGION);+ JsonNode envelope = null;+ long deadline = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(10);+ while (envelope == null && System.currentTimeMillis() < deadline) {+ for (Message message : sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION)) {+ envelope = mapper.readTree(message.getBody());+ }+ TimeUnit.MILLISECONDS.sleep(100);+ }+ assertNotNull(envelope, "No approval notification reached the topic");+ String subject = envelope.path("Subject").asText();+ assertEquals(100, subject.length());+ assertTrue(subject.startsWith("APPROVAL NEEDED: AWS CodePipeline approval-it-"));++ JsonNode message = mapper.readTree(envelope.path("Message").asText());+ assertEquals("us-east-1", message.path("region").asText());+ assertEquals("https://console.aws.amazon.com/codepipeline/home?region=us-east-1#/view/"+ + pipelineName, message.path("consoleLink").asText());+ JsonNode approval = message.path("approval");+ assertEquals(pipelineName, approval.path("pipelineName").asText());+ assertEquals("Gate", approval.path("stageName").asText());+ assertEquals("HumanGateWithALongActionName", approval.path("actionName").asText());+ assertEquals("ship it", approval.path("customData").asText());+ assertEquals("http://example.com/review", approval.path("externalEntityLink").asText());+ assertEquals("https://console.aws.amazon.com/codepipeline/home?region=us-east-1#/view/"+ + pipelineName + "/Gate/HumanGateWithALongActionName/approve/"+ + approval.path("token").asText(), approval.path("approvalReviewLink").asText());+ assertFalse(approval.path("token").asText().isEmpty());+ assertTrue(approval.path("expires").asText().matches(MINUTE_TIMESTAMP),+ "expires must be an ISO-8601 timestamp to the minute: " + approval.path("expires"));++ call("StopPipelineExecution")+ .body("{ \"pipelineName\": \"" + pipelineName + "\", \"pipelineExecutionId\": \""+ + executionId + "\", \"abandon\": true }")+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }++ private JsonNode awaitEvent(String detailType, String state) throws Exception {+ long deadline = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(10);+ String queueUrl = sqsService.getQueueUrl("cp-events-it", REGION);+ while (System.currentTimeMillis() < deadline) {+ for (Message message : sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION)) {+ JsonNode event = mapper.readTree(message.getBody());+ if (detailType.equals(event.path("detail-type").asText())+ && state.equals(event.path("detail").path("state").asText())) {+ return event;+ }+ }+ TimeUnit.MILLISECONDS.sleep(100);+ }+ return fail("No " + detailType + " event with state " + state + " arrived on the queue");+ }+}