From bd58181a415c4f9872a40ff7498b762fb685d5ff Mon Sep 17 00:00:00 2001 From: Paulo Costa Date: Sat, 21 Nov 2026 16:55:42 -0300 Subject: [PATCH] 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 --- docs/services/cloudformation.md | 2 +- .../provisioners/CfnRollback.java | 9 + .../provisioners/EventsCfnProvisioner.java | 147 ++++++- .../eventbridge/EventBridgeService.java | 46 ++- .../resources/aws/cfn-property-types.json | 232 ++++++++++- .../create-only-properties.json | 3 + ...mationEventsConnectionIntegrationTest.java | 288 +++++++++++++ .../EventsConnectionCfnProvisionerTest.java | 385 ++++++++++++++++++ .../cloudformation/change-exempt.tsv | 1 + .../resources/cloudformation/drop-policy.tsv | 6 + .../cloudformation/schema-surface.tsv | 1 + .../supported-resource-types.tsv | 1 + tools/aws/regen_cfn_property_types.py | 3 +- tools/docs/cfn_resource_types.yaml | 1 + 14 files changed, 1105 insertions(+), 20 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventsConnectionIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/provisioners/EventsConnectionCfnProvisionerTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 0c81f0d14d..8cafb9071a 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -244,7 +244,7 @@ cross-resource references. | Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` | | Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `/`; `EnabledMfas` is applied with `SetUserPoolMfaConfig`, as on AWS, and once `SMS_MFA` is on only `MfaConfiguration: OFF` turns it off), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolIdentityProvider` (Ref returns the ProviderName; changing only `ProviderType` is refused, as on AWS, because the name is always the template's and the replacement would need the same address), `UserPoolResourceServer`, `UserPoolUser`, `UserPoolUserToGroupAttachment` | | ACM | `Certificate` | -| EventBridge | `Rule`, `EventBus`, `EventBusPolicy`, `ApiDestination`, `Archive` (`KmsKeyIdentifier` is ignored) | +| EventBridge | `Rule`, `EventBus`, `EventBusPolicy`, `ApiDestination`, `Archive` (`KmsKeyIdentifier` is ignored), `Connection` (Ref returns the connection name; an update changes the supplied properties in place and a dropped `KmsKeyIdentifier` or `InvocationConnectivityParameters` is cleared, a dropped `Description` stays as it is and an empty one clears it, while renaming it or dropping `AuthorizationType` or `AuthParameters` is refused; `KmsKeyIdentifier` and `InvocationConnectivityParameters` are stored and not applied) | | EventBridge V2 | `EventBus`, `Subscriber` (delivers only to Amazon SQS queues; `Transformer` RAW or WITH_METADATA; a target parameter takes a literal or a `$events` path) | | EventBridge Scheduler | `Schedule`, `ScheduleGroup` | | Transfer Family | `Server` (management plane only; Ref returns the server ARN; Arn, ServerId and State attributes supported; AS2 managed egress IPs are not modeled; Domain replacement and IdentityProviderType changes are not supported), `User` (management plane only; Ref returns the user ARN; Arn attribute supported; Policy and PosixProfile are not supported; a ServerId or UserName change replaces the user) | diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java index dce6270871..cf8da004bb 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java @@ -244,6 +244,15 @@ public final class CfnRollback { */ public static final String EVENT_BUS_UPDATE_SNAPSHOT_ATTR = "__FlociEventBusUpdateSnapshot"; + /** + * Holds the description, authorization type, auth and connectivity parameters, KMS key, + * authorization state and timestamps an EventBridge connection carried before an in-place + * update changed them, so a failed stack update can put them back. The auth parameters hold the + * connection's credentials, as the connection itself does. Written by + * {@code EventsCfnProvisioner} before its update call and spent by its {@code rollbackUpdate}. + */ + public static final String CONNECTION_UPDATE_SNAPSHOT_ATTR = "__FlociConnectionUpdateSnapshot"; + /** * Holds the name, description and endpoint configuration a REST API had before an in-place * update patched them, so a failed stack update can put them back, and a {@code body} flag set diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisioner.java index 0532105ac1..acbca418cc 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisioner.java @@ -13,6 +13,8 @@ import io.floci.aws.services.cloudformation.model.StackResource; import io.floci.aws.services.eventbridge.EventBridgeService; import io.floci.aws.services.eventbridge.model.ApiDestination; import io.floci.aws.services.eventbridge.model.BatchParameters; +import io.floci.aws.services.eventbridge.model.Connection; +import io.floci.aws.services.eventbridge.model.ConnectionState; import io.floci.aws.services.eventbridge.model.EcsParameters; import io.floci.aws.services.eventbridge.model.EventBus; import io.floci.aws.services.eventbridge.model.HttpParameters; @@ -25,9 +27,11 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; @@ -62,6 +66,7 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { /** The shape AWS::Events::Rule's resource schema declares for its targets. */ private static final String TARGETS = CfnPropertyTypes.propertyShape("AWS::Events::Rule", "Targets"); + private static final String CONNECTION = "AWS::Events::Connection"; private static final String EVENT_BUS_CREATED_TIME_ATTR = "FlociEventBusCreatedTime"; private static final String EVENT_BUS_MANAGED_TAG_KEYS_ATTR = "FlociEventBusManagedTagKeys"; private static final String EVENT_BUS_MANAGED_POLICY_ATTR = "FlociEventBusManagedPolicy"; @@ -71,6 +76,15 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { Pattern.compile("[\\p{L}\\p{N}\\p{Z}_.:/=+\\-@]*"); private static final Pattern STATEMENT_ID_PATTERN = Pattern.compile("[a-zA-Z0-9\\-_]+"); private static final int STATEMENT_ID_MAX_LENGTH = 64; + /** Connection properties an update cannot clear (EventBridge keeps an omitted field) or replace. */ + private static final Set CONNECTION_REFUSED_DROPS = Set.of( + "Name", "AuthorizationType", "AuthParameters"); + /** + * Connection properties a template that drops them clears. A dropped {@code Description} is not + * among them: CloudFormation leaves it as it is, and only an explicit empty string clears it. + */ + private static final Set CONNECTION_CLEARED_DROPS = Set.of( + "InvocationConnectivityParameters", "KmsKeyIdentifier"); private final EventBridgeService eventBridgeService; @@ -82,7 +96,7 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { @Override public Set resourceTypes() { return Set.of("AWS::Events::Rule", "AWS::Events::EventBus", "AWS::Events::EventBusPolicy", - "AWS::Events::ApiDestination"); + "AWS::Events::ApiDestination", "AWS::Events::Connection"); } @Override @@ -92,6 +106,7 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { case "AWS::Events::EventBus" -> provisionEventBus(r, props, ctx); case "AWS::Events::EventBusPolicy" -> provisionEventBusPolicy(r, props, ctx); case "AWS::Events::ApiDestination" -> provisionApiDestination(r, props, ctx); + case "AWS::Events::Connection" -> provisionConnection(r, props, ctx); default -> throw new IllegalStateException( "EventsCfnProvisioner cannot handle " + r.getResourceType()); } @@ -124,6 +139,7 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { case "AWS::Events::EventBus" -> deleteEventBusSafe(physicalId, region); case "AWS::Events::EventBusPolicy" -> removeEventBusPolicySafe(physicalId, region); case "AWS::Events::ApiDestination" -> deleteApiDestinationSafe(physicalId, region); + case "AWS::Events::Connection" -> deleteConnectionSafe(physicalId, region); default -> { // no other type reaches this provisioner } @@ -352,6 +368,9 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { if ("AWS::Events::EventBus".equals(resource.getResourceType())) { return rollbackEventBusUpdate(resource); } + if ("AWS::Events::Connection".equals(resource.getResourceType())) { + return rollbackConnectionUpdate(resource); + } String rawSnapshot = resource.getAttributes().get(CfnRollback.RULE_TARGETS_SNAPSHOT_ATTR); if (rawSnapshot == null) { return false; @@ -1015,6 +1034,132 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { "ResourceNotFoundException"); } + /** + * {@code AWS::Events::Connection}: {@code Ref} is the connection name, {@code Fn::GetAtt} gives + * {@code Arn} and {@code SecretArn}. An update changes the supplied properties in place, and a + * template that drops {@code InvocationConnectivityParameters} or {@code KmsKeyIdentifier} + * clears it. A dropped {@code Description} stays as it is and an empty one clears it. These + * follow what a real AWS account does, checked against a stack. EventBridge's UpdateConnection leaves an omitted + * {@code AuthorizationType} or {@code AuthParameters} as it is, so dropping one is refused rather + * than left silently stale, and a different name is a replacement, refused too. The properties are + * read as the resource handler reads them, so an {@code ApiKeyAuthParameters} without its + * {@code ApiKeyValue} fails the resource. A connection an older Floci stubbed names nothing that + * exists, so an update creates it. + */ + private void provisionConnection(StackResource r, JsonNode template, ProvisionContext ctx) { + // A snapshot describes the update in flight; one an earlier update left behind is stale, and + // a check below that refuses this update would otherwise leave it for the rollback to restore + r.getAttributes().remove(CfnRollback.CONNECTION_UPDATE_SNAPSHOT_ATTR); + Map attributesBefore = new HashMap<>(r.getAttributes()); + boolean updating = ctx.isUpdate() && !CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore); + Set cleared = new HashSet<>(); + if (updating) { + for (String dropped : ctx.droppedProperties(template)) { + if (CONNECTION_REFUSED_DROPS.contains(dropped)) { + throw new AwsException("ValidationError", "Removing " + dropped + + " from a Connection is not supported: EventBridge keeps the value it has.", 400); + } + if (CONNECTION_CLEARED_DROPS.contains(dropped)) { + cleared.add(dropped); + } + } + } + JsonNode props = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(CONNECTION, template); + String name = ctx.stablePhysicalName( + ctx.resolveOptional(props, "Name"), r.getLogicalId(), 64, false); + if (updating && ctx.priorPhysicalId() != null && !ctx.priorPhysicalId().equals(name)) { + throw new AwsException("ValidationError", + "Updating Connection Name requires resource replacement, which is not supported.", 400); + } + + String description = ctx.resolveOptional(props, "Description"); + String authorizationType = ctx.resolveOptional(props, "AuthorizationType"); + String authParameters = resolvedObjectAsJson(props, "AuthParameters", ctx); + String connectivityParameters = resolvedObjectAsJson(props, "InvocationConnectivityParameters", ctx); + String kmsKeyIdentifier = ctx.resolveOptional(props, "KmsKeyIdentifier"); + + Connection connection; + if (updating && ctx.reusesPriorEntity(name)) { + snapshotConnectionBeforeUpdate(r, eventBridgeService.describeConnection(name, ctx.region()), + ctx.region()); + connection = eventBridgeService.updateConnection(name, description, authorizationType, + authParameters, connectivityParameters, kmsKeyIdentifier, cleared, ctx.region()); + } else { + connection = eventBridgeService.createConnection(name, description, authorizationType, + authParameters, connectivityParameters, kmsKeyIdentifier, ctx.region()); + } + + r.setPhysicalId(name); + String arn = connection.getConnectionArn(); + r.getAttributes().put("Arn", arn); + // The ARN EventBridge allows in a policy is the one without the trailing id: connection/ + r.getAttributes().put("ArnForPolicy", arn.substring(0, arn.lastIndexOf('/'))); + r.getAttributes().put("SecretArn", connection.getSecretArn()); + r.getAttributes().put("Name", name); + } + + /** + * A nested object property with its intrinsics resolved, as the JSON text EventBridge stores; + * null when the property is absent or empty, which the service reads as "not supplied". + */ + private static String resolvedObjectAsJson(JsonNode props, String name, ProvisionContext ctx) { + if (props == null || !props.has(name) || props.get(name).isNull()) { + return null; + } + JsonNode resolved = ctx.engine().resolveNode(props.get(name)); + return resolved != null && resolved.isObject() && !resolved.isEmpty() ? resolved.toString() : null; + } + + private void snapshotConnectionBeforeUpdate(StackResource r, Connection current, String region) { + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("region", region); + snapshot.put("name", current.getName()); + snapshot.put("description", current.getDescription()); + snapshot.put("authorizationType", current.getAuthorizationType()); + snapshot.put("authParameters", current.getAuthParameters()); + snapshot.put("invocationConnectivityParameters", current.getInvocationConnectivityParameters()); + snapshot.put("kmsKeyIdentifier", current.getKmsKeyIdentifier()); + snapshot.put("connectionState", + current.getConnectionState() == null ? null : current.getConnectionState().name()); + snapshot.put("stateReason", current.getStateReason()); + snapshot.put("lastModifiedTime", + current.getLastModifiedTime() == null ? null : current.getLastModifiedTime().toString()); + snapshot.put("lastAuthorizedTime", + current.getLastAuthorizedTime() == null ? null : current.getLastAuthorizedTime().toString()); + r.getAttributes().put(CfnRollback.CONNECTION_UPDATE_SNAPSHOT_ATTR, snapshot.toString()); + } + + // The snapshot is spent only once the restore succeeded: a restore that throws leaves it for the next attempt + private boolean rollbackConnectionUpdate(StackResource resource) { + JsonNode snapshot = CfnRollback.updateSnapshot(resource, CfnRollback.CONNECTION_UPDATE_SNAPSHOT_ATTR); + if (snapshot == null) { + return false; + } + Connection previous = new Connection(); + previous.setName(snapshot.path("name").asText()); + previous.setDescription(snapshotText(snapshot, "description")); + previous.setAuthorizationType(snapshotText(snapshot, "authorizationType")); + previous.setAuthParameters(snapshotText(snapshot, "authParameters")); + previous.setInvocationConnectivityParameters(snapshotText(snapshot, "invocationConnectivityParameters")); + previous.setKmsKeyIdentifier(snapshotText(snapshot, "kmsKeyIdentifier")); + String state = snapshotText(snapshot, "connectionState"); + previous.setConnectionState(state == null ? null : ConnectionState.valueOf(state)); + previous.setStateReason(snapshotText(snapshot, "stateReason")); + String modified = snapshotText(snapshot, "lastModifiedTime"); + previous.setLastModifiedTime(modified == null ? null : Instant.parse(modified)); + String authorized = snapshotText(snapshot, "lastAuthorizedTime"); + previous.setLastAuthorizedTime(authorized == null ? null : Instant.parse(authorized)); + eventBridgeService.restoreConnection(previous, snapshot.path("region").asText()); + resource.getAttributes().remove(CfnRollback.CONNECTION_UPDATE_SNAPSHOT_ATTR); + return true; + } + + private void deleteConnectionSafe(String name, String region) { + CfnDeletes.safeDelete("EventBridge connection", name, + () -> eventBridgeService.deleteConnection(name, region), + "ResourceNotFoundException"); + } + /** * A template's {@code EcsParameters} in the shape PutTargets takes. The resource schema * capitalizes members the EventBridge API spells in camel case ({@code AwsVpcConfiguration}, diff --git a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java index 0e1ce7f908..4903797940 100644 --- a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java @@ -2010,6 +2010,18 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns public Connection updateConnection(String name, String description, String authorizationType, String authParameters, String invocationConnectivityParameters, String kmsKeyIdentifier, String region) { + return updateConnection(name, description, authorizationType, authParameters, + invocationConnectivityParameters, kmsKeyIdentifier, Set.of(), region); + } + + /** + * As {@link #updateConnection(String, String, String, String, String, String, String)}, and the + * settings named in {@code cleared} ({@code InvocationConnectivityParameters} or + * {@code KmsKeyIdentifier}) are removed, as a CloudFormation update that drops them does. + */ + public Connection updateConnection(String name, String description, String authorizationType, + String authParameters, String invocationConnectivityParameters, + String kmsKeyIdentifier, Set cleared, String region) { String key = connectionKey(region, name); Connection connection = connectionStore.get(key) .orElseThrow(() -> new AwsException("ResourceNotFoundException", @@ -2023,7 +2035,8 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns connection.setAuthorizationType(authorizationType); } if (description != null) { - connection.setDescription(description); + // An empty description clears it, as the stack update that sets one does + connection.setDescription(description.isEmpty() ? null : description); } if (authParameters != null) { connection.setAuthParameters(authParameters); @@ -2034,6 +2047,12 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns if (kmsKeyIdentifier != null) { connection.setKmsKeyIdentifier(kmsKeyIdentifier); } + if (cleared.contains("InvocationConnectivityParameters")) { + connection.setInvocationConnectivityParameters(null); + } + if (cleared.contains("KmsKeyIdentifier")) { + connection.setKmsKeyIdentifier(null); + } Instant now = Instant.now(); connection.setConnectionState(ConnectionState.AUTHORIZED); connection.setLastModifiedTime(now); @@ -2042,6 +2061,31 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns return connection; } + /** + * Puts a connection's mutable settings back to the values {@code previous} carries, exactly: + * unlike {@link #updateConnection} a null clears the field, and the authorization state and + * timestamps come back with it. The ARN, secret ARN and creation time are the stored + * connection's own and stay. Used by a failed CloudFormation update to undo an in-place update. + */ + public synchronized Connection restoreConnection(Connection previous, String region) { + String key = connectionKey(region, previous.getName()); + Connection connection = connectionStore.get(key) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Connection " + previous.getName() + " does not exist.", 400)); + connection.setDescription(previous.getDescription()); + connection.setAuthorizationType(previous.getAuthorizationType()); + connection.setAuthParameters(previous.getAuthParameters()); + connection.setInvocationConnectivityParameters(previous.getInvocationConnectivityParameters()); + connection.setKmsKeyIdentifier(previous.getKmsKeyIdentifier()); + connection.setConnectionState(previous.getConnectionState()); + connection.setStateReason(previous.getStateReason()); + connection.setLastModifiedTime(previous.getLastModifiedTime()); + connection.setLastAuthorizedTime(previous.getLastAuthorizedTime()); + connectionStore.put(key, connection); + LOG.infov("Restored connection: {0}", previous.getName()); + return connection; + } + public Connection deleteConnection(String name, String region) { String key = connectionKey(region, name); Connection connection = connectionStore.get(key) diff --git a/src/main/resources/aws/cfn-property-types.json b/src/main/resources/aws/cfn-property-types.json index 4d57fbde96..ad028c1a3b 100644 --- a/src/main/resources/aws/cfn-property-types.json +++ b/src/main/resources/aws/cfn-property-types.json @@ -2,7 +2,7 @@ "_source": { "generator": "tools/aws/regen_cfn_property_types.py", "schemas": "https://schema.cloudformation.us-east-1.amazonaws.com/CloudformationSchema.zip", - "retrieved": "2026-11-18", + "retrieved": "2026-11-21", "note": "make cfn-property-types-verify checks the file against AWS." }, "operations": { @@ -14,6 +14,7 @@ "AWS::EKS::Cluster": "AWS::EKS::Cluster", "AWS::EMRContainers::VirtualCluster": "AWS::EMRContainers::VirtualCluster", "AWS::EMRServerless::Application": "AWS::EMRServerless::Application", + "AWS::Events::Connection": "AWS::Events::Connection", "AWS::Events::Rule": "AWS::Events::Rule", "AWS::Lambda::Function": "AWS::Lambda::Function", "AWS::Lambda::LayerVersion": "AWS::Lambda::LayerVersion", @@ -104,28 +105,28 @@ "AWS::DSQL::Cluster": { "type": "structure", "members": { - "DeletionProtectionEnabled": "Boolean", - "Tags": "AWS::DSQL::Cluster.Tags", + "Status": "String", + "PolicyVersion": "String", + "EncryptionDetails": "AWS::DSQL::Cluster.EncryptionDetails", + "KmsEncryptionKey": "String", + "MultiRegionProperties": "AWS::DSQL::Cluster.MultiRegionProperties", "ResourceArn": "String", "Identifier": "String", - "CreationTime": "String", - "Status": "String", "VpcEndpointServiceName": "String", - "MultiRegionProperties": "AWS::DSQL::Cluster.MultiRegionProperties", - "KmsEncryptionKey": "String", - "EncryptionDetails": "AWS::DSQL::Cluster.EncryptionDetails", - "Endpoint": "String", "VpcEndpoint": "String", - "PolicyVersion": "String", + "Endpoint": "String", + "MetricGroups": "AWS::DSQL::Cluster.MetricGroups", + "CreationTime": "String", "PolicyDocument": "String", - "MetricGroups": "AWS::DSQL::Cluster.MetricGroups" + "DeletionProtectionEnabled": "Boolean", + "Tags": "AWS::DSQL::Cluster.Tags" } }, "AWS::DSQL::Cluster.EncryptionDetails": { "type": "structure", "members": { - "EncryptionStatus": "String", "EncryptionType": "String", + "EncryptionStatus": "String", "KmsKeyArn": "String" } }, @@ -136,8 +137,8 @@ "AWS::DSQL::Cluster.MultiRegionProperties": { "type": "structure", "members": { - "WitnessRegion": "String", - "Clusters": "AWS::DSQL::Cluster.MultiRegionProperties.Clusters" + "Clusters": "AWS::DSQL::Cluster.MultiRegionProperties.Clusters", + "WitnessRegion": "String" } }, "AWS::DSQL::Cluster.MultiRegionProperties.Clusters": { @@ -160,8 +161,8 @@ "AWS::DSQL::Cluster/Tag": { "type": "structure", "members": { - "Key": "AWS::DSQL::Cluster/Tag.Key", - "Value": "AWS::DSQL::Cluster/Tag.Value" + "Value": "AWS::DSQL::Cluster/Tag.Value", + "Key": "AWS::DSQL::Cluster/Tag.Key" }, "required": [ "Key", @@ -2425,6 +2426,205 @@ "maxLength": 50, "pattern": "^[a-zA-Z]+[-_]*[a-zA-Z]+$" }, + "AWS::Events::Connection": { + "type": "structure", + "members": { + "Name": "AWS::Events::Connection.Name", + "Arn": "AWS::Events::Connection.Arn", + "ArnForPolicy": "AWS::Events::Connection.ArnForPolicy", + "SecretArn": "AWS::Events::Connection.SecretArn", + "Description": "AWS::Events::Connection.Description", + "AuthorizationType": "String", + "AuthParameters": "AWS::Events::Connection/AuthParameters", + "InvocationConnectivityParameters": "AWS::Events::Connection.InvocationConnectivityParameters", + "KmsKeyIdentifier": "AWS::Events::Connection.KmsKeyIdentifier" + } + }, + "AWS::Events::Connection.Arn": { + "type": "string", + "pattern": "^arn:aws([a-z]|\\-)*:events:([a-z]|\\d|\\-)*:([0-9]{12})?:connection\\/[\\.\\-_A-Za-z0-9]+\\/[\\-A-Za-z0-9]+$" + }, + "AWS::Events::Connection.ArnForPolicy": { + "type": "string", + "pattern": "^arn:aws([a-z]|\\-)*:events:([a-z]|\\d|\\-)*:([0-9]{12})?:connection\\/[\\.\\-_A-Za-z0-9]+$" + }, + "AWS::Events::Connection.Description": { + "type": "string", + "maxLength": 512 + }, + "AWS::Events::Connection.InvocationConnectivityParameters": { + "type": "structure", + "members": { + "ResourceParameters": "AWS::Events::Connection/ResourceParameters" + }, + "required": [ + "ResourceParameters" + ] + }, + "AWS::Events::Connection.KmsKeyIdentifier": { + "type": "string", + "maxLength": 2048, + "pattern": "^[a-zA-Z0-9_\\-/:]*$" + }, + "AWS::Events::Connection.Name": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "[\\.\\-_A-Za-z0-9]+" + }, + "AWS::Events::Connection.SecretArn": { + "type": "string", + "pattern": "^arn:aws([a-z]|\\-)*:secretsmanager:([a-z]|\\d|\\-)*:([0-9]{12})?:secret:([a-z]|\\d|\\-)*(!)*[\\/_+=\\.@\\-A-Za-z0-9]+$" + }, + "AWS::Events::Connection/ApiKeyAuthParameters": { + "type": "structure", + "members": { + "ApiKeyName": "AWS::Events::Connection/ApiKeyAuthParameters.ApiKeyName", + "ApiKeyValue": "AWS::Events::Connection/ApiKeyAuthParameters.ApiKeyValue" + }, + "required": [ + "ApiKeyName", + "ApiKeyValue" + ] + }, + "AWS::Events::Connection/ApiKeyAuthParameters.ApiKeyName": { + "type": "string", + "pattern": "^[ \\t]*[^\\x00-\\x1F\\x7F]+([ \\t]+[^\\x00-\\x1F\\x7F]+)*[ \\t]*$" + }, + "AWS::Events::Connection/ApiKeyAuthParameters.ApiKeyValue": { + "type": "string", + "pattern": "^[ \\t]*[^\\x00-\\x1F\\x7F]+([ \\t]+[^\\x00-\\x1F\\x7F]+)*[ \\t]*$" + }, + "AWS::Events::Connection/AuthParameters": { + "type": "structure", + "members": { + "ApiKeyAuthParameters": "AWS::Events::Connection/ApiKeyAuthParameters", + "BasicAuthParameters": "AWS::Events::Connection/BasicAuthParameters", + "OAuthParameters": "AWS::Events::Connection/OAuthParameters", + "InvocationHttpParameters": "AWS::Events::Connection/ConnectionHttpParameters", + "ConnectivityParameters": "AWS::Events::Connection/ConnectivityParameters" + } + }, + "AWS::Events::Connection/BasicAuthParameters": { + "type": "structure", + "members": { + "Username": "AWS::Events::Connection/BasicAuthParameters.Username", + "Password": "AWS::Events::Connection/BasicAuthParameters.Password" + }, + "required": [ + "Username", + "Password" + ] + }, + "AWS::Events::Connection/BasicAuthParameters.Password": { + "type": "string", + "pattern": "^[ \\t]*[^\\x00-\\x1F\\x7F]+([ \\t]+[^\\x00-\\x1F\\x7F]+)*[ \\t]*$" + }, + "AWS::Events::Connection/BasicAuthParameters.Username": { + "type": "string", + "pattern": "^[ \\t]*[^\\x00-\\x1F\\x7F]+([ \\t]+[^\\x00-\\x1F\\x7F]+)*[ \\t]*$" + }, + "AWS::Events::Connection/ClientParameters": { + "type": "structure", + "members": { + "ClientID": "AWS::Events::Connection/ClientParameters.ClientID", + "ClientSecret": "AWS::Events::Connection/ClientParameters.ClientSecret" + }, + "required": [ + "ClientID", + "ClientSecret" + ] + }, + "AWS::Events::Connection/ClientParameters.ClientID": { + "type": "string", + "pattern": "^[ \\t]*[^\\x00-\\x1F\\x7F]+([ \\t]+[^\\x00-\\x1F\\x7F]+)*[ \\t]*$" + }, + "AWS::Events::Connection/ClientParameters.ClientSecret": { + "type": "string", + "pattern": "^[ \\t]*[^\\x00-\\x1F\\x7F]+([ \\t]+[^\\x00-\\x1F\\x7F]+)*[ \\t]*$" + }, + "AWS::Events::Connection/ConnectionHttpParameters": { + "type": "structure", + "members": { + "HeaderParameters": "AWS::Events::Connection/ConnectionHttpParameters.HeaderParameters", + "QueryStringParameters": "AWS::Events::Connection/ConnectionHttpParameters.QueryStringParameters", + "BodyParameters": "AWS::Events::Connection/ConnectionHttpParameters.BodyParameters" + } + }, + "AWS::Events::Connection/ConnectionHttpParameters.BodyParameters": { + "type": "list", + "member": "AWS::Events::Connection/Parameter" + }, + "AWS::Events::Connection/ConnectionHttpParameters.HeaderParameters": { + "type": "list", + "member": "AWS::Events::Connection/Parameter" + }, + "AWS::Events::Connection/ConnectionHttpParameters.QueryStringParameters": { + "type": "list", + "member": "AWS::Events::Connection/Parameter" + }, + "AWS::Events::Connection/ConnectivityParameters": { + "type": "structure", + "members": { + "ResourceParameters": "AWS::Events::Connection/ResourceParameters" + }, + "required": [ + "ResourceParameters" + ] + }, + "AWS::Events::Connection/OAuthParameters": { + "type": "structure", + "members": { + "ClientParameters": "AWS::Events::Connection/ClientParameters", + "AuthorizationEndpoint": "AWS::Events::Connection/OAuthParameters.AuthorizationEndpoint", + "HttpMethod": "String", + "OAuthHttpParameters": "AWS::Events::Connection/ConnectionHttpParameters" + }, + "required": [ + "ClientParameters", + "AuthorizationEndpoint", + "HttpMethod" + ] + }, + "AWS::Events::Connection/OAuthParameters.AuthorizationEndpoint": { + "type": "string", + "minLength": 1, + "maxLength": 2048, + "pattern": "^((%[0-9A-Fa-f]{2}|[-()_.!~*';/?:@\\x26=+$,A-Za-z0-9])+)([).!';/?:,])?$" + }, + "AWS::Events::Connection/Parameter": { + "type": "structure", + "members": { + "Key": "String", + "Value": "String", + "IsValueSecret": "Boolean" + }, + "required": [ + "Key", + "Value" + ] + }, + "AWS::Events::Connection/ResourceParameters": { + "type": "structure", + "members": { + "ResourceConfigurationArn": "AWS::Events::Connection/ResourceParameters.ResourceConfigurationArn", + "ResourceAssociationArn": "AWS::Events::Connection/ResourceParameters.ResourceAssociationArn" + }, + "required": [ + "ResourceConfigurationArn" + ] + }, + "AWS::Events::Connection/ResourceParameters.ResourceAssociationArn": { + "type": "string", + "minLength": 20, + "maxLength": 2048, + "pattern": "^arn:[a-z0-9\\-]+:vpc-lattice:[a-zA-Z0-9\\-]+:\\d{12}:servicenetworkresourceassociation/snra-[0-9a-z]{17}$" + }, + "AWS::Events::Connection/ResourceParameters.ResourceConfigurationArn": { + "type": "string", + "maxLength": 2048, + "pattern": "^arn:[a-z0-9f\\-]+:vpc-lattice:[a-zA-Z0-9\\-]+:\\d{12}:resourceconfiguration/rcfg-[0-9a-z]{17}$" + }, "AWS::Events::Rule": { "type": "structure", "members": { diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index 513779b904..29b60b3e5f 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -608,6 +608,9 @@ "ArchiveName", "SourceArn" ], + "AWS::Events::Connection": [ + "Name" + ], "AWS::Events::EventBus": [ "Name" ], diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventsConnectionIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventsConnectionIntegrationTest.java new file mode 100644 index 0000000000..77a21bd445 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventsConnectionIntegrationTest.java @@ -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 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 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 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 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 connection(String name, String description) { + Map apiKey = new LinkedHashMap<>(); + apiKey.put("ApiKeyName", "Authorization"); + apiKey.put("ApiKeyValue", Map.of("Fn::Sub", "Bearer ${Token}")); + Map 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 connectionProperties, boolean withDestination) + throws Exception { + return template(connectionProperties, withDestination, null); + } + + private static String template(Map connectionProperties, boolean withDestination, + String destinationName) throws Exception { + Map 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 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)); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/EventsConnectionCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EventsConnectionCfnProvisionerTest.java new file mode 100644 index 0000000000..23d3af7a48 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EventsConnectionCfnProvisionerTest.java @@ -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 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 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 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()); + } +} diff --git a/src/test/resources/cloudformation/change-exempt.tsv b/src/test/resources/cloudformation/change-exempt.tsv index 83ea028ac8..b7e8bb8caf 100644 --- a/src/test/resources/cloudformation/change-exempt.tsv +++ b/src/test/resources/cloudformation/change-exempt.tsv @@ -110,6 +110,7 @@ AWS::ElasticLoadBalancingV2::LoadBalancer prior entity found by reusesPriorEntit AWS::ElasticLoadBalancingV2::TargetGroup prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work AWS::Events::ApiDestination prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work AWS::Events::Archive prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work +AWS::Events::Connection prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work AWS::Events::EventBus update not yet on the engine's changes (#6606) AWS::Events::EventBusPolicy update not yet on the engine's changes (#6606) AWS::Events::Rule update not yet on the engine's changes (#6606) diff --git a/src/test/resources/cloudformation/drop-policy.tsv b/src/test/resources/cloudformation/drop-policy.tsv index 1ebbe217e5..4abbf1a881 100644 --- a/src/test/resources/cloudformation/drop-policy.tsv +++ b/src/test/resources/cloudformation/drop-policy.tsv @@ -154,6 +154,12 @@ AWS::ECS::Service NetworkConfiguration keep:the update leaves a missing network AWS::ECS::Service ServiceName keep:the prior name is reused AWS::ECS::Service ServiceRegistries keep:AWS removes registries only through a declared empty list AWS::ECS::Service TaskDefinition keep:required for the ECS controller +AWS::Events::Connection AuthParameters keep:refused with a ValidationError, EventBridge keeps the value it has; a real AWS account fails the update too +AWS::Events::Connection AuthorizationType keep:refused with a ValidationError, EventBridge keeps the value it has; a real AWS account fails the update too +AWS::Events::Connection Description keep:a real AWS account leaves a dropped Description as it is; an empty one clears it +AWS::Events::Connection InvocationConnectivityParameters clear a real AWS account clears it +AWS::Events::Connection KmsKeyIdentifier clear a real AWS account clears it +AWS::Events::Connection Name keep:refused with a ValidationError, a different name is a replacement, which a real AWS account performs and Floci does not AWS::KMS::Key Description clear cleared to the empty description, KMS's own empty state; the CloudFormation page lists no default AWS::KMS::Key EnableKeyRotation default:false the CloudFormation page: EnableKeyRotation defaults to false AWS::KMS::Key Enabled default:true the CloudFormation page: Enabled defaults to true diff --git a/src/test/resources/cloudformation/schema-surface.tsv b/src/test/resources/cloudformation/schema-surface.tsv index 107efd8d19..8c70a94e72 100644 --- a/src/test/resources/cloudformation/schema-surface.tsv +++ b/src/test/resources/cloudformation/schema-surface.tsv @@ -123,6 +123,7 @@ AWS::ElasticLoadBalancingV2::LoadBalancer CanonicalHostedZoneID,DNSName,LoadBala AWS::ElasticLoadBalancingV2::TargetGroup LoadBalancerArns,TargetGroupArn,TargetGroupFullName,TargetGroupName HealthCheckEnabled,HealthCheckIntervalSeconds,HealthCheckPath,HealthCheckPort,HealthCheckProtocol,HealthCheckTimeoutSeconds,HealthyThresholdCount,IpAddressType,Matcher,Name,Port,Protocol,ProtocolVersion,Tags,TargetControlPort,TargetGroupAttributes,TargetType,Targets,UnhealthyThresholdCount,VpcId AWS::Events::ApiDestination Arn,ArnForPolicy ConnectionArn,Description,HttpMethod,InvocationEndpoint,InvocationRateLimitPerSecond,Name AWS::Events::Archive Arn ArchiveName,Description,EventPattern,KmsKeyIdentifier,RetentionDays,SourceArn +AWS::Events::Connection Arn,ArnForPolicy,SecretArn AuthParameters,AuthorizationType,Description,InvocationConnectivityParameters,KmsKeyIdentifier,Name AWS::Events::EventBus Arn DeadLetterConfig,Description,EventSourceName,KmsKeyIdentifier,LogConfig,Name,Policy,Tags AWS::Events::EventBusPolicy EventBusName,Statement,StatementId AWS::Events::Rule Arn,RuleName Description,EventBusName,EventPattern,Name,RoleArn,ScheduleExpression,State,Tags,Targets diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 0bba27a23f..4b27569c5f 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -124,6 +124,7 @@ AWS::ElasticLoadBalancingV2::LoadBalancer ElbV2CfnProvisioner AWS::ElasticLoadBalancingV2::TargetGroup ElbV2CfnProvisioner AWS::Events::ApiDestination EventsCfnProvisioner AWS::Events::Archive EventsArchiveCfnProvisioner +AWS::Events::Connection EventsCfnProvisioner AWS::Events::EventBus EventsCfnProvisioner AWS::Events::EventBusPolicy EventsCfnProvisioner AWS::Events::Rule EventsCfnProvisioner diff --git a/tools/aws/regen_cfn_property_types.py b/tools/aws/regen_cfn_property_types.py index 6561b25ac7..35e5734e92 100644 --- a/tools/aws/regen_cfn_property_types.py +++ b/tools/aws/regen_cfn_property_types.py @@ -52,7 +52,8 @@ FETCH_TIMEOUT_SECONDS = 60 # The resource types whose provisioners read their properties through CfnPropertyTypes. RESOURCE_TYPES = ["AWS::AutoScaling::LaunchConfiguration", "AWS::DSQL::Cluster", "AWS::EC2::Instance", "AWS::EC2::LaunchTemplate", "AWS::ECS::TaskDefinition", "AWS::EKS::Cluster", - "AWS::EMRContainers::VirtualCluster", "AWS::EMRServerless::Application", "AWS::Events::Rule", + "AWS::EMRContainers::VirtualCluster", "AWS::EMRServerless::Application", + "AWS::Events::Connection", "AWS::Events::Rule", "AWS::Lambda::Function", "AWS::Lambda::LayerVersion", "AWS::SES::ConfigurationSetEventDestination"] diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index fbaa664bc1..d1d4ded9f2 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -249,6 +249,7 @@ notes: AWS::SES::EmailIdentity: 'BYODKIM is not supported by this resource; Easy DKIM DNS attributes use the shared emulator signing zone `dkim.amazonses.com` rather than AWS''s region- and identity-specific zone assignment' AWS::SES::ReceiptRule: 'stored in an existing SES receipt rule set; Ref and RuleName return the rule name; management plane only, with no inbound mail delivery' AWS::Events::Archive: '`KmsKeyIdentifier` is ignored' + AWS::Events::Connection: 'Ref returns the connection name; an update changes the supplied properties in place and a dropped `KmsKeyIdentifier` or `InvocationConnectivityParameters` is cleared, a dropped `Description` stays as it is and an empty one clears it, while renaming it or dropping `AuthorizationType` or `AuthParameters` is refused; `KmsKeyIdentifier` and `InvocationConnectivityParameters` are stored and not applied' AWS::EventsV2::Subscriber: 'delivers only to Amazon SQS queues; `Transformer` RAW or WITH_METADATA; a target parameter takes a literal or a `$events` path' AWS::AppConfig::Environment: '`Tags` and `DeletionProtectionCheck` are accepted and not stored' AWS::AppConfig::ConfigurationProfile: '`Tags`, `KmsKeyIdentifier`, `RetrievalRoleArn`, `Validators` and `DeletionProtectionCheck` are accepted and not stored'