feat(codepipeline): emit EventBridge state-change events and SNS approval notifications (#4616)

* feat(codepipeline): emit EventBridge state-change events and SNS approval notifications

Publishes pipeline, stage, and action execution state changes to the default bus and notifies NotificationArn topics for manual approvals.

* fix(codepipeline): match the approval message and event timestamps to the user guide

Mint the pipeline ARN with AwsArnUtils.Arn.of, publish the approval notification as the pipeline's account, emit expires and start-time as ISO-8601, add externalEntityLink, drop the dead console links, truncate the SNS subject to 100 characters, and use warnv.

* fix(codepipeline): restore the approval console links and keep event timestamp precision

consoleLink and approvalReviewLink point at the AWS console URLs from the user guide, expires is to the minute, and start-time keeps its milliseconds. Terminal event dispatch uses switch expressions.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-10-02 11:53:44 -04:00
1 parent 86c06247e3
commit a833551d03
5 files changed
+617 -5

No files matched your search

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