mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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.
This commit is contained in:
1 parent
33a95e92f2
commit
180aef5e44
9 files changed
+670
-286
No files matched your search
+4
-1
@@ -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,
|
||||
|
||||
+133
@@ -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;
|
||||
}
|
||||
}
|
||||
+160
@@ -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<String> 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<List<IpPermission>> 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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user