From 180aef5e4490fd183a3abcaef09b05f219800094 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Thu, 17 Sep 2026 22:12:14 -0500 Subject: [PATCH] refactor(cloudformation): move the EC2 SecurityGroup and Instance types into per-service provisioners (#3810) * refactor(cloudformation): move the EC2 SecurityGroup and Instance types into per-service provisioners AWS::EC2::SecurityGroup moves out of CloudFormationResourceProvisioner into a new Ec2SecurityGroupCfnProvisioner with its six helpers, and AWS::EC2::Instance into a new Ec2InstanceCfnProvisioner. The code moves as written: the only changes are the ProvisionContext helpers in place of the monolith's identical private ones, explicit types and imports in place of var and inline qualified names, and a comment reworded around an em-dash. SecurityGroup gets its own class rather than joining Ec2SecurityGroupRuleCfnProvisioner: the schema coverage gate attributes attributes per type only through a statement switch on the resource type, and the rule provisioner has one shared path, so joining it would have meant restructuring that class too. The rule provisioner's shared rule mapping is still the one both use. Leaving the legacy switch puts both types under CfnSchemaCoverageTest. The read-only attributes neither arm set before are recorded as gaps rather than published, which would change what Fn::GetAtt returns: SecurityGroup Id, and Instance VpcId and State. The legacy switch goes from 23 to 21 types, the monolith from 3,413 to 3,133 lines, and its constructor loses ec2Service. * fix(cloudformation): guard EC2 instance provisioning when Properties is absent Ec2InstanceCfnProvisioner read props.path("NetworkInterfaces") without the props != null guard the rest of provision() uses, so an Instance declared with no Properties (valid: the registry schema has no required properties) threw an NPE and the resource went CREATE_FAILED. Guard the NetworkInterfaces block like the LaunchTemplate, SecurityGroupIds and Tags accesses above it. A carried-over gap from the monolith, surfaced by the move in this PR. --- .../CloudFormationResourceProvisioner.java | 280 ------------------ .../Ec2InstanceCfnProvisioner.java | 142 +++++++++ .../Ec2SecurityGroupCfnProvisioner.java | 224 ++++++++++++++ .../Ec2SecurityGroupRuleCfnProvisioner.java | 5 +- .../cloudformation/CfnProvisionerFixture.java | 5 +- .../Ec2InstanceCfnProvisionerTest.java | 133 +++++++++ .../Ec2SecurityGroupCfnProvisionerTest.java | 160 ++++++++++ .../cloudformation/getatt-attribute-gaps.tsv | 3 + .../supported-resource-types.tsv | 4 +- 9 files changed, 670 insertions(+), 286 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisionerTest.java diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index 14cac70fa8..877a84d424 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -9,17 +9,8 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudForm import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext; import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences; import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceProvisioner; -import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2SecurityGroupRuleCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.UpdateCleanupResult; import io.github.hectorvent.floci.services.eventbridge.model.Target; -import io.github.hectorvent.floci.services.ec2.model.IpPermission; -import io.github.hectorvent.floci.services.ec2.model.IpRange; -import io.github.hectorvent.floci.services.ec2.model.Ipv6Range; -import io.github.hectorvent.floci.services.ec2.model.PrefixListId; -import io.github.hectorvent.floci.services.ec2.model.SecurityGroup; -import io.github.hectorvent.floci.services.ec2.Ec2Service; -import io.github.hectorvent.floci.services.ec2.model.Tag; -import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair; import io.github.hectorvent.floci.services.eks.EksService; import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest; import io.github.hectorvent.floci.services.eks.model.Nodegroup; @@ -127,8 +118,6 @@ public class CloudFormationResourceProvisioner { "AWS::ApiGatewayV2::Route", "AWS::ApiGatewayV2::Stage", "AWS::CloudFormation::CustomResource", - "AWS::EC2::Instance", - "AWS::EC2::SecurityGroup", "AWS::EKS::Cluster", "AWS::EKS::Nodegroup", "AWS::IAM::AccessKey", @@ -157,7 +146,6 @@ public class CloudFormationResourceProvisioner { private final ObjectMapper objectMapper; private final CustomResourceResponseStore customResourceResponseStore; private final ContainerReachableEndpoint reachableEndpoint; - private final Ec2Service ec2Service; private final EksService eksService; // Item 15 decomposition: extracted per-service provisioners are consulted before the switch // below. As types migrate, their switch cases and provisionXxx methods are removed here; the @@ -176,7 +164,6 @@ public class CloudFormationResourceProvisioner { ObjectMapper objectMapper, CustomResourceResponseStore customResourceResponseStore, ContainerReachableEndpoint reachableEndpoint, - Ec2Service ec2Service, EksService eksService, CloudFormationResourceRegistry resourceRegistry, CfnDynamicReferences dynamicReferences, @@ -191,7 +178,6 @@ public class CloudFormationResourceProvisioner { this.objectMapper = objectMapper; this.customResourceResponseStore = customResourceResponseStore; this.reachableEndpoint = reachableEndpoint; - this.ec2Service = ec2Service; this.eksService = eksService; this.resourceRegistry = resourceRegistry; this.dynamicReferences = dynamicReferences; @@ -268,11 +254,6 @@ public class CloudFormationResourceProvisioner { case "AWS::ApiGatewayV2::Deployment" -> provisionApiGatewayV2Deployment(resource, properties, engine, region); case "AWS::CloudFormation::CustomResource" -> provisionCustomResource(resource, properties, engine, region, accountId, stackName); - // EC2 networking. These delegate to Ec2Service so the resources actually exist - // (describe-subnets, ELBv2, etc. can find them) instead of being stubbed with a - // fake physical id. Topological ordering guarantees parents are provisioned first. - case "AWS::EC2::SecurityGroup" -> provisionSecurityGroup(resource, properties, engine, region, stackName); - case "AWS::EC2::Instance" -> provisionEc2Instance(resource, properties, engine, region); case "AWS::EKS::Cluster" -> provisionEksCluster(resource, properties, engine, stackName); case "AWS::EKS::Nodegroup" -> provisionEksNodegroup(resource, properties, engine, stackName); default -> { @@ -488,8 +469,6 @@ public class CloudFormationResourceProvisioner { case "AWS::ApiGateway::RestApi" -> apiGatewayService.deleteRestApi(region, physicalId); case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId); case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region); - case "AWS::EC2::SecurityGroup" -> ec2Service.deleteSecurityGroup(region, physicalId); - case "AWS::EC2::Instance" -> ec2Service.terminateInstances(region, List.of(physicalId)); case "AWS::EKS::Cluster" -> eksService.deleteCluster(physicalId); // Warn for the same reason the create path does: the delete reports success over a // type nothing here removes, and at debug that is invisible at the default log level. @@ -501,60 +480,6 @@ public class CloudFormationResourceProvisioner { } } - // ── EC2 networking ───────────────────────────────────────────────────────── - // Each method delegates to Ec2Service so the resource really exists (describe-subnets, - // ELBv2 create-load-balancer, etc. resolve it). physicalId is set to the real EC2 id so - // Ref/exports resolve to a real vpc-/subnet-/... id rather than a stub. - - private void provisionSecurityGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String region, String stackName) { - String groupName = resolveOptional(props, "GroupName", engine); - if (groupName == null || groupName.isBlank()) { - groupName = generatePhysicalName(stackName, r.getLogicalId(), 255, false); - } - String description = resolveOptional(props, "GroupDescription", engine); - if (description == null || description.isBlank()) { - description = "Managed by CloudFormation"; - } - String vpcId = resolveOptional(props, "VpcId", engine); - // provision() re-runs for every resource on every update. Re-creating an unchanged group - // would mint a new group id (and collide on the name whenever the VPC id is stable), so - // reuse the group this resource already points at. - var reconciled = existingSecurityGroupToReconcile(r.getPhysicalId(), groupName, description, vpcId, region); - final SecurityGroup sg = reconciled != null - ? reconciled - : ec2Service.createSecurityGroup(region, groupName, description, vpcId); - // Ref on AWS::EC2::SecurityGroup returns the group id for VPC security groups. - r.setPhysicalId(sg.getGroupId()); - r.getAttributes().put("GroupId", sg.getGroupId()); - if (sg.getVpcId() != null) { - r.getAttributes().put("VpcId", sg.getVpcId()); - } - - // Inline rule properties — previously dropped, leaving the group empty. The mapping is - // shared with the standalone SecurityGroupIngress/Egress resource types, which live in - // Ec2SecurityGroupRuleCfnProvisioner; this arm joins them when it is extracted. - // Authorize appends without a duplicate check, so re-running this on a reused group would - // stack another copy of every inline rule on each update. Only authorize what the group - // does not already carry. - // - // Deliberately additive: a rule dropped from the template is not revoked here. Revoking - // the difference would mean revoking permissions this resource cannot prove it owns - a - // group can also carry rules from standalone AWS::EC2::SecurityGroupIngress/Egress - // resources, and clearing them on an unrelated update would close ports another stack - // resource is responsible for. Removing a rule the template no longer declares needs the - // provisioner to record what it authorized; noted as a follow-up. - var peerGroupId = peerGroupIdResolver(region, sg.getVpcId()); - if (props != null && props.has("SecurityGroupIngress")) { - authorizeMissing(props.get("SecurityGroupIngress"), sg.getIpPermissions(), engine, peerGroupId, - perms -> ec2Service.authorizeSecurityGroupIngress(region, sg.getGroupId(), perms)); - } - if (props != null && props.has("SecurityGroupEgress")) { - authorizeMissing(props.get("SecurityGroupEgress"), sg.getIpPermissionsEgress(), engine, peerGroupId, - perms -> ec2Service.authorizeSecurityGroupEgress(region, sg.getGroupId(), perms)); - } - } - // ── CloudWatch Logs ───────────────────────────────────────────────────────── /** @@ -612,211 +537,6 @@ public class CloudFormationResourceProvisioner { return new ArrayList<>(engine.resolveStringList(props.get(field))); } - private void provisionEc2Instance(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String region) { - String imageId = resolveOptional(props, "ImageId", engine); - String instanceType = resolveOptional(props, "InstanceType", engine); - String keyName = resolveOptional(props, "KeyName", engine); - - // An instance may reference a LaunchTemplate for its config; fields the - // properties don't set resolve from the template's data, as on AWS. - if (props != null && props.has("LaunchTemplate")) { - JsonNode ltRef = engine.resolveNode(props.get("LaunchTemplate")); - try { - var ltData = ec2Service.resolveLaunchTemplateData(region, - ltRef.path("LaunchTemplateId").asText(null), - ltRef.path("LaunchTemplateName").asText(null), - ltRef.path("Version").asText(null)); - if (imageId == null || imageId.isBlank()) { - imageId = ltData.getImageId(); - } - if (instanceType == null || instanceType.isBlank()) { - instanceType = ltData.getInstanceType(); - } - if (keyName == null || keyName.isBlank()) { - keyName = ltData.getKeyName(); - } - } catch (Exception e) { - LOG.debugv("Could not resolve launch template for instance {0}: {1}", - r.getLogicalId(), e.getMessage()); - } - } - if (instanceType == null || instanceType.isBlank()) { - instanceType = "t3.micro"; - } - String subnetId = resolveOptional(props, "SubnetId", engine); - String userData = resolveOptional(props, "UserData", engine); - String iamInstanceProfile = resolveOptional(props, "IamInstanceProfile", engine); - - List securityGroupIds = new ArrayList<>(); - if (props != null && props.has("SecurityGroupIds") && props.get("SecurityGroupIds").isArray()) { - for (JsonNode sg : props.get("SecurityGroupIds")) { - securityGroupIds.add(engine.resolve(sg)); - } - } - - List tags = new ArrayList<>(); - JsonNode tagsNode = props != null ? engine.resolveNode(props.get("Tags")) : null; - if (tagsNode != null && tagsNode.isArray()) { - for (JsonNode tag : tagsNode) { - String key = engine.resolve(tag.path("Key")); - if (!key.isEmpty()) { - tags.add(new Tag(key, engine.resolve(tag.path("Value")))); - } - } - } - - // The launch-time public-IP override rides on the primary network - // interface spec; absent means the subnet's MapPublicIpOnLaunch default. - Boolean associatePublicIp = null; - var networkInterfaces = props.path("NetworkInterfaces"); - if (networkInterfaces.isArray() && !networkInterfaces.isEmpty()) { - String assocRaw = engine.resolve(networkInterfaces.get(0).path("AssociatePublicIpAddress")); - if (assocRaw != null && !assocRaw.isBlank()) { - associatePublicIp = Boolean.parseBoolean(assocRaw); - } - } - - var reservation = ec2Service.runInstances(region, imageId, instanceType, 1, 1, keyName, - securityGroupIds, subnetId, null, tags, userData, iamInstanceProfile, - associatePublicIp); - var instance = reservation.getInstances().get(0); - r.setPhysicalId(instance.getInstanceId()); - r.getAttributes().put("InstanceId", instance.getInstanceId()); - r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true"); - ec2Service.awaitContainerLaunch(instance); - r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR); - if (instance.getPrivateIpAddress() != null) { - r.getAttributes().put("PrivateIp", instance.getPrivateIpAddress()); - } - if (instance.getPublicIpAddress() != null) { - r.getAttributes().put("PublicIp", instance.getPublicIpAddress()); - } - if (instance.getPrivateDnsName() != null) { - r.getAttributes().put("PrivateDnsName", instance.getPrivateDnsName()); - } - if (instance.getPublicDnsName() != null) { - r.getAttributes().put("PublicDnsName", instance.getPublicDnsName()); - } - if (instance.getPlacement() != null && instance.getPlacement().getAvailabilityZone() != null) { - r.getAttributes().put("AvailabilityZone", instance.getPlacement().getAvailabilityZone()); - } - } - - /** The VPC a security group would land in for this template value: the default when omitted. */ - private String effectiveVpcId(String vpcId, String region) { - return vpcId != null && !vpcId.isEmpty() ? vpcId : String.valueOf(ec2Service.resolveDefaultVpcId(region)); - } - - /** - * Authorizes each declared rule that the group does not already carry, one call per rule so a - * rejected rule cannot take its siblings down with it. - */ - private void authorizeMissing(JsonNode declared, List existing, - CloudFormationTemplateEngine engine, - java.util.function.UnaryOperator peerGroupId, - java.util.function.Consumer> authorize) { - Set present = existing.stream() - .map(p -> permissionKey(p, peerGroupId)) - .collect(java.util.stream.Collectors.toSet()); - for (JsonNode rule : declared) { - IpPermission perm = Ec2SecurityGroupRuleCfnProvisioner.toIpPermission(rule, engine); - if (present.add(permissionKey(perm, peerGroupId))) { - authorize.accept(List.of(perm)); - } - } - } - - /** - * Resolves a peer group's name to its id, the same lookup {@code Ec2Service} performs when it - * stores an authorized rule. Group names are unique per VPC rather than per region, so the - * search is confined to the group being authorized. A name matching nothing there stays a - * name, which is also what the service does. - */ - private java.util.function.UnaryOperator peerGroupIdResolver(String region, String vpcId) { - return groupName -> ec2Service.describeSecurityGroups(region, List.of(), List.of(groupName), Map.of()) - .stream() - .filter(peer -> Objects.equals(vpcId, peer.getVpcId())) - .map(SecurityGroup::getGroupId) - .filter(Objects::nonNull) - .findFirst() - .orElse(groupName); - } - - /** - * Identity of a permission for duplicate detection. {@link IpPermission} and the range types - * it holds define no {@code equals}, so compare a canonical rendering instead. Descriptions - * are left out: AWS treats a rule differing only by description as the same rule. - */ - private static String permissionKey(IpPermission p, java.util.function.UnaryOperator peerGroupId) { - return String.join("|", - String.valueOf(p.getIpProtocol()), - String.valueOf(p.getFromPort()), - String.valueOf(p.getToPort()), - p.getIpRanges().stream().map(IpRange::getCidrIp).filter(Objects::nonNull).sorted() - .collect(java.util.stream.Collectors.joining(",")), - p.getIpv6Ranges().stream().map(Ipv6Range::getCidrIpv6).filter(Objects::nonNull).sorted() - .collect(java.util.stream.Collectors.joining(",")), - p.getUserIdGroupPairs().stream() - .map(g -> peerIdentity(g, peerGroupId)) - .filter(Objects::nonNull).sorted() - .collect(java.util.stream.Collectors.joining(",")), - p.getPrefixListIds().stream().map(PrefixListId::getPrefixListId) - .filter(Objects::nonNull).sorted() - .collect(java.util.stream.Collectors.joining(","))); - } - - /** - * How a peer group is identified when two permissions are compared: its id whenever one can be - * had. A stored pair already carries one, because authorize resolves the name as it records the - * rule, while a pair straight from the template carries only the name it was declared with. - * Keying a resolved id against an unresolved name never matches, which re-authorized a rule - * naming its peer through {@code SourceSecurityGroupName} on every single update. - */ - private static String peerIdentity(UserIdGroupPair pair, - java.util.function.UnaryOperator peerGroupId) { - if (pair.getGroupId() != null) { - return pair.getGroupId(); - } - return pair.getGroupName() == null ? null : peerGroupId.apply(pair.getGroupName()); - } - - /** - * The security group this stack resource already points at, when an UpdateStack re-invocation - * left it unchanged. Unlike most resources the physical id here is the group id, not - * the name, so the rename check compares the stored group's name against the template's. - * - *

Returns {@code null} for a fresh create, a group deleted out of band, or any change AWS - * treats as a replacement: GroupName, GroupDescription and VpcId are all immutable on a - * security group, so a template that changes one wants a new group, not an edit to this one. - * The caller then creates. - */ - private SecurityGroup existingSecurityGroupToReconcile(String priorPhysicalId, String groupName, - String description, String vpcId, String region) { - if (priorPhysicalId == null || priorPhysicalId.isBlank()) { - return null; - } - try { - return ec2Service.describeSecurityGroups(region, List.of(priorPhysicalId), List.of(), Map.of()) - .stream() - .filter(existing -> groupName == null || groupName.equals(existing.getGroupName())) - .filter(existing -> description == null || description.equals(existing.getDescription())) - // Compare the VpcId the template would actually get, not the raw property. - // createSecurityGroup resolves an omitted VpcId to the region's default VPC, - // so the stored group always has one: comparing against a null property would - // either force a replacement on every update, or - the bug - let a template - // that drops VpcId keep a group sitting in the explicit VPC it named before. - .filter(existing -> effectiveVpcId(vpcId, region).equals(existing.getVpcId())) - .findFirst() - .orElse(null); - } catch (AwsException notFound) { - // Expected when the group was deleted out of band since the prior update. - LOG.debugv(notFound, "No existing security group {0} found on file, falling back to create", - priorPhysicalId); - return null; - } - } - // ── EKS ───────────────────────────────────────────────────────────────────── private void provisionEksCluster(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java new file mode 100644 index 0000000000..294ede1ae1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java @@ -0,0 +1,142 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData; +import io.github.hectorvent.floci.services.ec2.model.Reservation; +import io.github.hectorvent.floci.services.ec2.model.Tag; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** + * CloudFormation provisioning for {@code AWS::EC2::Instance}. It delegates to {@link Ec2Service} so + * the instance really launches, and sets the physical id to the real instance id so Ref and exports + * resolve to a real {@code i-} id rather than a stub. + */ +@ApplicationScoped +public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner { + + private static final Logger LOG = Logger.getLogger(Ec2InstanceCfnProvisioner.class); + + private static final String INSTANCE = "AWS::EC2::Instance"; + + private final Ec2Service ec2Service; + + @Inject + public Ec2InstanceCfnProvisioner(Ec2Service ec2Service) { + this.ec2Service = ec2Service; + } + + @Override + public Set resourceTypes() { + return Set.of(INSTANCE); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + CloudFormationTemplateEngine engine = ctx.engine(); + String region = ctx.region(); + String imageId = ctx.resolveOptional(props, "ImageId"); + String instanceType = ctx.resolveOptional(props, "InstanceType"); + String keyName = ctx.resolveOptional(props, "KeyName"); + + // An instance may reference a LaunchTemplate for its config; fields the + // properties don't set resolve from the template's data, as on AWS. + if (props != null && props.has("LaunchTemplate")) { + JsonNode ltRef = engine.resolveNode(props.get("LaunchTemplate")); + try { + LaunchTemplateData ltData = ec2Service.resolveLaunchTemplateData(region, + ltRef.path("LaunchTemplateId").asText(null), + ltRef.path("LaunchTemplateName").asText(null), + ltRef.path("Version").asText(null)); + if (imageId == null || imageId.isBlank()) { + imageId = ltData.getImageId(); + } + if (instanceType == null || instanceType.isBlank()) { + instanceType = ltData.getInstanceType(); + } + if (keyName == null || keyName.isBlank()) { + keyName = ltData.getKeyName(); + } + } catch (Exception e) { + LOG.debugv("Could not resolve launch template for instance {0}: {1}", + r.getLogicalId(), e.getMessage()); + } + } + if (instanceType == null || instanceType.isBlank()) { + instanceType = "t3.micro"; + } + String subnetId = ctx.resolveOptional(props, "SubnetId"); + String userData = ctx.resolveOptional(props, "UserData"); + String iamInstanceProfile = ctx.resolveOptional(props, "IamInstanceProfile"); + + List securityGroupIds = new ArrayList<>(); + if (props != null && props.has("SecurityGroupIds") && props.get("SecurityGroupIds").isArray()) { + for (JsonNode sg : props.get("SecurityGroupIds")) { + securityGroupIds.add(engine.resolve(sg)); + } + } + + List tags = new ArrayList<>(); + JsonNode tagsNode = props != null ? engine.resolveNode(props.get("Tags")) : null; + if (tagsNode != null && tagsNode.isArray()) { + for (JsonNode tag : tagsNode) { + String key = engine.resolve(tag.path("Key")); + if (!key.isEmpty()) { + tags.add(new Tag(key, engine.resolve(tag.path("Value")))); + } + } + } + + // The launch-time public-IP override rides on the primary network + // interface spec; absent means the subnet's MapPublicIpOnLaunch default. + Boolean associatePublicIp = null; + if (props != null) { + JsonNode networkInterfaces = props.path("NetworkInterfaces"); + if (networkInterfaces.isArray() && !networkInterfaces.isEmpty()) { + String assocRaw = engine.resolve(networkInterfaces.get(0).path("AssociatePublicIpAddress")); + if (assocRaw != null && !assocRaw.isBlank()) { + associatePublicIp = Boolean.parseBoolean(assocRaw); + } + } + } + + Reservation reservation = ec2Service.runInstances(region, imageId, instanceType, 1, 1, keyName, + securityGroupIds, subnetId, null, tags, userData, iamInstanceProfile, + associatePublicIp); + Instance instance = reservation.getInstances().get(0); + r.setPhysicalId(instance.getInstanceId()); + r.getAttributes().put("InstanceId", instance.getInstanceId()); + r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true"); + ec2Service.awaitContainerLaunch(instance); + r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR); + if (instance.getPrivateIpAddress() != null) { + r.getAttributes().put("PrivateIp", instance.getPrivateIpAddress()); + } + if (instance.getPublicIpAddress() != null) { + r.getAttributes().put("PublicIp", instance.getPublicIpAddress()); + } + if (instance.getPrivateDnsName() != null) { + r.getAttributes().put("PrivateDnsName", instance.getPrivateDnsName()); + } + if (instance.getPublicDnsName() != null) { + r.getAttributes().put("PublicDnsName", instance.getPublicDnsName()); + } + if (instance.getPlacement() != null && instance.getPlacement().getAvailabilityZone() != null) { + r.getAttributes().put("AvailabilityZone", instance.getPlacement().getAvailabilityZone()); + } + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + ec2Service.terminateInstances(region, List.of(physicalId)); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java new file mode 100644 index 0000000000..2060b11ff2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java @@ -0,0 +1,224 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.IpPermission; +import io.github.hectorvent.floci.services.ec2.model.IpRange; +import io.github.hectorvent.floci.services.ec2.model.Ipv6Range; +import io.github.hectorvent.floci.services.ec2.model.PrefixListId; +import io.github.hectorvent.floci.services.ec2.model.SecurityGroup; +import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +/** + * CloudFormation provisioning for {@code AWS::EC2::SecurityGroup}. It delegates to + * {@link Ec2Service} so the group really exists (describe-security-groups, ELBv2 and instance + * launches resolve it), and sets the physical id to the real group id so Ref and exports resolve to + * a real {@code sg-} id rather than a stub. + * + *

The inline {@code SecurityGroupIngress}/{@code SecurityGroupEgress} properties share their + * rule-object mapping with the standalone rule resources, through + * {@link Ec2SecurityGroupRuleCfnProvisioner#toIpPermission}. + */ +@ApplicationScoped +public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner { + + private static final Logger LOG = Logger.getLogger(Ec2SecurityGroupCfnProvisioner.class); + + private static final String SECURITY_GROUP = "AWS::EC2::SecurityGroup"; + + private final Ec2Service ec2Service; + + @Inject + public Ec2SecurityGroupCfnProvisioner(Ec2Service ec2Service) { + this.ec2Service = ec2Service; + } + + @Override + public Set resourceTypes() { + return Set.of(SECURITY_GROUP); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + CloudFormationTemplateEngine engine = ctx.engine(); + String region = ctx.region(); + String groupName = ctx.resolveOptional(props, "GroupName"); + if (groupName == null || groupName.isBlank()) { + groupName = ctx.generatePhysicalName(r.getLogicalId(), 255, false); + } + String description = ctx.resolveOptional(props, "GroupDescription"); + if (description == null || description.isBlank()) { + description = "Managed by CloudFormation"; + } + String vpcId = ctx.resolveOptional(props, "VpcId"); + // provision() re-runs for every resource on every update. Re-creating an unchanged group + // would mint a new group id (and collide on the name whenever the VPC id is stable), so + // reuse the group this resource already points at. + SecurityGroup reconciled = existingSecurityGroupToReconcile(ctx.priorPhysicalId(), groupName, description, + vpcId, region); + final SecurityGroup sg = reconciled != null + ? reconciled + : ec2Service.createSecurityGroup(region, groupName, description, vpcId); + // Ref on AWS::EC2::SecurityGroup returns the group id for VPC security groups. + r.setPhysicalId(sg.getGroupId()); + r.getAttributes().put("GroupId", sg.getGroupId()); + if (sg.getVpcId() != null) { + r.getAttributes().put("VpcId", sg.getVpcId()); + } + + // Inline rule properties: previously dropped, leaving the group empty. The mapping is + // shared with the standalone SecurityGroupIngress/Egress resource types, which live in + // Ec2SecurityGroupRuleCfnProvisioner. + // Authorize appends without a duplicate check, so re-running this on a reused group would + // stack another copy of every inline rule on each update. Only authorize what the group + // does not already carry. + // + // Deliberately additive: a rule dropped from the template is not revoked here. Revoking + // the difference would mean revoking permissions this resource cannot prove it owns - a + // group can also carry rules from standalone AWS::EC2::SecurityGroupIngress/Egress + // resources, and clearing them on an unrelated update would close ports another stack + // resource is responsible for. Removing a rule the template no longer declares needs the + // provisioner to record what it authorized; noted as a follow-up. + UnaryOperator peerGroupId = peerGroupIdResolver(region, sg.getVpcId()); + if (props != null && props.has("SecurityGroupIngress")) { + authorizeMissing(props.get("SecurityGroupIngress"), sg.getIpPermissions(), engine, peerGroupId, + perms -> ec2Service.authorizeSecurityGroupIngress(region, sg.getGroupId(), perms)); + } + if (props != null && props.has("SecurityGroupEgress")) { + authorizeMissing(props.get("SecurityGroupEgress"), sg.getIpPermissionsEgress(), engine, peerGroupId, + perms -> ec2Service.authorizeSecurityGroupEgress(region, sg.getGroupId(), perms)); + } + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + ec2Service.deleteSecurityGroup(region, physicalId); + } + + /** The VPC a security group would land in for this template value: the default when omitted. */ + private String effectiveVpcId(String vpcId, String region) { + return vpcId != null && !vpcId.isEmpty() ? vpcId : String.valueOf(ec2Service.resolveDefaultVpcId(region)); + } + + /** + * Authorizes each declared rule that the group does not already carry, one call per rule so a + * rejected rule cannot take its siblings down with it. + */ + private void authorizeMissing(JsonNode declared, List existing, + CloudFormationTemplateEngine engine, + UnaryOperator peerGroupId, + Consumer> authorize) { + Set present = existing.stream() + .map(p -> permissionKey(p, peerGroupId)) + .collect(Collectors.toSet()); + for (JsonNode rule : declared) { + IpPermission perm = Ec2SecurityGroupRuleCfnProvisioner.toIpPermission(rule, engine); + if (present.add(permissionKey(perm, peerGroupId))) { + authorize.accept(List.of(perm)); + } + } + } + + /** + * Resolves a peer group's name to its id, the same lookup {@code Ec2Service} performs when it + * stores an authorized rule. Group names are unique per VPC rather than per region, so the + * search is confined to the group being authorized. A name matching nothing there stays a + * name, which is also what the service does. + */ + private UnaryOperator peerGroupIdResolver(String region, String vpcId) { + return groupName -> ec2Service.describeSecurityGroups(region, List.of(), List.of(groupName), Map.of()) + .stream() + .filter(peer -> Objects.equals(vpcId, peer.getVpcId())) + .map(SecurityGroup::getGroupId) + .filter(Objects::nonNull) + .findFirst() + .orElse(groupName); + } + + /** + * Identity of a permission for duplicate detection. {@link IpPermission} and the range types + * it holds define no {@code equals}, so compare a canonical rendering instead. Descriptions + * are left out: AWS treats a rule differing only by description as the same rule. + */ + private static String permissionKey(IpPermission p, UnaryOperator peerGroupId) { + return String.join("|", + String.valueOf(p.getIpProtocol()), + String.valueOf(p.getFromPort()), + String.valueOf(p.getToPort()), + p.getIpRanges().stream().map(IpRange::getCidrIp).filter(Objects::nonNull).sorted() + .collect(Collectors.joining(",")), + p.getIpv6Ranges().stream().map(Ipv6Range::getCidrIpv6).filter(Objects::nonNull).sorted() + .collect(Collectors.joining(",")), + p.getUserIdGroupPairs().stream() + .map(g -> peerIdentity(g, peerGroupId)) + .filter(Objects::nonNull).sorted() + .collect(Collectors.joining(",")), + p.getPrefixListIds().stream().map(PrefixListId::getPrefixListId) + .filter(Objects::nonNull).sorted() + .collect(Collectors.joining(","))); + } + + /** + * How a peer group is identified when two permissions are compared: its id whenever one can be + * had. A stored pair already carries one, because authorize resolves the name as it records the + * rule, while a pair straight from the template carries only the name it was declared with. + * Keying a resolved id against an unresolved name never matches, which re-authorized a rule + * naming its peer through {@code SourceSecurityGroupName} on every single update. + */ + private static String peerIdentity(UserIdGroupPair pair, UnaryOperator peerGroupId) { + if (pair.getGroupId() != null) { + return pair.getGroupId(); + } + return pair.getGroupName() == null ? null : peerGroupId.apply(pair.getGroupName()); + } + + /** + * The security group this stack resource already points at, when an UpdateStack re-invocation + * left it unchanged. Unlike most resources the physical id here is the group id, not + * the name, so the rename check compares the stored group's name against the template's. + * + *

Returns {@code null} for a fresh create, a group deleted out of band, or any change AWS + * treats as a replacement: GroupName, GroupDescription and VpcId are all immutable on a + * security group, so a template that changes one wants a new group, not an edit to this one. + * The caller then creates. + */ + private SecurityGroup existingSecurityGroupToReconcile(String priorPhysicalId, String groupName, + String description, String vpcId, String region) { + if (priorPhysicalId == null || priorPhysicalId.isBlank()) { + return null; + } + try { + return ec2Service.describeSecurityGroups(region, List.of(priorPhysicalId), List.of(), Map.of()) + .stream() + .filter(existing -> groupName == null || groupName.equals(existing.getGroupName())) + .filter(existing -> description == null || description.equals(existing.getDescription())) + // Compare the VpcId the template would actually get, not the raw property. + // createSecurityGroup resolves an omitted VpcId to the region's default VPC, + // so the stored group always has one: comparing against a null property would + // either force a replacement on every update, or - the bug - let a template + // that drops VpcId keep a group sitting in the explicit VPC it named before. + .filter(existing -> effectiveVpcId(vpcId, region).equals(existing.getVpcId())) + .findFirst() + .orElse(null); + } catch (AwsException notFound) { + // Expected when the group was deleted out of band since the prior update. + LOG.debugv(notFound, "No existing security group {0} found on file, falling back to create", + priorPhysicalId); + return null; + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupRuleCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupRuleCfnProvisioner.java index 5fe804f66f..d53dc556a0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupRuleCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupRuleCfnProvisioner.java @@ -26,9 +26,8 @@ import java.util.stream.Stream; *

The rule-object to {@link IpPermission} mapping lives here as * {@link #toIpPermission(JsonNode, CloudFormationTemplateEngine)} because the inline * {@code SecurityGroupIngress}/{@code SecurityGroupEgress} properties of - * {@code AWS::EC2::SecurityGroup} take the same shape. That arm is still in - * {@code CloudFormationResourceProvisioner} and calls this method, so there is one mapping rather - * than two; it moves here when the security-group arm itself is extracted. + * {@code AWS::EC2::SecurityGroup} take the same shape. {@link Ec2SecurityGroupCfnProvisioner} + * provisions the group and calls this method, so there is one mapping rather than two. */ @ApplicationScoped public class Ec2SecurityGroupRuleCfnProvisioner implements CfnResourceProvisioner { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index 8c0cd8688f..1e30d355d3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFron import io.github.hectorvent.floci.services.cloudformation.provisioners.ConfigCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.DynamoDbCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2FlowLogCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2InstanceCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaMicrovmsCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.OrganizationsCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.StepFunctionsCfnProvisioner; @@ -47,6 +48,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoCf import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2LaunchTemplateCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkAclCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2SecurityGroupCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2SecurityGroupRuleCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2VpcCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2VpcEndpointCfnProvisioner; @@ -363,7 +365,9 @@ final class CfnProvisionerFixture { discovered.add(new Ec2VpcEndpointCfnProvisioner(ec2Service)); discovered.add(new Ec2VpcGatewayAttachmentCfnProvisioner(ec2Service)); discovered.add(new Ec2NetworkAclCfnProvisioner(ec2Service)); + discovered.add(new Ec2SecurityGroupCfnProvisioner(ec2Service)); discovered.add(new Ec2SecurityGroupRuleCfnProvisioner(ec2Service)); + discovered.add(new Ec2InstanceCfnProvisioner(ec2Service)); discovered.add(new Ec2LaunchTemplateCfnProvisioner(ec2Service)); discovered.add(new Ec2NetworkCfnProvisioner(ec2Service)); } @@ -684,7 +688,6 @@ final class CfnProvisionerFixture { objectMapper, customResourceResponseStore, reachableEndpoint, - ec2Service, eksService, resourceRegistry, dynamicReferences, diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java new file mode 100644 index 0000000000..b2e2fe530e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java @@ -0,0 +1,133 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData; +import io.github.hectorvent.floci.services.ec2.model.Placement; +import io.github.hectorvent.floci.services.ec2.model.Reservation; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * {@code AWS::EC2::Instance} in isolation: the attributes Ref and Fn::GetAtt read once the launch + * completes, launch-template fields filling what the properties leave unset, and the delete. + * The launch-failure and rollback-marker paths are covered through the dispatcher by + * {@code CloudFormationEc2ProvisionerTest}. + */ +class Ec2InstanceCfnProvisionerTest { + + private static final String TYPE = "AWS::EC2::Instance"; + + private final Ec2Service ec2 = mock(Ec2Service.class); + private final Ec2InstanceCfnProvisioner provisioner = new Ec2InstanceCfnProvisioner(ec2); + private final ObjectMapper mapper = new ObjectMapper(); + + @Test + void launchPublishesTheInstanceAttributes() throws Exception { + Instance instance = new Instance(); + instance.setInstanceId("i-1"); + instance.setPrivateIpAddress("10.0.0.5"); + instance.setPublicIpAddress("54.0.0.5"); + instance.setPrivateDnsName("ip-10-0-0-5.ec2.internal"); + instance.setPublicDnsName("ec2-54-0-0-5.compute-1.amazonaws.com"); + instance.setPlacement(new Placement("us-east-1a")); + stubLaunch(instance); + StackResource r = resource("Server"); + + provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"), ctx()); + + assertEquals("i-1", r.getPhysicalId()); + assertEquals(Set.of("InstanceId", "PrivateIp", "PublicIp", "PrivateDnsName", "PublicDnsName", + "AvailabilityZone"), r.getAttributes().keySet()); + assertEquals("10.0.0.5", r.getAttributes().get("PrivateIp")); + assertEquals("us-east-1a", r.getAttributes().get("AvailabilityZone")); + verify(ec2).awaitContainerLaunch(instance); + } + + @Test + void launchTemplateFillsWhatThePropertiesLeaveUnset() throws Exception { + LaunchTemplateData data = new LaunchTemplateData(); + data.setImageId("ami-from-template"); + data.setInstanceType("m5.large"); + data.setKeyName("template-key"); + when(ec2.resolveLaunchTemplateData("us-east-1", "lt-1", null, "1")).thenReturn(data); + Instance instance = new Instance(); + instance.setInstanceId("i-2"); + stubLaunch(instance); + + provisioner.provision(resource("Server"), props(""" + {"LaunchTemplate": {"LaunchTemplateId": "lt-1", "Version": "1"}} + """), ctx()); + + verify(ec2).runInstances(eq("us-east-1"), eq("ami-from-template"), eq("m5.large"), eq(1), eq(1), + eq("template-key"), anyList(), any(), any(), anyList(), any(), any(), any()); + } + + @Test + void provisionsAnInstanceDeclaredWithNoProperties() { + Instance instance = new Instance(); + instance.setInstanceId("i-3"); + stubLaunch(instance); + StackResource r = resource("Server"); + + // A bare {"Type": "AWS::EC2::Instance"} has no Properties, so props is null. The registry + // schema lists no required properties, so this is a valid template. + provisioner.provision(r, null, ctx()); + + assertEquals("i-3", r.getPhysicalId()); + assertEquals("i-3", r.getAttributes().get("InstanceId")); + } + + @Test + void deleteTerminatesTheInstance() { + provisioner.delete(TYPE, "i-1", "us-east-1"); + + verify(ec2).terminateInstances("us-east-1", List.of("i-1")); + } + + private void stubLaunch(Instance instance) { + Reservation reservation = new Reservation(); + reservation.getInstances().add(instance); + when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(), + any(), any(), anyList(), any(), any(), any())).thenReturn(reservation); + } + + private ProvisionContext ctx() { + 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)); + return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack"); + } + + private JsonNode props(String json) throws Exception { + return mapper.readTree(json); + } + + private static StackResource resource(String logicalId) { + StackResource r = new StackResource(); + r.setLogicalId(logicalId); + r.setResourceType(TYPE); + r.setAttributes(new HashMap<>()); + return r; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisionerTest.java new file mode 100644 index 0000000000..61a0fea456 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisionerTest.java @@ -0,0 +1,160 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.IpPermission; +import io.github.hectorvent.floci.services.ec2.model.IpRange; +import io.github.hectorvent.floci.services.ec2.model.SecurityGroup; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * {@code AWS::EC2::SecurityGroup} in isolation: the attributes Ref and Fn::GetAtt read, the + * generated name, reuse of the prior group on update, and the duplicate check that keeps an update + * from stacking another copy of every inline rule. + */ +class Ec2SecurityGroupCfnProvisionerTest { + + private static final String TYPE = "AWS::EC2::SecurityGroup"; + + private final Ec2Service ec2 = mock(Ec2Service.class); + private final Ec2SecurityGroupCfnProvisioner provisioner = new Ec2SecurityGroupCfnProvisioner(ec2); + private final ObjectMapper mapper = new ObjectMapper(); + + @Test + void createPublishesGroupIdAndVpcIdOnly() throws Exception { + when(ec2.createSecurityGroup("us-east-1", "web", "web tier", "vpc-1")) + .thenReturn(group("sg-1", "web", "web tier", "vpc-1")); + StackResource r = resource("WebSg"); + + provisioner.provision(r, props(""" + {"GroupName": "web", "GroupDescription": "web tier", "VpcId": "vpc-1"} + """), ctx(null)); + + assertEquals("sg-1", r.getPhysicalId()); + assertEquals(Set.of("GroupId", "VpcId"), r.getAttributes().keySet()); + assertEquals("sg-1", r.getAttributes().get("GroupId")); + assertEquals("vpc-1", r.getAttributes().get("VpcId")); + } + + @Test + void absentGroupNameIsGeneratedFromStackAndLogicalId() throws Exception { + when(ec2.createSecurityGroup(eq("us-east-1"), anyString(), anyString(), any())) + .thenReturn(group("sg-2", "generated", "Managed by CloudFormation", "vpc-default")); + StackResource r = resource("WebSg"); + + provisioner.provision(r, props("{}"), ctx(null)); + + ArgumentCaptor name = ArgumentCaptor.forClass(String.class); + verify(ec2).createSecurityGroup(eq("us-east-1"), name.capture(), eq("Managed by CloudFormation"), any()); + assertTrue(name.getValue().matches("my-stack-WebSg-[0-9a-f]{12}"), name.getValue()); + } + + @Test + void updateReusesThePriorGroupInsteadOfCreatingAnother() throws Exception { + when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of())) + .thenReturn(List.of(group("sg-1", "web", "web tier", "vpc-1"))); + StackResource r = resource("WebSg"); + r.setPhysicalId("sg-1"); + + provisioner.provision(r, props(""" + {"GroupName": "web", "GroupDescription": "web tier", "VpcId": "vpc-1"} + """), ctx("sg-1")); + + assertEquals("sg-1", r.getPhysicalId()); + verify(ec2, never()).createSecurityGroup(anyString(), anyString(), anyString(), any()); + } + + @Test + void inlineRuleTheGroupAlreadyCarriesIsNotAuthorizedAgain() throws Exception { + SecurityGroup existing = group("sg-1", "web", "web tier", "vpc-1"); + existing.getIpPermissions().add(tcp(80, "0.0.0.0/0")); + when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of())) + .thenReturn(List.of(existing)); + StackResource r = resource("WebSg"); + r.setPhysicalId("sg-1"); + + provisioner.provision(r, props(""" + {"GroupName": "web", "GroupDescription": "web tier", "VpcId": "vpc-1", + "SecurityGroupIngress": [ + {"IpProtocol": "tcp", "FromPort": 80, "ToPort": 80, "CidrIp": "0.0.0.0/0"}, + {"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443, "CidrIp": "0.0.0.0/0"} + ]} + """), ctx("sg-1")); + + @SuppressWarnings("unchecked") + ArgumentCaptor> authorized = ArgumentCaptor.forClass(List.class); + verify(ec2).authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), authorized.capture()); + assertEquals(1, authorized.getAllValues().size()); + assertEquals(443, authorized.getValue().get(0).getFromPort()); + verify(ec2, never()).authorizeSecurityGroupEgress(anyString(), anyString(), anyList()); + } + + @Test + void deleteDeletesTheGroup() { + provisioner.delete(TYPE, "sg-1", "us-east-1"); + + verify(ec2).deleteSecurityGroup("us-east-1", "sg-1"); + } + + private ProvisionContext ctx(String priorPhysicalId) { + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null ? null : node.asText(); + }); + return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId); + } + + private JsonNode props(String json) throws Exception { + return mapper.readTree(json); + } + + private static StackResource resource(String logicalId) { + StackResource r = new StackResource(); + r.setLogicalId(logicalId); + r.setResourceType(TYPE); + r.setAttributes(new HashMap<>()); + return r; + } + + private static SecurityGroup group(String id, String name, String description, String vpcId) { + SecurityGroup group = new SecurityGroup(); + group.setGroupId(id); + group.setGroupName(name); + group.setDescription(description); + group.setVpcId(vpcId); + group.setIpPermissions(new ArrayList<>()); + group.setIpPermissionsEgress(new ArrayList<>()); + return group; + } + + private static IpPermission tcp(int port, String cidr) { + IpPermission permission = new IpPermission(); + permission.setIpProtocol("tcp"); + permission.setFromPort(port); + permission.setToPort(port); + permission.setIpRanges(new ArrayList<>(List.of(new IpRange(cidr)))); + return permission; + } +} diff --git a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv index 124d6ae7cf..d73318b74c 100644 --- a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv +++ b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv @@ -3,10 +3,13 @@ AWS::CertificateManager::Certificate Id schema gives no description; Ref returns AWS::CodeBuild::Project Id schema gives no description; AWS's Id may differ from the project name Floci uses AWS::CodePipeline::CustomActionType Id schema gives no description; the custom action has no separate id in Floci AWS::CodePipeline::Webhook Id schema gives no description; Floci keys webhooks by name +AWS::EC2::Instance State not published yet: Floci tracks the instance state, setting it is a separate change to what Fn::GetAtt returns +AWS::EC2::Instance VpcId not published yet: the instance's VPC comes from its subnet, setting it is a separate change to what Fn::GetAtt returns AWS::EC2::NatGateway AutoProvisionZones availability-mode NAT gateways are not emulated AWS::EC2::NatGateway AutoScalingIps availability-mode NAT gateways are not emulated AWS::EC2::NatGateway EniId the NAT gateway's network interface is not created AWS::EC2::NatGateway RouteTableId availability-mode NAT gateways are not emulated +AWS::EC2::SecurityGroup Id not published yet: the group id is already published as GroupId, adding Id is a separate change to what Fn::GetAtt returns AWS::EC2::Subnet BlockPublicAccessStates VPC block public access is not emulated AWS::EC2::Subnet Ipv6CidrBlocks IPv6 CIDR association is not emulated AWS::EC2::Subnet NetworkAclAssociationId the subnet's default network ACL association is not created with the subnet diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index f893ec6940..fed582cbe0 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -54,7 +54,7 @@ AWS::DynamoDB::GlobalTable DynamoDbCfnProvisioner AWS::DynamoDB::Table DynamoDbCfnProvisioner AWS::EC2::EIP Ec2NetworkCfnProvisioner AWS::EC2::FlowLog Ec2FlowLogCfnProvisioner -AWS::EC2::Instance LEGACY_SWITCH +AWS::EC2::Instance Ec2InstanceCfnProvisioner AWS::EC2::InternetGateway Ec2NetworkCfnProvisioner AWS::EC2::LaunchTemplate Ec2LaunchTemplateCfnProvisioner AWS::EC2::NatGateway Ec2NetworkCfnProvisioner @@ -62,7 +62,7 @@ AWS::EC2::NetworkAcl Ec2NetworkAclCfnProvisioner AWS::EC2::NetworkAclEntry Ec2NetworkAclCfnProvisioner AWS::EC2::Route Ec2NetworkCfnProvisioner AWS::EC2::RouteTable Ec2NetworkCfnProvisioner -AWS::EC2::SecurityGroup LEGACY_SWITCH +AWS::EC2::SecurityGroup Ec2SecurityGroupCfnProvisioner AWS::EC2::SecurityGroupEgress Ec2SecurityGroupRuleCfnProvisioner AWS::EC2::SecurityGroupIngress Ec2SecurityGroupRuleCfnProvisioner AWS::EC2::Subnet Ec2NetworkCfnProvisioner