mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cloudformation): provision AWS::Events::Connection (#7718)
* feat(cloudformation): provision AWS::Events::Connection * feat(cloudformation): roll back an AWS::Events::Connection updated in place * feat(cloudformation): address review of the Connection provisioner * fix(cloudformation): match AWS when an AWS::Events::Connection drops a description * fix(cloudformation): clear a stale Connection rollback snapshot before any check * test(cloudformation): add AWS::Events::Connection's change-exempt row Co-authored-by: Priamo <pgermosen@gmail.com>
This commit is contained in:
1 parent
ba3a019a19
commit
bd58181a41
14 files changed
+1105
-20
No files matched your search
+288
@@ -0,0 +1,288 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.XmlParser;
|
||||
import io.floci.aws.testing.CfnRequests;
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.json.JsonPath;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
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.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Provisions an {@code AWS::Events::Connection} through a CloudFormation stack and reads it back
|
||||
* through the EventBridge API. {@code Ref} is the connection name; {@code Fn::GetAtt} gives
|
||||
* {@code Arn}, {@code ArnForPolicy} and {@code SecretArn}. An {@code AWS::Events::ApiDestination}
|
||||
* can take the connection's ARN, a description change updates the connection in place, a dropped
|
||||
* description stays and an empty one clears it, dropped Kms and connectivity settings are cleared, dropping a property the service cannot clear is refused, a failed
|
||||
* update rolls the connection back, and the stack delete removes the connection.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationEventsConnectionIntegrationTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String EVENTS_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261001/us-east-1/events/aws4_request";
|
||||
private final List<String> stacks = new ArrayList<>();
|
||||
|
||||
@BeforeAll
|
||||
static void configureContentTypes() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUp() {
|
||||
for (String stack : List.copyOf(stacks)) {
|
||||
deleteStack(stack);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createReadsBackThroughDescribeConnectionAndExposesTheAttributes() throws Exception {
|
||||
String name = "orders-" + suffix();
|
||||
String body = awaitComplete(createStack(template(connection(name, "orders connection"), false)),
|
||||
"CREATE_COMPLETE");
|
||||
|
||||
assertEquals(name, output(body, "ConnectionRef"), "Ref is the connection name");
|
||||
JsonPath connection = describeConnection(name).then().statusCode(200).extract().jsonPath();
|
||||
assertEquals("API_KEY", connection.getString("AuthorizationType"));
|
||||
assertEquals("AUTHORIZED", connection.getString("ConnectionState"));
|
||||
assertEquals("orders connection", connection.getString("Description"));
|
||||
assertEquals("Authorization", connection.getString("AuthParameters.ApiKeyAuthParameters.ApiKeyName"));
|
||||
String arn = connection.getString("ConnectionArn");
|
||||
assertEquals(arn, output(body, "ConnectionArn"), "GetAtt Arn is the connection ARN");
|
||||
assertEquals(arn.substring(0, arn.lastIndexOf('/')), output(body, "ConnectionArnForPolicy"),
|
||||
"GetAtt ArnForPolicy is the ARN without the trailing id");
|
||||
assertEquals(connection.getString("SecretArn"), output(body, "ConnectionSecretArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anApiDestinationTakesTheConnectionArn() throws Exception {
|
||||
String name = "orders-" + suffix();
|
||||
String destination = "orders-dest-" + suffix();
|
||||
String body = awaitComplete(createStack(template(connection(name, null), true, destination)),
|
||||
"CREATE_COMPLETE");
|
||||
|
||||
String arn = describeConnection(name).then().statusCode(200).extract().jsonPath()
|
||||
.getString("ConnectionArn");
|
||||
assertEquals(arn, output(body, "ConnectionArn"));
|
||||
assertEquals(arn, events("DescribeApiDestination", Map.of("Name", destination)).then().statusCode(200)
|
||||
.extract().jsonPath().getString("ConnectionArn"), "the destination points at the real connection");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDescriptionChangeUpdatesTheConnectionInPlace() throws Exception {
|
||||
String name = "orders-" + suffix();
|
||||
String stack = createStack(template(connection(name, "first"), false));
|
||||
String arn = output(awaitComplete(stack, "CREATE_COMPLETE"), "ConnectionArn");
|
||||
|
||||
updateStack(stack, template(connection(name, "second"), false));
|
||||
String body = awaitComplete(stack, "UPDATE_COMPLETE");
|
||||
|
||||
assertEquals(arn, output(body, "ConnectionArn"), "an in-place update keeps the connection");
|
||||
assertEquals("second", describeConnection(name).then().statusCode(200).extract().jsonPath()
|
||||
.getString("Description"));
|
||||
}
|
||||
|
||||
/** A real AWS account leaves a dropped description as it is and clears an empty one. */
|
||||
@Test
|
||||
void aDroppedDescriptionStaysAndAnEmptyOneClears() throws Exception {
|
||||
String name = "orders-" + suffix();
|
||||
String stack = createStack(template(connection(name, "first"), false));
|
||||
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE");
|
||||
|
||||
updateStack(stack, template(connection(name, null), false));
|
||||
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE");
|
||||
assertEquals("first", describeConnection(name).then().statusCode(200).extract().jsonPath()
|
||||
.getString("Description"));
|
||||
|
||||
updateStack(stack, template(connection(name, ""), false));
|
||||
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE");
|
||||
assertNull(describeConnection(name).then().statusCode(200).extract().jsonPath().getString("Description"));
|
||||
}
|
||||
|
||||
/** A real AWS account clears both when a template drops them. */
|
||||
@Test
|
||||
void aDroppedKmsKeyAndConnectivityParametersAreCleared() throws Exception {
|
||||
String name = "orders-" + suffix();
|
||||
Map<String, Object> full = connection(name, null);
|
||||
full.put("KmsKeyIdentifier", "alias/orders");
|
||||
full.put("InvocationConnectivityParameters", Map.of("ResourceParameters", Map.of(
|
||||
"ResourceConfigurationArn",
|
||||
"arn:aws:vpc-lattice:us-east-1:000000000000:resourceconfiguration/rcfg-0123456789abcdef0")));
|
||||
String stack = createStack(template(full, false));
|
||||
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE");
|
||||
JsonPath created = describeConnection(name).then().statusCode(200).extract().jsonPath();
|
||||
assertEquals("alias/orders", created.getString("KmsKeyIdentifier"));
|
||||
assertFalse(created.getMap("InvocationConnectivityParameters").isEmpty());
|
||||
|
||||
updateStack(stack, template(connection(name, null), false));
|
||||
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE");
|
||||
|
||||
JsonPath updated = describeConnection(name).then().statusCode(200).extract().jsonPath();
|
||||
assertNull(updated.getString("KmsKeyIdentifier"));
|
||||
assertNull(updated.get("InvocationConnectivityParameters"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void droppingAPropertyTheServiceCannotClearIsRefused() throws Exception {
|
||||
String name = "orders-" + suffix();
|
||||
String stack = createStack(template(connection(name, "first"), false));
|
||||
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE");
|
||||
|
||||
Map<String, Object> dropped = connection(name, "first");
|
||||
dropped.remove("AuthorizationType");
|
||||
updateStack(stack, template(dropped, false));
|
||||
CfnStackWaits.awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
assertTrue(CfnStackWaits.failedResourceReason(stack).contains("Removing AuthorizationType"));
|
||||
assertEquals("API_KEY", describeConnection(name).then().statusCode(200).extract().jsonPath()
|
||||
.getString("AuthorizationType"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedUpdateRollsTheConnectionBack() throws Exception {
|
||||
String name = "orders-" + suffix();
|
||||
String stack = createStack(template(connection(name, "first"), false));
|
||||
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE");
|
||||
|
||||
// The connection is updated first; the destination after it points at a connection that
|
||||
// does not exist, so the update fails and the connection has to go back to "first".
|
||||
updateStack(stack, withBrokenDestination(template(connection(name, "second"), false)));
|
||||
CfnStackWaits.awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
assertEquals("first", describeConnection(name).then().statusCode(200).extract().jsonPath()
|
||||
.getString("Description"));
|
||||
assertEquals("AUTHORIZED", describeConnection(name).then().statusCode(200).extract().jsonPath()
|
||||
.getString("ConnectionState"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStackRemovesTheConnection() throws Exception {
|
||||
String name = "orders-" + suffix();
|
||||
String stack = createStack(template(connection(name, null), false));
|
||||
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE");
|
||||
describeConnection(name).then().statusCode(200);
|
||||
|
||||
deleteStack(stack);
|
||||
|
||||
assertEquals("ResourceNotFoundException", describeConnection(name).then().statusCode(400)
|
||||
.extract().jsonPath().getString("__type"));
|
||||
}
|
||||
|
||||
/** The template plus an API destination whose connection ARN does not exist, which fails the update. */
|
||||
private static String withBrokenDestination(String template) throws Exception {
|
||||
ObjectNode root = (ObjectNode) MAPPER.readTree(template);
|
||||
((ObjectNode) root.get("Resources")).set("Broken", MAPPER.valueToTree(Map.of(
|
||||
"Type", "AWS::Events::ApiDestination",
|
||||
"Properties", Map.of(
|
||||
"Name", "broken-" + suffix(),
|
||||
"ConnectionArn", "arn:aws:events:us-east-1:000000000000:connection/missing/00000000",
|
||||
"HttpMethod", "POST",
|
||||
"InvocationEndpoint", "https://example.com/events"))));
|
||||
return root.toString();
|
||||
}
|
||||
|
||||
private static String suffix() {
|
||||
return Long.toString(System.nanoTime(), 36);
|
||||
}
|
||||
|
||||
private String createStack(String template) {
|
||||
String stack = "cfn-connection-" + suffix();
|
||||
CfnRequests.cfn("CreateStack", stack).formParam("TemplateBody", template)
|
||||
.when().post("/").then().statusCode(200);
|
||||
stacks.add(stack);
|
||||
return stack;
|
||||
}
|
||||
|
||||
private static void updateStack(String stack, String template) {
|
||||
CfnRequests.cfn("UpdateStack", stack).formParam("TemplateBody", template)
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private void deleteStack(String stack) {
|
||||
CfnStackWaits.deleteStack(stack);
|
||||
stacks.remove(stack);
|
||||
}
|
||||
|
||||
/** Waits for {@code status} and returns the DescribeStacks body, which carries the outputs. */
|
||||
private static String awaitComplete(String stack, String status) {
|
||||
CfnStackWaits.awaitStatus(stack, status);
|
||||
return CfnRequests.cfn("DescribeStacks", stack).when().post("/").then().statusCode(200)
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
private static String output(String body, String key) {
|
||||
String value = XmlParser.extractPairs(body, "Outputs", "OutputKey", "OutputValue").get(key);
|
||||
assertFalse(value == null || value.isBlank(), body);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static Response events(String action, Map<String, ?> body) throws Exception {
|
||||
return given().contentType("application/x-amz-json-1.1").header("Authorization", EVENTS_AUTH)
|
||||
.header("X-Amz-Target", "AWSEvents." + action).body(MAPPER.writeValueAsString(body)).post("/");
|
||||
}
|
||||
|
||||
private static Response describeConnection(String name) throws Exception {
|
||||
return events("DescribeConnection", Map.of("Name", name));
|
||||
}
|
||||
|
||||
/** An API key connection whose key value is built with {@code Fn::Sub}, as event-streaming templates do. */
|
||||
private static Map<String, Object> connection(String name, String description) {
|
||||
Map<String, Object> apiKey = new LinkedHashMap<>();
|
||||
apiKey.put("ApiKeyName", "Authorization");
|
||||
apiKey.put("ApiKeyValue", Map.of("Fn::Sub", "Bearer ${Token}"));
|
||||
Map<String, Object> properties = new LinkedHashMap<>();
|
||||
properties.put("Name", name);
|
||||
properties.put("AuthorizationType", "API_KEY");
|
||||
properties.put("AuthParameters", Map.of("ApiKeyAuthParameters", apiKey));
|
||||
if (description != null) {
|
||||
properties.put("Description", description);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
|
||||
private static String template(Map<String, Object> connectionProperties, boolean withDestination)
|
||||
throws Exception {
|
||||
return template(connectionProperties, withDestination, null);
|
||||
}
|
||||
|
||||
private static String template(Map<String, Object> connectionProperties, boolean withDestination,
|
||||
String destinationName) throws Exception {
|
||||
Map<String, Object> resources = new LinkedHashMap<>();
|
||||
resources.put("Connection", Map.of("Type", "AWS::Events::Connection", "Properties", connectionProperties));
|
||||
if (withDestination) {
|
||||
resources.put("Destination", Map.of("Type", "AWS::Events::ApiDestination", "Properties", Map.of(
|
||||
"Name", destinationName,
|
||||
"ConnectionArn", Map.of("Fn::GetAtt", List.of("Connection", "Arn")),
|
||||
"HttpMethod", "POST",
|
||||
"InvocationEndpoint", "https://example.com/events")));
|
||||
}
|
||||
Map<String, Object> outputs = new LinkedHashMap<>();
|
||||
outputs.put("ConnectionRef", Map.of("Value", Map.of("Ref", "Connection")));
|
||||
outputs.put("ConnectionArn", Map.of("Value", Map.of("Fn::GetAtt", List.of("Connection", "Arn"))));
|
||||
outputs.put("ConnectionArnForPolicy",
|
||||
Map.of("Value", Map.of("Fn::GetAtt", List.of("Connection", "ArnForPolicy"))));
|
||||
outputs.put("ConnectionSecretArn",
|
||||
Map.of("Value", Map.of("Fn::GetAtt", List.of("Connection", "SecretArn"))));
|
||||
return MAPPER.writeValueAsString(Map.of(
|
||||
"Parameters", Map.of("Token", Map.of("Type", "String", "Default", "tok-123")),
|
||||
"Resources", resources,
|
||||
"Outputs", outputs));
|
||||
}
|
||||
}
|
||||
+385
@@ -0,0 +1,385 @@
|
||||
package io.floci.aws.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.floci.aws.services.cloudformation.model.StackResource;
|
||||
import io.floci.aws.services.eventbridge.EventBridgeService;
|
||||
import io.floci.aws.services.eventbridge.model.Connection;
|
||||
import io.floci.aws.services.eventbridge.model.ConnectionState;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
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.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** {@code AWS::Events::Connection} in the Events CFN provisioner, with only {@link EventBridgeService} mocked. */
|
||||
class EventsConnectionCfnProvisionerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String NAME = "orders-connection";
|
||||
private static final String ARN = "arn:aws:events:us-east-1:000000000000:connection/" + NAME + "/4f1c2d3e";
|
||||
private static final String SECRET_ARN =
|
||||
"arn:aws:secretsmanager:us-east-1:000000000000:secret:events!connection/" + NAME + "/4f1c2d3e";
|
||||
|
||||
private final EventBridgeService events = mock(EventBridgeService.class);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final EventsCfnProvisioner provisioner = new EventsCfnProvisioner(events);
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId, JsonNode priorProperties) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
when(engine.omitNoValue(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId,
|
||||
event -> { }, priorProperties);
|
||||
}
|
||||
|
||||
private StackResource resource(String logicalId) {
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Events::Connection");
|
||||
r.setLogicalId(logicalId);
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
private ObjectNode apiKeyAuth(String value) {
|
||||
ObjectNode apiKey = mapper.createObjectNode().put("ApiKeyName", "Authorization").put("ApiKeyValue", value);
|
||||
return mapper.createObjectNode().set("ApiKeyAuthParameters", apiKey);
|
||||
}
|
||||
|
||||
private ObjectNode props(String description, String apiKeyValue) {
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("Name", NAME);
|
||||
props.put("AuthorizationType", "API_KEY");
|
||||
props.set("AuthParameters", apiKeyAuth(apiKeyValue));
|
||||
if (description != null) {
|
||||
props.put("Description", description);
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
private Connection stored() {
|
||||
Connection connection = new Connection();
|
||||
connection.setName(NAME);
|
||||
connection.setConnectionArn(ARN);
|
||||
connection.setSecretArn(SECRET_ARN);
|
||||
return connection;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createMapsThePropertiesAndExposesTheAttributes() throws Exception {
|
||||
when(events.createConnection(eq(NAME), eq("Events to orders"), eq("API_KEY"), anyString(),
|
||||
isNull(), isNull(), eq(REGION))).thenReturn(stored());
|
||||
|
||||
StackResource r = resource("ApiDestinationConnection");
|
||||
provisioner.provision(r, props("Events to orders", "Bearer tok"), ctx(null, null));
|
||||
|
||||
ArgumentCaptor<String> auth = ArgumentCaptor.forClass(String.class);
|
||||
verify(events).createConnection(eq(NAME), eq("Events to orders"), eq("API_KEY"), auth.capture(),
|
||||
isNull(), isNull(), eq(REGION));
|
||||
assertEquals(apiKeyAuth("Bearer tok"), mapper.readTree(auth.getValue()),
|
||||
"AuthParameters reach the service as the JSON object the API takes");
|
||||
assertEquals(NAME, r.getPhysicalId(), "Ref is the connection name");
|
||||
assertEquals(ARN, r.getAttributes().get("Arn"));
|
||||
assertEquals("arn:aws:events:us-east-1:000000000000:connection/" + NAME,
|
||||
r.getAttributes().get("ArnForPolicy"), "the policy ARN drops the trailing id");
|
||||
assertEquals(SECRET_ARN, r.getAttributes().get("SecretArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnnamedConnectionGetsAGeneratedNameWithinTheLimit() {
|
||||
when(events.createConnection(anyString(), any(), any(), any(), any(), any(), anyString()))
|
||||
.thenReturn(stored());
|
||||
ObjectNode props = props(null, "tok");
|
||||
props.remove("Name");
|
||||
|
||||
StackResource r = resource("ApiDestinationConnection");
|
||||
provisioner.provision(r, props, ctx(null, null));
|
||||
|
||||
assertTrue(r.getPhysicalId().startsWith("my-stack-ApiDestinationConnection-"), r.getPhysicalId());
|
||||
assertTrue(r.getPhysicalId().length() <= 64, r.getPhysicalId());
|
||||
assertTrue(r.getPhysicalId().matches("[.\\-_A-Za-z0-9]+"), r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateChangesTheConnectionInPlace() {
|
||||
when(events.describeConnection(NAME, REGION)).thenReturn(stored());
|
||||
when(events.updateConnection(eq(NAME), eq("new description"), eq("API_KEY"), anyString(),
|
||||
isNull(), isNull(), eq(Set.of()), eq(REGION))).thenReturn(stored());
|
||||
|
||||
StackResource r = resource("ApiDestinationConnection");
|
||||
ObjectNode prior = props("old description", "tok");
|
||||
provisioner.provision(r, props("new description", "rotated"), ctx(NAME, prior));
|
||||
|
||||
verify(events).updateConnection(eq(NAME), eq("new description"), eq("API_KEY"), anyString(),
|
||||
isNull(), isNull(), eq(Set.of()), eq(REGION));
|
||||
verify(events, never()).createConnection(any(), any(), any(), any(), any(), any(), any());
|
||||
assertEquals(NAME, r.getPhysicalId());
|
||||
assertEquals(ARN, r.getAttributes().get("Arn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDifferentNameIsAReplacementAndRefused() {
|
||||
StackResource r = resource("ApiDestinationConnection");
|
||||
ObjectNode renamed = props(null, "tok");
|
||||
renamed.put("Name", "another-name");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, renamed, ctx(NAME, props(null, "tok"))));
|
||||
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
assertTrue(e.getMessage().contains("requires resource replacement"), e.getMessage());
|
||||
verify(events, never()).createConnection(any(), any(), any(), any(), any(), any(), any());
|
||||
verify(events, never()).updateConnection(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDroppedDescriptionStaysAsItIsAsOnAws() {
|
||||
when(events.describeConnection(NAME, REGION)).thenReturn(stored());
|
||||
when(events.updateConnection(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(stored());
|
||||
|
||||
provisioner.provision(resource("ApiDestinationConnection"), props(null, "tok"),
|
||||
ctx(NAME, props("a description", "tok")));
|
||||
|
||||
verify(events).updateConnection(eq(NAME), isNull(), eq("API_KEY"), anyString(),
|
||||
isNull(), isNull(), eq(Set.of()), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyDescriptionIsPassedOnToClearIt() {
|
||||
when(events.describeConnection(NAME, REGION)).thenReturn(stored());
|
||||
when(events.updateConnection(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(stored());
|
||||
|
||||
provisioner.provision(resource("ApiDestinationConnection"), props("", "tok"),
|
||||
ctx(NAME, props("a description", "tok")));
|
||||
|
||||
verify(events).updateConnection(eq(NAME), eq(""), eq("API_KEY"), anyString(),
|
||||
isNull(), isNull(), eq(Set.of()), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDroppedKmsKeyAndConnectivityParametersAreCleared() {
|
||||
when(events.describeConnection(NAME, REGION)).thenReturn(stored());
|
||||
when(events.updateConnection(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(stored());
|
||||
ObjectNode prior = props(null, "tok");
|
||||
prior.put("KmsKeyIdentifier", "alias/orders");
|
||||
prior.set("InvocationConnectivityParameters", mapper.createObjectNode().set("ResourceParameters",
|
||||
mapper.createObjectNode().put("ResourceConfigurationArn", "arn:aws:vpc-lattice:us-east-1:000000000000:resourceconfiguration/rcfg-1")));
|
||||
|
||||
provisioner.provision(resource("ApiDestinationConnection"), props(null, "tok"), ctx(NAME, prior));
|
||||
|
||||
verify(events).updateConnection(eq(NAME), isNull(), eq("API_KEY"), anyString(), isNull(), isNull(),
|
||||
eq(Set.of("KmsKeyIdentifier", "InvocationConnectivityParameters")), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDroppedAuthorizationTypeIsRefusedBecauseEventBridgeWouldKeepIt() {
|
||||
StackResource r = resource("ApiDestinationConnection");
|
||||
ObjectNode dropped = props(null, "tok");
|
||||
dropped.remove("AuthorizationType");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, dropped, ctx(NAME, props(null, "tok"))));
|
||||
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
assertTrue(e.getMessage().contains("Removing AuthorizationType"), e.getMessage());
|
||||
verify(events, never()).updateConnection(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anApiKeyWithoutItsValueFailsTheResource() {
|
||||
StackResource r = resource("ApiDestinationConnection");
|
||||
ObjectNode props = props(null, "tok");
|
||||
((ObjectNode) props.get("AuthParameters").get("ApiKeyAuthParameters")).remove("ApiKeyValue");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx(null, null)));
|
||||
|
||||
assertTrue(e.getMessage().contains("ApiKeyValue"), e.getMessage());
|
||||
verify(events, never()).createConnection(any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConnectionAnOlderFlociStubbedIsCreatedByTheNextUpdate() {
|
||||
when(events.createConnection(any(), any(), any(), any(), any(), any(), any())).thenReturn(stored());
|
||||
StackResource r = resource("ApiDestinationConnection");
|
||||
r.getAttributes().put("Arn", "arn:aws:stub:::ApiDestinationConnection");
|
||||
String stubId = "ApiDestinationConnection-1a2b3c4d";
|
||||
|
||||
provisioner.provision(r, props("Events to orders", "tok"), ctx(stubId, props("older", "tok")));
|
||||
|
||||
verify(events).createConnection(eq(NAME), eq("Events to orders"), eq("API_KEY"), anyString(),
|
||||
isNull(), isNull(), eq(REGION));
|
||||
verify(events, never()).updateConnection(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
assertEquals(NAME, r.getPhysicalId());
|
||||
}
|
||||
|
||||
private Connection priorConnection() {
|
||||
Connection connection = stored();
|
||||
connection.setDescription("old description");
|
||||
connection.setAuthorizationType("API_KEY");
|
||||
connection.setAuthParameters(apiKeyAuth("old-key").toString());
|
||||
connection.setKmsKeyIdentifier("alias/old");
|
||||
connection.setConnectionState(ConnectionState.AUTHORIZED);
|
||||
connection.setLastModifiedTime(Instant.parse("2026-11-01T10:00:00Z"));
|
||||
connection.setLastAuthorizedTime(Instant.parse("2026-11-01T10:00:05Z"));
|
||||
return connection;
|
||||
}
|
||||
|
||||
private StackResource updatedConnection() {
|
||||
when(events.describeConnection(NAME, REGION)).thenReturn(priorConnection());
|
||||
when(events.updateConnection(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(stored());
|
||||
StackResource r = resource("ApiDestinationConnection");
|
||||
provisioner.provision(r, props("new description", "rotated"), ctx(NAME, props("old description", "old-key")));
|
||||
return r;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRollbackPutsBackTheConnectionTheUpdateChanged() {
|
||||
StackResource r = updatedConnection();
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
ArgumentCaptor<Connection> restored = ArgumentCaptor.forClass(Connection.class);
|
||||
verify(events).restoreConnection(restored.capture(), eq(REGION));
|
||||
Connection previous = restored.getValue();
|
||||
assertEquals(NAME, previous.getName());
|
||||
assertEquals("old description", previous.getDescription());
|
||||
assertEquals("API_KEY", previous.getAuthorizationType());
|
||||
assertEquals(apiKeyAuth("old-key").toString(), previous.getAuthParameters());
|
||||
assertEquals("alias/old", previous.getKmsKeyIdentifier());
|
||||
assertEquals(ConnectionState.AUTHORIZED, previous.getConnectionState());
|
||||
assertEquals(Instant.parse("2026-11-01T10:00:00Z"), previous.getLastModifiedTime());
|
||||
assertEquals(Instant.parse("2026-11-01T10:00:05Z"), previous.getLastAuthorizedTime());
|
||||
assertFalse(provisioner.rollbackUpdate(r), "the snapshot is spent once restored");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRollbackKeepsAFailedRestoreForTheNextAttempt() {
|
||||
StackResource r = updatedConnection();
|
||||
doThrow(new AwsException("InternalException", "boom", 500)).when(events).restoreConnection(any(), any());
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
|
||||
|
||||
assertNotNull(r.getAttributes().get(CfnRollback.CONNECTION_UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSnapshotLeftByAnEarlierUpdateIsReplacedByTheOneInFlight() {
|
||||
StackResource r = updatedConnection();
|
||||
Connection later = priorConnection();
|
||||
later.setDescription("description after the first update");
|
||||
when(events.describeConnection(NAME, REGION)).thenReturn(later);
|
||||
|
||||
provisioner.provision(r, props("third", "rotated"), ctx(NAME, props("new description", "rotated")));
|
||||
provisioner.rollbackUpdate(r);
|
||||
|
||||
ArgumentCaptor<Connection> restored = ArgumentCaptor.forClass(Connection.class);
|
||||
verify(events).restoreConnection(restored.capture(), eq(REGION));
|
||||
assertEquals("description after the first update", restored.getValue().getDescription());
|
||||
}
|
||||
|
||||
/**
|
||||
* An update committed and left its snapshot; the next update is refused before it changes anything,
|
||||
* so its rollback has nothing to restore and must not undo the committed update.
|
||||
*/
|
||||
private void assertARefusedUpdateLeavesNothingToRestore(ObjectNode refused) {
|
||||
StackResource r = updatedConnection();
|
||||
assertNotNull(r.getAttributes().get(CfnRollback.CONNECTION_UPDATE_SNAPSHOT_ATTR));
|
||||
|
||||
assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, refused, ctx(NAME, props("new description", "rotated"))));
|
||||
|
||||
assertNull(r.getAttributes().get(CfnRollback.CONNECTION_UPDATE_SNAPSHOT_ATTR));
|
||||
assertFalse(provisioner.rollbackUpdate(r));
|
||||
verify(events, never()).restoreConnection(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDroppedPropertyRefusedAfterACommittedUpdateLeavesNothingToRestore() {
|
||||
ObjectNode refused = props("new description", "rotated");
|
||||
refused.remove("AuthParameters");
|
||||
|
||||
assertARefusedUpdateLeavesNothingToRestore(refused);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMissingApiKeyValueRefusedAfterACommittedUpdateLeavesNothingToRestore() {
|
||||
ObjectNode refused = props("new description", "rotated");
|
||||
((ObjectNode) refused.get("AuthParameters").get("ApiKeyAuthParameters")).remove("ApiKeyValue");
|
||||
|
||||
assertARefusedUpdateLeavesNothingToRestore(refused);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRenameRefusedAfterACommittedUpdateLeavesNothingToRestore() {
|
||||
ObjectNode refused = props("new description", "rotated");
|
||||
refused.put("Name", "another-connection");
|
||||
|
||||
assertARefusedUpdateLeavesNothingToRestore(refused);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConnectionCreateTakesNoSnapshotToRollBack() {
|
||||
when(events.createConnection(any(), any(), any(), any(), any(), any(), any())).thenReturn(stored());
|
||||
StackResource r = resource("ApiDestinationConnection");
|
||||
|
||||
provisioner.provision(r, props("Events to orders", "tok"), ctx(null, null));
|
||||
|
||||
assertFalse(provisioner.rollbackUpdate(r));
|
||||
verify(events, never()).restoreConnection(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRemovesTheConnection() {
|
||||
provisioner.delete("AWS::Events::Connection", NAME, REGION);
|
||||
|
||||
verify(events).deleteConnection(NAME, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteToleratesAConnectionThatIsAlreadyGone() {
|
||||
doThrow(new AwsException("ResourceNotFoundException", "Connection " + NAME + " does not exist.", 400))
|
||||
.when(events).deleteConnection(NAME, REGION);
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete("AWS::Events::Connection", NAME, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteLetsARealFailurePropagate() {
|
||||
doThrow(new AwsException("InternalException", "boom", 500)).when(events).deleteConnection(NAME, REGION);
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.delete("AWS::Events::Connection", NAME, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteWithoutAPhysicalIdDoesNothing() {
|
||||
provisioner.delete("AWS::Events::Connection", null, REGION);
|
||||
provisioner.delete("AWS::Events::Connection", "", REGION);
|
||||
|
||||
verify(events, never()).deleteConnection(any(), any());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user