mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): roll back an AWS::EC2::SecurityGroup updated in place (#7562)
This commit is contained in:
1 parent
31227106b1
commit
d280f451fa
6 files changed
+558
-32
No files matched your search
+133
@@ -0,0 +1,133 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.testing.AwsTestClients;
|
||||
import io.github.hectorvent.floci.testing.CfnStackWaits;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ec2.model.SecurityGroup;
|
||||
import software.amazon.awssdk.services.ec2.model.Tag;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* A stack update that changes an {@code AWS::EC2::SecurityGroup} in place and then fails on a later
|
||||
* resource rolls the group back through the AWS SDK: its inline rules and the tag keys the stack
|
||||
* owns are the first deployment's again, a tag added through EC2 is kept, and a following update
|
||||
* still reconciles from that first deployment.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationSecurityGroupUpdateRollbackIntegrationTest {
|
||||
|
||||
private static final String ORIGINAL = """
|
||||
"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"}
|
||||
],
|
||||
"Tags": [{"Key": "team", "Value": "core"}]""";
|
||||
|
||||
private static final String CHANGED = """
|
||||
"SecurityGroupIngress": [
|
||||
{"IpProtocol": "tcp", "FromPort": 80, "ToPort": 80, "CidrIp": "0.0.0.0/0"},
|
||||
{"IpProtocol": "tcp", "FromPort": 8080, "ToPort": 8080, "CidrIp": "0.0.0.0/0"}
|
||||
],
|
||||
"Tags": [{"Key": "owner", "Value": "platform"}]""";
|
||||
|
||||
private final String stackName = "cfn-sg-rollback-" + UUID.randomUUID();
|
||||
private CloudFormationClient cfn;
|
||||
private Ec2Client ec2;
|
||||
private boolean stackCreated;
|
||||
|
||||
@BeforeEach
|
||||
void clients() {
|
||||
cfn = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1);
|
||||
ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void deleteStack() {
|
||||
try {
|
||||
if (stackCreated) {
|
||||
cfn.deleteStack(request -> request.stackName(stackName));
|
||||
}
|
||||
} finally {
|
||||
ec2.close();
|
||||
cfn.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedUpdatePutsTheRulesAndTheOwnedTagsBack() {
|
||||
cfn.createStack(request -> request.stackName(stackName).templateBody(template(ORIGINAL, "")));
|
||||
stackCreated = true;
|
||||
String groupId = CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE").outputs().getFirst()
|
||||
.outputValue();
|
||||
ec2.createTags(request -> request.resources(groupId)
|
||||
.tags(Tag.builder().key("external").value("preserve").build()));
|
||||
|
||||
cfn.updateStack(request -> request.stackName(stackName).templateBody(template(CHANGED, failingResource())));
|
||||
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
assertEquals(Set.of(80, 443), ingressPorts(groupId));
|
||||
assertEquals(Map.of("team", "core", "external", "preserve"), tags(groupId));
|
||||
|
||||
// The rollback put the first deployment's records back too, so dropping the rules and tags
|
||||
// now removes exactly what that deployment wrote.
|
||||
cfn.updateStack(request -> request.stackName(stackName).templateBody(template("\"Tags\": []", "")));
|
||||
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE");
|
||||
assertEquals(Set.of(), ingressPorts(groupId));
|
||||
assertEquals(Map.of("external", "preserve"), tags(groupId));
|
||||
}
|
||||
|
||||
private String template(String groupProperties, String moreResources) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Group": {"Type": "AWS::EC2::SecurityGroup", "Properties": {
|
||||
"GroupDescription": "rollback",
|
||||
%s
|
||||
}}%s
|
||||
},
|
||||
"Outputs": {"GroupId": {"Value": {"Ref": "Group"}}}
|
||||
}
|
||||
""".formatted(groupProperties, moreResources);
|
||||
}
|
||||
|
||||
/** A resource that fails after the group, so the update rolls back. */
|
||||
private String failingResource() {
|
||||
return """
|
||||
,
|
||||
"BadSecret": {
|
||||
"Type": "AWS::SecretsManager::Secret",
|
||||
"DependsOn": "Group",
|
||||
"Properties": {
|
||||
"Name": "%s",
|
||||
"SecretString": "explicit",
|
||||
"GenerateSecretString": {"PasswordLength": 32}
|
||||
}
|
||||
}""".formatted(stackName);
|
||||
}
|
||||
|
||||
private Set<Integer> ingressPorts(String groupId) {
|
||||
SecurityGroup group = ec2.describeSecurityGroups(request -> request.groupIds(groupId)).securityGroups()
|
||||
.getFirst();
|
||||
return group.ipPermissions().stream().map(permission -> permission.fromPort()).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private Map<String, String> tags(String groupId) {
|
||||
Map<String, String> tags = new TreeMap<>();
|
||||
ec2.describeTags(request -> request.filters(filter -> filter.name("resource-id").values(groupId)))
|
||||
.tags().forEach(tag -> tags.put(tag.key(), tag.value()));
|
||||
return tags;
|
||||
}
|
||||
}
|
||||
+196
@@ -12,24 +12,29 @@ import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.ArgumentMatcher;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
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.assertThrows;
|
||||
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.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -336,6 +341,197 @@ class Ec2SecurityGroupCfnProvisionerTest {
|
||||
assertEquals(443, revoked.getValue().get(0).getFromPort());
|
||||
}
|
||||
|
||||
private static final String WEB_80_443 = """
|
||||
{"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"}
|
||||
],
|
||||
"Tags": [{"Key": "team", "Value": "core"}]}
|
||||
""";
|
||||
|
||||
private static final String WEB_80_8080 = """
|
||||
{"GroupName": "web", "GroupDescription": "web tier", "VpcId": "vpc-1",
|
||||
"SecurityGroupIngress": [
|
||||
{"IpProtocol": "tcp", "FromPort": 80, "ToPort": 80, "CidrIp": "0.0.0.0/0"},
|
||||
{"IpProtocol": "tcp", "FromPort": 8080, "ToPort": 8080, "CidrIp": "0.0.0.0/0"}
|
||||
],
|
||||
"Tags": [{"Key": "owner", "Value": "platform"}]}
|
||||
""";
|
||||
|
||||
/** A group the first deployment created from {@link #WEB_80_443}, its rule and tag records in place. */
|
||||
private StackResource createdWeb() 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(WEB_80_443), ctx(null));
|
||||
r.setPhysicalId("sg-1");
|
||||
return r;
|
||||
}
|
||||
|
||||
/** The group as the first deployment left it, with a port 22 rule a standalone resource added. */
|
||||
private static SecurityGroup webBeforeUpdate() {
|
||||
SecurityGroup group = group("sg-1", "web", "web tier", "vpc-1");
|
||||
group.getIpPermissions().add(tcp(80, "0.0.0.0/0"));
|
||||
group.getIpPermissions().add(tcp(443, "0.0.0.0/0"));
|
||||
group.getIpPermissions().add(tcp(22, "10.0.0.0/8"));
|
||||
return group;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRolledBackUpdatePutsTheRulesTheTagsAndTheRecordsBack() throws Exception {
|
||||
StackResource r = createdWeb();
|
||||
Map<String, String> recordsBefore = new HashMap<>(r.getAttributes());
|
||||
SecurityGroup afterUpdate = group("sg-1", "web", "web tier", "vpc-1");
|
||||
afterUpdate.getIpPermissions().add(tcp(80, "0.0.0.0/0"));
|
||||
afterUpdate.getIpPermissions().add(tcp(8080, "0.0.0.0/0"));
|
||||
afterUpdate.getIpPermissions().add(tcp(22, "10.0.0.0/8"));
|
||||
when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of()))
|
||||
.thenReturn(List.of(webBeforeUpdate()), List.of(afterUpdate));
|
||||
// external was added through EC2, outside the stack, so neither the update nor its rollback touches it.
|
||||
when(ec2.describeTags(eq("us-east-1"), any())).thenReturn(
|
||||
List.of(tagEntry("sg-1", "team", "core"), tagEntry("sg-1", "external", "x")),
|
||||
List.of(tagEntry("sg-1", "team", "core"), tagEntry("sg-1", "external", "x")),
|
||||
List.of(tagEntry("sg-1", "owner", "platform"), tagEntry("sg-1", "external", "x")));
|
||||
|
||||
provisioner.provision(r, props(WEB_80_8080), ctx("sg-1"));
|
||||
verify(ec2).authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), argThat(port(8080)));
|
||||
verify(ec2).revokeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), argThat(port(443)));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
verify(ec2).revokeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), argThat(port(8080)));
|
||||
// 443 the first time, from the create, and again from the rollback.
|
||||
verify(ec2, times(2)).authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), argThat(port(443)));
|
||||
verify(ec2).deleteTags(eq("us-east-1"), eq(List.of("sg-1")), argThat(tags("owner")));
|
||||
verify(ec2, times(2)).createTags(eq("us-east-1"), eq(List.of("sg-1")), argThat(tags("team")));
|
||||
verify(ec2, never()).deleteTags(anyString(), anyList(), argThat(tags("external")));
|
||||
assertEquals(recordsBefore, r.getAttributes(), "the rule and tag records are the first deployment's again");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRollbackDoesNotAuthorizeARuleTheGroupStillCarries() throws Exception {
|
||||
StackResource r = createdWeb();
|
||||
// The update's revoke never took effect, so 443 is still there when the rollback runs.
|
||||
when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of()))
|
||||
.thenReturn(List.of(webBeforeUpdate()));
|
||||
when(ec2.describeTags(eq("us-east-1"), any())).thenReturn(List.of(tagEntry("sg-1", "team", "core")));
|
||||
provisioner.provision(r, props(WEB_80_8080), ctx("sg-1"));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
verify(ec2, times(1)).authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), argThat(port(443)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSourceAPermissionOutsideTheStackAlreadyHoldsIsNeitherAuthorizedNorRolledBack() throws Exception {
|
||||
StackResource r = resource("WebSg");
|
||||
r.setPhysicalId("sg-1");
|
||||
// One permission holding two sources, as an AuthorizeSecurityGroupIngress outside the stack
|
||||
// can leave it; the template declares one of them.
|
||||
SecurityGroup group = group("sg-1", "web", "web tier", "vpc-1");
|
||||
IpPermission external = tcp(80, "0.0.0.0/0");
|
||||
external.getIpRanges().add(new IpRange("10.0.0.0/8"));
|
||||
group.getIpPermissions().add(external);
|
||||
when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of())).thenReturn(List.of(group));
|
||||
|
||||
provisioner.provision(r, props(WEB_80_8080), ctx("sg-1"));
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
verify(ec2, never()).authorizeSecurityGroupIngress(anyString(), anyString(), argThat(port(80)));
|
||||
// A revoke of 80 would take 0.0.0.0/0 out of the permission that held it before the update.
|
||||
verify(ec2, never()).revokeSecurityGroupIngress(anyString(), anyString(), argThat(port(80)));
|
||||
verify(ec2).revokeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), argThat(port(8080)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRollbackPutsBackATagThatHadNoValue() throws Exception {
|
||||
StackResource r = resource("WebSg");
|
||||
r.setPhysicalId("sg-1");
|
||||
r.getAttributes().put(Ec2SecurityGroupCfnProvisioner.TAG_KEYS_ATTR, "[\"owner\"]");
|
||||
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")));
|
||||
when(ec2.describeTags(eq("us-east-1"), any())).thenReturn(
|
||||
List.of(tagEntry("sg-1", "owner", null)),
|
||||
List.of(tagEntry("sg-1", "owner", null)),
|
||||
List.of(tagEntry("sg-1", "owner", "platform")));
|
||||
|
||||
provisioner.provision(r, props(WEB_80_8080), ctx("sg-1"));
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
verify(ec2).createTags(eq("us-east-1"), eq(List.of("sg-1")), argThat(actual -> actual.size() == 1
|
||||
&& "owner".equals(actual.getFirst().getKey()) && actual.getFirst().getValue() == null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedStepPutsAReusedGroupBackBeforeTheFailurePropagates() throws Exception {
|
||||
StackResource r = createdWeb();
|
||||
when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of()))
|
||||
.thenReturn(List.of(webBeforeUpdate()));
|
||||
when(ec2.describeTags(eq("us-east-1"), any())).thenReturn(List.of(tagEntry("sg-1", "team", "core")));
|
||||
doThrow(new AwsException("InternalError", "ec2 is down", 500))
|
||||
.when(ec2).createTags(eq("us-east-1"), eq(List.of("sg-1")), argThat(tags("owner")));
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(r, props(WEB_80_8080), ctx("sg-1")));
|
||||
|
||||
verify(ec2).revokeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), argThat(port(8080)));
|
||||
assertFalse(r.getAttributes().containsKey(Ec2SecurityGroupCfnProvisioner.UPDATE_SNAPSHOT_ATTR));
|
||||
verify(ec2, never()).deleteSecurityGroup(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedTagWriteOnANewGroupDeletesIt() throws Exception {
|
||||
when(ec2.createSecurityGroup("us-east-1", "web", "web tier", "vpc-1"))
|
||||
.thenReturn(group("sg-1", "web", "web tier", "vpc-1"));
|
||||
doThrow(new AwsException("InternalError", "ec2 is down", 500))
|
||||
.when(ec2).createTags(anyString(), anyList(), anyList());
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(resource("WebSg"), props(WEB_80_443), ctx(null)));
|
||||
|
||||
verify(ec2).deleteSecurityGroup("us-east-1", "sg-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReplacedGroupIsNotReportedAsRolledBack() throws Exception {
|
||||
StackResource r = createdWeb();
|
||||
when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of()))
|
||||
.thenReturn(List.of(webBeforeUpdate()));
|
||||
when(ec2.createSecurityGroup("us-east-1", "web", "new description", "vpc-1"))
|
||||
.thenReturn(group("sg-2", "web", "new description", "vpc-1"));
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{"GroupName": "web", "GroupDescription": "new description", "VpcId": "vpc-1"}
|
||||
"""), ctx("sg-1"));
|
||||
|
||||
assertEquals("sg-2", r.getPhysicalId());
|
||||
assertFalse(provisioner.rollbackUpdate(r), "a replacement is not rolled back here");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCommittedOrClearedUpdateDropsTheSnapshot() throws Exception {
|
||||
StackResource r = createdWeb();
|
||||
when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of()))
|
||||
.thenReturn(List.of(webBeforeUpdate()));
|
||||
provisioner.provision(r, props(WEB_80_8080), ctx("sg-1"));
|
||||
assertTrue(r.getAttributes().containsKey(Ec2SecurityGroupCfnProvisioner.UPDATE_SNAPSHOT_ATTR));
|
||||
|
||||
provisioner.completeUpdate(r);
|
||||
assertFalse(r.getAttributes().containsKey(Ec2SecurityGroupCfnProvisioner.UPDATE_SNAPSHOT_ATTR));
|
||||
|
||||
provisioner.provision(r, props(WEB_80_443), ctx("sg-1"));
|
||||
provisioner.clearUpdate(r);
|
||||
assertFalse(r.getAttributes().containsKey(Ec2SecurityGroupCfnProvisioner.UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
private static ArgumentMatcher<List<IpPermission>> port(int port) {
|
||||
return perms -> perms != null && perms.size() == 1 && perms.getFirst().getFromPort() == port;
|
||||
}
|
||||
|
||||
private static ArgumentMatcher<List<Tag>> tags(String... keys) {
|
||||
return actual -> actual != null
|
||||
&& actual.stream().map(Tag::getKey).collect(Collectors.toSet()).equals(Set.of(keys));
|
||||
}
|
||||
|
||||
private static Map<String, String> tagEntry(String resourceId, String key, String value) {
|
||||
Map<String, String> entry = new HashMap<>();
|
||||
entry.put("resourceId", resourceId);
|
||||
|
||||
Reference in new issue
Block a user