mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): resolve an RDS instance's previous template as it was deployed (#9058)
This commit is contained in:
1 parent
a6a609d62f
commit
3e1fe3c8b6
11 files changed
+190
-61
No files matched your search
+3
-11
@@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.floci.aws.testing.RdsRequests.auroraClusterWithMember;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
@@ -94,18 +95,9 @@ class CloudFormationRdsAssociatedRolesIntegrationTest {
|
||||
void anAuroraMemberCannotCarryItsOwnRoles() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cfn-rds-roles-member-" + suffix;
|
||||
String clusterId = "cfn-roles-member-cluster-" + suffix;
|
||||
try {
|
||||
stack("CreateStack", stackName, """
|
||||
{"Resources": {
|
||||
"Cluster": {"Type": "AWS::RDS::DBCluster", "Properties": {
|
||||
"DBClusterIdentifier": "%s", "Engine": "aurora-postgresql",
|
||||
"MasterUsername": "dbadmin", "MasterUserPassword": "password123"}},
|
||||
"Member": {"Type": "AWS::RDS::DBInstance", "Properties": {
|
||||
"DBClusterIdentifier": {"Ref": "Cluster"}, "Engine": "aurora-postgresql",
|
||||
"DBInstanceClass": "db.r6g.large",
|
||||
"AssociatedRoles": [{"RoleArn": "%s", "FeatureName": "s3Import"}]}}}}
|
||||
""".formatted(clusterId, EXPORT_ROLE));
|
||||
stack("CreateStack", stackName, "{\"Resources\": {%s}}".formatted(auroraClusterWithMember(
|
||||
"\"AssociatedRoles\": [{\"RoleArn\": \"%s\", \"FeatureName\": \"s3Import\"}]".formatted(EXPORT_ROLE))));
|
||||
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);
|
||||
assertTrue(state.status().startsWith("ROLLBACK") || state.status().equals("CREATE_FAILED"),
|
||||
state.status());
|
||||
|
||||
+47
-6
@@ -7,6 +7,8 @@ import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Stack;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.rds.RdsClient;
|
||||
@@ -14,8 +16,10 @@ import software.amazon.awssdk.services.rds.model.DBInstance;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.floci.aws.testing.CfnStackWaits.failedResourceReason;
|
||||
import static io.floci.aws.testing.CfnStackWaits.output;
|
||||
import static io.floci.aws.testing.Ec2Requests.defaultSecurityGroupId;
|
||||
import static io.floci.aws.testing.RdsRequests.auroraClusterWithMember;
|
||||
import static io.floci.aws.testing.RdsRequests.vpcSecurityGroupIds;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -26,7 +30,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
* {@code VPCSecurityGroups} and {@code StorageEncrypted} on {@code AWS::RDS::DBInstance}, read back
|
||||
* through the AWS SDK: the groups follow the template in place, through a failed update, a group of
|
||||
* another VPC that RDS refuses, and a template that drops them, and a change of {@code StorageEncrypted}
|
||||
* either way replaces the instance.
|
||||
* either way replaces the instance. A cluster member's groups are its cluster's, so an update that
|
||||
* changes them fails, even when the template does so only through a parameter or a replaced group.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(RdsMockProfile.class)
|
||||
@@ -80,8 +85,46 @@ class CloudFormationRdsDbInstanceIntegrationTest {
|
||||
assertEquals(List.of(encrypted), stackInstanceIds());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"Second, first, UPDATE_ROLLBACK_COMPLETE", "First, replaced, UPDATE_ROLLBACK_FAILED"})
|
||||
void aMembersGroupsChangedOnlyThroughAParameterOrAReplacedGroupFailTheUpdate(String group, String firstDescription,
|
||||
String status) {
|
||||
String id = output(stack.create(memberTemplate("First", "first")), "MemberId");
|
||||
List<String> groups = vpcSecurityGroupIds(rds(), id);
|
||||
|
||||
// A replaced security group is not rolled back, so that update's rollback fails at First.
|
||||
stack.update(memberTemplate(group, firstDescription), status);
|
||||
String reason = failedResourceReason(stack.name());
|
||||
assertTrue(reason.contains("Modify vpc security group for the DB Cluster"), reason);
|
||||
assertEquals(groups, vpcSecurityGroupIds(rds(), id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Two security groups of the default VPC, a third, Outside, of another VPC, and a DB instance on
|
||||
* The {@link #securityGroups}, First with {@code firstDescription}, which replaces it when it
|
||||
* changes, and an Aurora cluster with a member on the group the parameter {@code Group} names, {@code group}
|
||||
* by default. The member's own properties never change.
|
||||
*/
|
||||
private static String memberTemplate(String group, String firstDescription) {
|
||||
return """
|
||||
{"Parameters": {"Group": {"Type": "String", "Default": "%s"}},
|
||||
"Conditions": {"OnSecond": {"Fn::Equals": [{"Ref": "Group"}, "Second"]}},
|
||||
"Resources": {%s, %s},
|
||||
"Outputs": {"MemberId": {"Value": {"Ref": "Member"}}}}
|
||||
""".formatted(group, securityGroups(firstDescription), auroraClusterWithMember("""
|
||||
"VPCSecurityGroups": [{"Fn::If": ["OnSecond",
|
||||
{"Fn::GetAtt": ["Second", "GroupId"]}, {"Fn::GetAtt": ["First", "GroupId"]}]}]"""));
|
||||
}
|
||||
|
||||
/** Two security groups of the default VPC: First, described as {@code firstDescription}, and Second. */
|
||||
private static String securityGroups(String firstDescription) {
|
||||
return """
|
||||
"First": {"Type": "AWS::EC2::SecurityGroup", "Properties": {"GroupDescription": "%s"}},
|
||||
"Second": {"Type": "AWS::EC2::SecurityGroup", "Properties": {"GroupDescription": "second"}}"""
|
||||
.formatted(firstDescription);
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@link #securityGroups}, a third, Outside, of another VPC, and a DB instance on
|
||||
* {@code group}, or on none when it is null; with {@code StorageEncrypted: true} when {@code encrypted}, and with a resource that fails
|
||||
* after the instance when {@code laterFails}.
|
||||
*/
|
||||
@@ -89,9 +132,7 @@ class CloudFormationRdsDbInstanceIntegrationTest {
|
||||
String groups = group == null ? "" : """
|
||||
, "VPCSecurityGroups": [{"Fn::GetAtt": ["%s", "GroupId"]}]""".formatted(group);
|
||||
return """
|
||||
{"Resources": {
|
||||
"First": {"Type": "AWS::EC2::SecurityGroup", "Properties": {"GroupDescription": "first"}},
|
||||
"Second": {"Type": "AWS::EC2::SecurityGroup", "Properties": {"GroupDescription": "second"}},
|
||||
{"Resources": {%s,
|
||||
"Elsewhere": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.43.0.0/16"}},
|
||||
"Outside": {"Type": "AWS::EC2::SecurityGroup", "Properties": {"GroupDescription": "outside",
|
||||
"VpcId": {"Ref": "Elsewhere"}}},
|
||||
@@ -103,7 +144,7 @@ class CloudFormationRdsDbInstanceIntegrationTest {
|
||||
"FirstId": {"Value": {"Fn::GetAtt": ["First", "GroupId"]}},
|
||||
"SecondId": {"Value": {"Fn::GetAtt": ["Second", "GroupId"]}}
|
||||
}}
|
||||
""".formatted(groups, encrypted ? ", \"StorageEncrypted\": true" : "",
|
||||
""".formatted(securityGroups("first"), groups, encrypted ? ", \"StorageEncrypted\": true" : "",
|
||||
laterFails ? CfnStackWaits.failingResourceAfter("Db") : "");
|
||||
}
|
||||
|
||||
|
||||
+4
-3
@@ -50,10 +50,11 @@ class CloudFormationStackPolicyServiceTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
provisioner = mock(CfnResourceDispatcher.class);
|
||||
// The last argument is the permissions boundary a delegation registered for the caller,
|
||||
// which a stack deployed by an ordinary caller carries as null.
|
||||
// The last two arguments are the permissions boundary a delegation registered for the caller,
|
||||
// which a stack deployed by an ordinary caller carries as null, and the previous deployment's
|
||||
// engine, which only an update has.
|
||||
when(provisioner.provision(anyString(), anyString(), any(), any(), anyString(), anyString(), anyString(),
|
||||
any(), any(), any(), any(), any(), any())).thenAnswer(invocation -> {
|
||||
any(), any(), any(), any(), any(), any(), any())).thenAnswer(invocation -> {
|
||||
StackResource resource = new StackResource();
|
||||
resource.setLogicalId(invocation.getArgument(0));
|
||||
resource.setResourceType(invocation.getArgument(1));
|
||||
|
||||
@@ -78,6 +78,7 @@ class RdsCfnProvisionerTest {
|
||||
private CfnResourceDispatcher provisioner;
|
||||
private Function<String, String> importResolver;
|
||||
private Map<String, Boolean> conditions;
|
||||
private Map<String, String> parameters;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -88,6 +89,7 @@ class RdsCfnProvisionerTest {
|
||||
ssmService = mock(SsmService.class);
|
||||
importResolver = name -> null;
|
||||
conditions = Map.of();
|
||||
parameters = Map.of();
|
||||
provisioner = CfnProvisionerFixture.builder()
|
||||
.ssm(ssmService)
|
||||
.secretsManager(secretsManagerService)
|
||||
@@ -97,8 +99,12 @@ class RdsCfnProvisionerTest {
|
||||
}
|
||||
|
||||
private CloudFormationTemplateEngine engine() {
|
||||
return engine(parameters);
|
||||
}
|
||||
|
||||
private CloudFormationTemplateEngine engine(Map<String, String> parameterValues) {
|
||||
return new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",
|
||||
"stack/id", Map.of(), Map.of(), Map.of(), conditions, Map.of(), mapper,
|
||||
"stack/id", parameterValues, Map.of(), Map.of(), conditions, Map.of(), mapper,
|
||||
importResolver);
|
||||
}
|
||||
|
||||
@@ -2076,6 +2082,9 @@ class RdsCfnProvisionerTest {
|
||||
"{\"Engine\":\"postgres\",\"DBSubnetGroupName\":\"app-subnets\",\"VPCSecurityGroups\":[\"sg-second\"]}";
|
||||
private static final String ENCRYPTED = "{\"Engine\":\"postgres\",\"StorageEncrypted\":true}";
|
||||
private static final String MEMBER = "{\"DBClusterIdentifier\":\"cluster\"";
|
||||
private static final String MEMBER_ON_PARAMETER = MEMBER + ",\"VPCSecurityGroups\":[{\"Ref\":\"Value\"}]}";
|
||||
private static final String ENCRYPTED_BY_PARAMETER =
|
||||
"{\"Engine\":\"postgres\",\"StorageEncrypted\":{\"Ref\":\"Value\"}}";
|
||||
|
||||
/** What one {@code createDbInstance} call asked for, of what these tests read. */
|
||||
private record CreateRequest(String id, List<String> groups, DbInstanceSettings settings) { }
|
||||
@@ -2085,7 +2094,13 @@ class RdsCfnProvisionerTest {
|
||||
* {@code createDbInstance} call made since, that one first.
|
||||
*/
|
||||
private record Created(StackResource resource, String id, String template, DbInstance onFile,
|
||||
List<CreateRequest> requests) { }
|
||||
List<CreateRequest> requests) {
|
||||
|
||||
/** This instance as an UpdateStack to {@code json} left it, {@code updated}, still under the created id. */
|
||||
Created updatedBy(StackResource updated, String json) {
|
||||
return new Created(updated, id, json, onFile, requests);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A CreateStack of the unnamed instance {@code json}. RdsService then has it on file with
|
||||
@@ -2107,9 +2122,36 @@ class RdsCfnProvisionerTest {
|
||||
|
||||
/** An UpdateStack from the template the instance was created with to {@code json}. */
|
||||
private StackResource updateInstance(Created created, String json) {
|
||||
return provisioner.provision("Db", "AWS::RDS::DBInstance", props(json), engine(), "us-east-1",
|
||||
return updateInstance(created, json, engine());
|
||||
}
|
||||
|
||||
/**
|
||||
* As {@link #updateInstance(Created, String)}, with {@code json} resolved by {@code current}; the
|
||||
* previous template still resolves with {@link #engine()}, as the stack was deployed.
|
||||
*/
|
||||
private StackResource updateInstance(Created created, String json, CloudFormationTemplateEngine current) {
|
||||
return provisioner.provision("Db", "AWS::RDS::DBInstance", props(json), current, "us-east-1",
|
||||
"000000000000", "my-stack", created.id(), created.resource().getAttributes(), event -> { },
|
||||
props(created.template()));
|
||||
props(created.template()), null, null, engine());
|
||||
}
|
||||
|
||||
/**
|
||||
* An instance created from {@code template} with the stack parameter {@code Value} at
|
||||
* {@code before}, then updated to {@code updated} with it at {@code after}; the previous template
|
||||
* still resolves with {@code before}. The result is the updated resource under the created id.
|
||||
*/
|
||||
private Created updateThroughParameter(String template, String updated, String before, String after,
|
||||
String... groupsOnFile) {
|
||||
return updateThroughParameter(template, updated, before, after, created -> { }, groupsOnFile);
|
||||
}
|
||||
|
||||
/** As above, with {@code beforeUpdate} given the created instance first. */
|
||||
private Created updateThroughParameter(String template, String updated, String before, String after,
|
||||
Consumer<Created> beforeUpdate, String... groupsOnFile) {
|
||||
parameters = Map.of("Value", before);
|
||||
Created created = createInstance(template, groupsOnFile);
|
||||
beforeUpdate.accept(created);
|
||||
return created.updatedBy(updateInstance(created, updated, engine(Map.of("Value", after))), updated);
|
||||
}
|
||||
|
||||
/** An instance created on {@code sg-first}, then updated to {@code json}; it is kept, under the same id. */
|
||||
@@ -2129,7 +2171,7 @@ class RdsCfnProvisionerTest {
|
||||
Created created = createInstance(ENCRYPTED);
|
||||
StackResource replaced = updateInstance(created, PLAIN);
|
||||
assertNotEquals(created.id(), replaced.getPhysicalId());
|
||||
return new Created(replaced, created.id(), PLAIN, created.onFile(), created.requests());
|
||||
return created.updatedBy(replaced, PLAIN);
|
||||
}
|
||||
|
||||
/** Makes {@code groupIds} the default groups of whatever VPC an update leaves the instance in. */
|
||||
@@ -2263,13 +2305,15 @@ class RdsCfnProvisionerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', value = {
|
||||
MEMBER + ",\"VPCSecurityGroups\":[\"sg-first\"]} | " + MEMBER + ",\"VPCSecurityGroups\":[\"sg-second\"]}",
|
||||
MEMBER + "} | " + MEMBER + ",\"VPCSecurityGroups\":[\"sg-cluster\"]}"
|
||||
MEMBER + ",\"VPCSecurityGroups\":[\"sg-first\"]} | " + MEMBER + ",\"VPCSecurityGroups\":[\"sg-second\"]} | sg-first",
|
||||
MEMBER + "} | " + MEMBER + ",\"VPCSecurityGroups\":[\"sg-cluster\"]} | sg-first",
|
||||
MEMBER_ON_PARAMETER + " | " + MEMBER_ON_PARAMETER + " | sg-second"
|
||||
})
|
||||
void aClusterMemberWhoseTemplateChangesItsGroupsFailsBeforeAnythingChanges(String template, String updated) {
|
||||
void aClusterMemberWhoseTemplateChangesItsGroupsFailsBeforeAnythingChanges(String template, String updated,
|
||||
String groupNow) {
|
||||
// AWS's handler sends the change to ModifyDBInstance, and RDS refuses it for a member, even one
|
||||
// that names the groups the member already has.
|
||||
StackResource r = updateInstance(createInstance(template, "sg-cluster"), updated);
|
||||
// that names the groups the member already has, or changes them only through a parameter.
|
||||
StackResource r = updateThroughParameter(template, updated, "sg-first", groupNow, "sg-cluster").resource();
|
||||
|
||||
assertEquals("CREATE_FAILED", r.getStatus());
|
||||
assertTrue(r.getStatusReason().contains("Modify vpc security group for the DB Cluster"), r.getStatusReason());
|
||||
@@ -2403,18 +2447,21 @@ class RdsCfnProvisionerTest {
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', value = {ENCRYPTED + " | false", PLAIN + " | true"})
|
||||
@CsvSource(delimiter = '|', value = {
|
||||
ENCRYPTED + " | " + ENCRYPTED + " | true | false",
|
||||
ENCRYPTED + " | " + PLAIN + " | true | true",
|
||||
ENCRYPTED_BY_PARAMETER + " | " + ENCRYPTED_BY_PARAMETER + " | false | true"
|
||||
})
|
||||
void anInstanceFromBeforeStorageEncryptedWasRecordedIsComparedWithThePreviousTemplate(
|
||||
String updated, boolean replaced) {
|
||||
// Its template said true, but nothing records that, so the update reads the previous template:
|
||||
// keeping true keeps the instance, dropping it replaces the instance.
|
||||
Created created = createInstance(ENCRYPTED);
|
||||
created.resource().getAttributes().remove(ENCRYPTION_ATTR);
|
||||
String template, String updated, String encryptedNow, boolean replaced) {
|
||||
// Its template said true, but nothing records that, so the update reads the previous template,
|
||||
// resolved with the parameters it was deployed with: keeping true keeps the instance, dropping
|
||||
// it, or turning the parameter it reads to false, replaces the instance.
|
||||
Created result = updateThroughParameter(template, updated, "true", encryptedNow,
|
||||
created -> created.resource().getAttributes().remove(ENCRYPTION_ATTR));
|
||||
|
||||
StackResource r = updateInstance(created, updated);
|
||||
|
||||
assertEquals(replaced, !created.id().equals(r.getPhysicalId()));
|
||||
assertEquals(String.valueOf(!replaced), r.getAttributes().get(ENCRYPTION_ATTR));
|
||||
assertEquals(replaced, !result.id().equals(result.resource().getPhysicalId()));
|
||||
assertEquals(String.valueOf(!replaced), result.resource().getAttributes().get(ENCRYPTION_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+7
-1
@@ -72,7 +72,8 @@ class ProvisionContextTest {
|
||||
PropertyChanges changes = PropertyChanges.between("AWS::SQS::Queue", true,
|
||||
props("{\"A\":1}"), props("{\"A\":2}"));
|
||||
ProvisionContext original = new ProvisionContext(engine, "eu-west-1", "123456789012", "stack",
|
||||
"old-id", event -> {}, props("{\"A\":1}"), changes);
|
||||
"old-id", event -> {}, props("{\"A\":1}"), changes, "boundary-arn",
|
||||
mock(CloudFormationTemplateEngine.class));
|
||||
|
||||
for (String replacement : new String[] {"new-id", null}) {
|
||||
ProvisionContext copy = original.withPriorPhysicalId(replacement);
|
||||
@@ -86,6 +87,11 @@ class ProvisionContextTest {
|
||||
assertEquals("old-id", original.priorPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aContextWithoutThePreviousDeploymentsEngineResolvesThePreviousPropertiesWithItsOwn() {
|
||||
assertSame(engine, contextWithPriorProperties("{}").priorEngine());
|
||||
}
|
||||
|
||||
@Test
|
||||
void previouslyDeclaredReadsThePreviousTemplatesProperties() {
|
||||
ProvisionContext ctx = contextWithPriorProperties("""
|
||||
|
||||
@@ -85,6 +85,19 @@ public final class RdsRequests {
|
||||
.vpcSecurityGroups().stream().map(VpcSecurityGroupMembership::vpcSecurityGroupId).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Two CloudFormation resources, to put inside a template's {@code Resources}: an Aurora PostgreSQL
|
||||
* cluster {@code Cluster}, and its {@code Member} instance, which also has
|
||||
* {@code memberProperties}, written as members of a JSON object.
|
||||
*/
|
||||
public static String auroraClusterWithMember(String memberProperties) {
|
||||
return """
|
||||
"Cluster": {"Type": "AWS::RDS::DBCluster", "Properties": {"Engine": "aurora-postgresql",
|
||||
"MasterUsername": "dbadmin", "MasterUserPassword": "password123"}},
|
||||
"Member": {"Type": "AWS::RDS::DBInstance", "Properties": {"DBClusterIdentifier": {"Ref": "Cluster"},
|
||||
"Engine": "aurora-postgresql", "DBInstanceClass": "db.r6g.large", %s}}""".formatted(memberProperties);
|
||||
}
|
||||
|
||||
private static RdsClientBuilder rdsClientBuilder(String region, String account) {
|
||||
return RdsClient.builder()
|
||||
.endpointOverride(URI.create("http://localhost:" + RestAssured.port))
|
||||
|
||||
Reference in new issue
Block a user