From 3e1fe3c8b64cff5b23cc65c99812b05e4b547865 Mon Sep 17 00:00:00 2001 From: Suja Shaj <135242046+sujashaj@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:55:19 -0800 Subject: [PATCH] fix(cloudformation): resolve an RDS instance's previous template as it was deployed (#9058) --- docs/services/cloudformation.md | 12 +-- .../cloudformation/CloudFormationService.java | 2 +- .../provisioners/CfnResourceDispatcher.java | 10 ++- .../provisioners/ProvisionContext.java | 27 +++++- .../provisioners/RdsCfnProvisioner.java | 18 ++-- ...tionRdsAssociatedRolesIntegrationTest.java | 14 +-- ...FormationRdsDbInstanceIntegrationTest.java | 53 +++++++++-- .../CloudFormationStackPolicyServiceTest.java | 7 +- .../cloudformation/RdsCfnProvisionerTest.java | 87 ++++++++++++++----- .../provisioners/ProvisionContextTest.java | 8 +- .../io/floci/aws/testing/RdsRequests.java | 13 +++ 11 files changed, 190 insertions(+), 61 deletions(-) diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 6ec5bed03a..9f6676eff2 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -648,9 +648,11 @@ Dynamic-reference expansion is currently scoped to these RDS credential properti `CreateDBInstance` does, so `DescribeDBInstances` reports the declared groups and the encryption. - On `UpdateStack`, a changed `VPCSecurityGroups` moves the instance to the new groups in place, as - in AWS. A cluster member's groups are its cluster's, so an update whose template changes a - member's list fails with `InvalidParameterCombination` before anything changes, as RDS refuses - that change for a member. When the previous template declared groups and the new one does not, a + in AWS. A cluster member's groups are its cluster's, so an update that changes a member's list + fails with `InvalidParameterCombination` before the member changes, as RDS refuses that change for + a member. That includes a change made only through a parameter, or through a group the same + update replaces. A replaced security group is not rolled back yet, so that last update ends in + `UPDATE_ROLLBACK_FAILED`. When the previous template declared groups and the new one does not, a standalone instance is put on its VPC's default security group, as AWS's handler does; a cluster member, or an instance whose VPC has no default group, keeps its groups. While the template never declares groups, groups set outside the stack are kept. @@ -663,8 +665,8 @@ Dynamic-reference expansion is currently scoped to these RDS credential properti custom `DBInstanceIdentifier` cannot be replaced, so that update fails with a `ValidationError`, as in AWS. An instance created before Floci applied `StorageEncrypted` is unencrypted whatever its template said, and is replaced only by an update that changes the property. Its first update - reads the previous value from the previous template, resolved on that update, so a change made - only through a parameter, or anything else the update changes, is not seen there. + reads the previous value from the previous template, resolved with the parameters that deployment + had, so a change made only through a parameter replaces it too. - `KmsKeyId` is still accepted and ignored, so an encrypted instance reports no key. ## ELBv2 target group targets diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java index 9baa36aea9..5d309d0616 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java @@ -2949,7 +2949,7 @@ public class CloudFormationService implements ResourceProvider { resource.getPhysicalId(), resource.getAttributes(), event -> addEvent(stack, logicalId, event.getPhysicalResourceId(), type, event.getResourceStatus(), event.getResourceStatusReason()), - priorProps, changes, stack.getDelegatedRoleBoundaryArn()); + priorProps, changes, stack.getDelegatedRoleBoundaryArn(), previousEngine); } resource.setUpdateReplacePolicy( resDef.path("UpdateReplacePolicy").asText(null)); diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnResourceDispatcher.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnResourceDispatcher.java index 97804b9bd0..a4e6eec758 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnResourceDispatcher.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnResourceDispatcher.java @@ -111,19 +111,21 @@ public class CfnResourceDispatcher { Map existingAttributes, Consumer progress, JsonNode priorProperties, PropertyChanges changes) { return provision(logicalId, resourceType, properties, engine, region, accountId, stackName, - existingPhysicalId, existingAttributes, progress, priorProperties, changes, null); + existingPhysicalId, existingAttributes, progress, priorProperties, changes, null, null); } /** * The same with the permissions boundary a delegation registered for whoever created the stack, - * which the role provisioner applies to a role it creates. + * which the role provisioner applies to a role it creates, and {@code priorEngine}, which + * resolves {@code priorProperties} with the previous deployment's parameters; see + * {@link ProvisionContext}. */ public StackResource provision(String logicalId, String resourceType, JsonNode properties, CloudFormationTemplateEngine engine, String region, String accountId, String stackName, String existingPhysicalId, Map existingAttributes, Consumer progress, JsonNode priorProperties, PropertyChanges changes, - String delegatedRoleBoundaryArn) { + String delegatedRoleBoundaryArn, CloudFormationTemplateEngine priorEngine) { StackResource resource = new StackResource(); resource.setLogicalId(logicalId); resource.setResourceType(resourceType); @@ -135,7 +137,7 @@ public class CfnResourceDispatcher { if (owner != null) { owner.provision(resource, properties, new ProvisionContext(engine, region, accountId, stackName, existingPhysicalId, progress, - priorProperties, changes, delegatedRoleBoundaryArn)); + priorProperties, changes, delegatedRoleBoundaryArn, priorEngine)); // A provisioner that migrated a stub without writing its own Arn would leave the // stub's, and the real resource would read as a stub on its next update. String arn = resource.getAttributes().get("Arn"); diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java index 02891e73ad..bd350fc241 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java @@ -20,11 +20,34 @@ import java.util.function.Consumer; * intrinsic functions in properties) plus the region/account/stack it is being created in. The * helpers were lifted verbatim from the former CloudFormation monolith's private methods * so extracted provisioners produce byte-identical physical ids and resolved values. + * + *

{@code priorEngine} resolves {@code priorProperties} with the previous deployment's parameters, + * conditions and mappings, and the physical ids and attributes the update started from. A value the + * previous template took from a parameter, or from a resource this update replaces, reads as it was + * then. A dynamic reference, an export or another stack's output still reads its current value. A + * context built without one uses {@code engine} there, which reads such a value as this update + * resolves it. */ public record ProvisionContext(CloudFormationTemplateEngine engine, String region, String accountId, String stackName, String priorPhysicalId, Consumer progress, JsonNode priorProperties, - PropertyChanges changes, String delegatedRoleBoundaryArn) { + PropertyChanges changes, String delegatedRoleBoundaryArn, + CloudFormationTemplateEngine priorEngine) { + + public ProvisionContext { + if (priorEngine == null) { + priorEngine = engine; + } + } + + /** The context without the previous deployment's engine; see the record's description. */ + public ProvisionContext(CloudFormationTemplateEngine engine, String region, + String accountId, String stackName, String priorPhysicalId, + Consumer progress, JsonNode priorProperties, + PropertyChanges changes, String delegatedRoleBoundaryArn) { + this(engine, region, accountId, stackName, priorPhysicalId, progress, priorProperties, changes, + delegatedRoleBoundaryArn, null); + } /** * The context as every provisioner but the IAM role one needs it: no delegation cap, which is @@ -56,7 +79,7 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio */ public ProvisionContext withPriorPhysicalId(String priorPhysicalId) { return new ProvisionContext(engine, region, accountId, stackName, priorPhysicalId, progress, - priorProperties, changes); + priorProperties, changes, delegatedRoleBoundaryArn, priorEngine); } /** Intermediate resource events retain the stack pipeline's event IDs and metadata. */ diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/RdsCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/RdsCfnProvisioner.java index f200341704..766fc9f962 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/RdsCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/RdsCfnProvisioner.java @@ -107,10 +107,9 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { * The change is read against this record, as CloudFormation reads the template's change, and not * against the instance: one a stack created before Floci applied the property is unencrypted * whatever its template said. Such a resource has no record, so its first update reads the - * previous template's value instead, resolved as well as it still can be, and replaces the - * instance only when that changed. As in {@link Ec2Tags#ownedKeys}, that template resolves on this - * update, so a value taken from a parameter, or from anything else the update changes, reads as the - * new one, and a change made only that way is not seen. + * previous template's value instead, resolved with the previous deployment's parameters (see + * {@link ProvisionContext}), and replaces the instance only when that changed, a change made only + * through a parameter included. */ private static final CreateOnlyInputs DB_INSTANCE_STORAGE_ENCRYPTED = new CreateOnlyInputs( "__FlociDbInstanceStorageEncrypted", "__FlociDbInstanceStorageEncryptedPrior"); @@ -422,7 +421,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { DbInstance instance = sameNameExistingResource(priorPhysicalId, id, rdsService::getDbInstance); String recordedEncryption = DB_INSTANCE_STORAGE_ENCRYPTED.read(attributesBefore); if (recordedEncryption == null && instance != null && ctx.priorProperties() != null) { - recordedEncryption = String.valueOf(parseBoolProp(ctx.priorProperties(), "StorageEncrypted", engine)); + recordedEncryption = String.valueOf( + parseBoolProp(ctx.priorProperties(), "StorageEncrypted", ctx.priorEngine())); } boolean replacing = instance != null && recordedEncryption != null && !recordedEncryption.equals(encryptionRecord); @@ -513,8 +513,10 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { * The VPC security groups a kept instance should have, or null to leave them as they are. A * declared list is the groups, but a cluster member's groups are its cluster's: a template that * changes a member's list fails the update, as on AWS, where the handler sends the change to - * ModifyDBInstance and RDS refuses it for a member. The change is read from the template, as - * there, so a member a stack created before Floci applied the list still takes it. A list the + * ModifyDBInstance and RDS refuses it for a member. The change is read from the templates, each + * resolved with its own deployment's parameters and resources (see {@link ProvisionContext}), as + * there: a change made only through a parameter, or a group this update replaced, is one, and a + * member a stack created before Floci applied the list still takes it. A list the * previous template declared and this one drops puts a standalone instance on the default security * group of the VPC {@code subnetGroupName} leaves it in, as AWS's handler does, and leaves them * when there is no such group, as there; a @@ -526,7 +528,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { boolean member = clusterMember != null && !clusterMember.isBlank(); if (!declared.isEmpty()) { if (member && ctx.priorProperties() != null && !Set.copyOf(declared).equals( - Set.copyOf(resolveStringList(ctx.priorProperties(), "VPCSecurityGroups", ctx.engine())))) { + Set.copyOf(resolveStringList(ctx.priorProperties(), "VPCSecurityGroups", ctx.priorEngine())))) { throw new AwsException("InvalidParameterCombination", "The specified DB Instance is a member of a" + " cluster. Modify vpc security group for the DB Cluster using the ModifyDbCluster API", 400); } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsAssociatedRolesIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsAssociatedRolesIntegrationTest.java index e8a2257ad8..baeeb8a3ba 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsAssociatedRolesIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsAssociatedRolesIntegrationTest.java @@ -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()); diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsDbInstanceIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsDbInstanceIntegrationTest.java index a2cefd326c..f988529bd5 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsDbInstanceIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsDbInstanceIntegrationTest.java @@ -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 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") : ""); } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackPolicyServiceTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackPolicyServiceTest.java index ba9a304066..2be46bb1b5 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackPolicyServiceTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackPolicyServiceTest.java @@ -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)); diff --git a/src/test/java/io/floci/aws/services/cloudformation/RdsCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/RdsCfnProvisionerTest.java index 1f3a630f51..6d8312bcfc 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/RdsCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/RdsCfnProvisionerTest.java @@ -78,6 +78,7 @@ class RdsCfnProvisionerTest { private CfnResourceDispatcher provisioner; private Function importResolver; private Map conditions; + private Map 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 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 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 requests) { } + List 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 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 diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java index fc47bf0ade..be9408a54b 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java @@ -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(""" diff --git a/src/test/java/io/floci/aws/testing/RdsRequests.java b/src/test/java/io/floci/aws/testing/RdsRequests.java index 2380845908..cb872159d6 100644 --- a/src/test/java/io/floci/aws/testing/RdsRequests.java +++ b/src/test/java/io/floci/aws/testing/RdsRequests.java @@ -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))