fix(cloudformation): give a DB instance its security groups and encryption (#7867)

An AWS::RDS::DBInstance created through CloudFormation never received
its VPCSecurityGroups or StorageEncrypted, so describe-db-instances
showed neither. Both now reach the instance on create.

A stack update that changes the groups moves the instance to them in
place, and one that drops them puts a standalone instance on its VPC's
default group, as AWS does; a cluster member keeps its groups. A
rollback puts the previous groups back. StorageEncrypted can only be
set at create, so changing or dropping it replaces the instance: the
old one is deleted once the update commits and kept when it rolls
back. A custom-named instance refuses the change, as on AWS.

Part of #7603

The rollback test of a security group change now starts from two groups
and from none, as well as from one, so a saved list that kept only its
last group, or saved nothing for an instance that had none, fails it.
The line that saves the list now creates the array first, which reads
more plainly.

The docs and the encryption record's Javadoc now say that an instance
created before StorageEncrypted was applied, whose template sets it
through a parameter, does not see a change made only through that
parameter on its first update, as Ec2Tags.ownedKeys already notes for
tags.

The DB instance and DB cluster arms refuse a custom-named replacement
through CfnExceptions.customNamedReplacement, and the private copy is
gone.

The DB cluster's createOnly record and the AssociatedRoles record are
CreateOnlyInputs constants now, beside the DB instance's encryption
record, so all three are read, written, put back on a rollback and
cleared on commit through it. The attribute names are unchanged, so a
stack created before keeps its records, and an update that leaves the
cluster record as it was still saves no copy of it.

One thing changes with it: the roles record an update overwrites is now
saved every time, where it used to be saved only when no saved copy was
there. A committed in-place update used to leave that copy on the
resource, so a stack from then could have its roles record rolled back
to an older one by the first update that fails; a test covers it.

The encryption record's Javadoc and the docs now say that the previous
template resolves on the update, so a change made only through a
parameter, or anything else the update changes, is not seen.

An update whose template changed a cluster member's VPCSecurityGroups
moved the member to the new groups. On AWS the handler sends that change
to ModifyDBInstance and RDS refuses it for a member, whose groups are
its cluster's, so the update fails. It now fails the same way, with
InvalidParameterCombination and RDS's message, before anything on the
instance changes.

The change is read from the template, as AWS's handler reads it, so a
member whose list stays the same still updates, including one a stack
created before Floci applied the groups. Refusing the property outright
would fail a list that matches the cluster's, which the schema allows.
This commit is contained in:
Suja Shaj authored and GitHub committed 2026-11-11 00:49:50 -04:00
1 parent 3270066923
commit 3d3e94dcc6
10 files changed
+888 -168

No files matched your search

+25
View File
@@ -567,6 +567,31 @@ Dynamic-reference expansion is currently scoped to these RDS credential properti
- On `UpdateStack` (no interruption, as in AWS), a cluster's list is checked first, then the roles the template gained are added, and the roles the previous template declared and the new one drops are removed. A role associated outside the stack is kept while the template leaves it out; declaring it fails the update with `DBClusterRoleAlreadyExists`, as in AWS. If any step of an update is refused, the roles it already added are removed and the ones it removed are put back, so the database matches what the stack still records and a retry starts from there. A rolled-back cluster replacement restores the record of which roles the stack declared.
- An Aurora cluster member (`AWS::RDS::DBInstance` with `DBClusterIdentifier`) cannot carry `AssociatedRoles`: the schema documents the property as not applicable there, since the cluster manages its roles. The resource fails with a `ValidationError` pointing at the cluster's `AssociatedRoles`.
## RDS DB instance security groups and encryption
`AWS::RDS::DBInstance` creates the instance with its `VPCSecurityGroups` and `StorageEncrypted`, as
`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
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.
- A failed update puts the groups back. The rollback is complete when the update changed nothing
else Floci applies; a change to the password, IAM authentication, subnet group, CA certificate or
roles is still reported as not rolled back.
- `StorageEncrypted` is createOnly, so changing it, including dropping `StorageEncrypted: true`,
replaces the instance under a new generated name. The old instance is deleted once the update
commits, or kept, with the replacement deleted, when the update rolls back. An instance with a
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.
- `KmsKeyId` is still accepted and ignored, so an encrypted instance reports no key.
## S3 ownership controls
`AWS::S3::Bucket` applies `OwnershipControls` through the same S3 call as
@@ -25,6 +25,7 @@ import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -39,8 +40,9 @@ import java.util.function.Function;
* Extracted from the former CloudFormation monolith.
*
* <p>Every type here deletes by physical id alone, so the id-only
* {@link #delete(String, String, String)} serves all seven. {@code DBCluster} is the one type that
* replaces through {@link ReplacementCleanup}; see {@code provisionDbCluster}.
* {@link #delete(String, String, String)} serves all seven. {@code DBCluster} and {@code DBInstance}
* are the types that replace through {@link ReplacementCleanup}; see {@code provisionDbCluster} and
* {@code provisionDbInstance}.
*
* <p>Unlike most extractions this one does not take {@code RdsService} out of the monolith.
* {@code AWS::SecretsManager::SecretTargetAttachment} is still served there and reads an
@@ -60,7 +62,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
* emulate a KMS key, public access, a subnet group placement chosen by the template or a
* restore source on a cluster, so a change to one of these can only be seen against what the
* template said last time. The values the last successful provision resolved are kept on the
* resource under {@link #DB_CLUSTER_CREATE_ONLY_ATTR}, which is how CloudFormation decides too:
* resource under {@link #DB_CLUSTER_CREATE_ONLY}, which is how CloudFormation decides too:
* on the template's change, not on the live entity.
*/
static final List<String> DB_CLUSTER_RECORDED_CREATE_ONLY = List.of(
@@ -82,26 +84,42 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
/**
* The recorded createOnly values of a DB cluster resource, a JSON object keyed by property.
* Internal, like the other {@code __Floci} attributes. A resource provisioned before these were
* recorded has none, and its first update records them without replacing anything.
* recorded has none, and its first update records them without replacing anything. The record
* an update overwrote is kept until the update commits, so a rollback puts it back beside the
* prior cluster.
*/
static final String DB_CLUSTER_CREATE_ONLY_ATTR = "__FlociDbClusterCreateOnly";
/**
* The record an update overwrote, kept until the update commits so a rollback puts it back
* beside the prior cluster; an empty value means there was no record before.
*/
static final String DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR = "__FlociDbClusterCreateOnlyPrior";
private static final CreateOnlyInputs DB_CLUSTER_CREATE_ONLY = new CreateOnlyInputs(
"__FlociDbClusterCreateOnly", "__FlociDbClusterCreateOnlyPrior");
/**
* The {@code AssociatedRoles} the template declared at the last successful provision, a JSON
* array of {@code {RoleArn, FeatureName}}. An update removes only roles this record names and
* the template no longer does, so a role associated outside the stack is left in place.
* the template no longer does, so a role associated outside the stack is left in place. The
* record an update overwrote is kept until the update commits, so a rollback that puts the prior
* cluster or instance back puts its record back too.
*/
static final String ASSOCIATED_ROLES_ATTR = "__FlociAssociatedRoles";
private static final CreateOnlyInputs ASSOCIATED_ROLES = new CreateOnlyInputs(
"__FlociAssociatedRoles", "__FlociAssociatedRolesPrior");
/**
* The roles record an update overwrote, kept until the update commits so a rollback that puts
* the prior cluster back puts its record back too; an empty value means there was none.
* The {@code StorageEncrypted} a DB instance resource was last provisioned with, {@code true} or
* {@code false}. The property is createOnly, so an update that changes it replaces the instance.
* 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.
*/
static final String ASSOCIATED_ROLES_PRIOR_ATTR = "__FlociAssociatedRolesPrior";
private static final CreateOnlyInputs DB_INSTANCE_STORAGE_ENCRYPTED = new CreateOnlyInputs(
"__FlociDbInstanceStorageEncrypted", "__FlociDbInstanceStorageEncryptedPrior");
/**
* What an update that kept a DB instance needs for {@link #rollbackUpdate}: the region, the VPC
* security groups the instance had when the update changed them, and whether it changed anything
* else, which has no rollback here.
*/
static final String DB_INSTANCE_PRIOR_IN_PLACE_ATTR = "__FlociDbInstancePriorInPlaceUpdate";
private final RdsService rdsService;
private final CfnDynamicReferences dynamicReferences;
@@ -145,7 +163,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
@Override
public void delete(String resourceType, String physicalId, String region) {
switch (resourceType) {
case "AWS::RDS::DBInstance" -> rdsService.deleteDbInstance(physicalId, region);
case "AWS::RDS::DBInstance" -> CfnDeletes.safeDelete("DB instance", physicalId,
() -> rdsService.deleteDbInstance(physicalId, region), "DBInstanceNotFound");
case "AWS::RDS::DBCluster" -> CfnDeletes.safeDelete("DB cluster", physicalId,
() -> rdsService.deleteDbCluster(physicalId, region), "DBClusterNotFoundFault");
case "AWS::RDS::DBProxy" -> deleteDbProxySafe(physicalId, region);
@@ -159,8 +178,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
}
}
// ── replacement lifecycle: only AWS::RDS::DBCluster records one, so the other types answer
// "no cleanup owed" through ReplacementCleanup's own empty-record handling ──
// ── replacement lifecycle: only AWS::RDS::DBCluster and AWS::RDS::DBInstance record one, so the
// other types answer "no cleanup owed" through ReplacementCleanup's own empty-record handling ──
@Override
public boolean hasReplacementUpdate(StackResource resource) {
@@ -174,44 +193,82 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
resource.getAttributes().remove(DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR);
// An in-place update owes no cleanup, so the engine calls clearUpdate only after a
// replacement: the records a rollback would have spent go here, or the next update's
// rollback would put back the ones this update replaced.
clearPriorRecords(resource);
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR);
resource.getAttributes().remove(ASSOCIATED_ROLES_PRIOR_ATTR);
clearPriorRecords(resource);
ReplacementCleanup.clear(resource);
}
/**
* A replacement is undone through the cleanup record: the resource names the displaced cluster
* again and the replacement is deleted. The createOnly record follows the cluster back, since
* {@link ReplacementCleanup} leaves {@code __Floci} attributes alone. Without a record the
* update was in place, and putting that back needs a snapshot this provisioner does not keep,
* so the engine keeps reporting it as not rolled back, as before.
* or instance again and the replacement is deleted. The createOnly and roles records follow it
* back, since {@link ReplacementCleanup} leaves {@code __Floci} attributes alone, even when the
* replacement's delete fails, as the resource names the displaced one from then on. Without a
* record the update was in place: an instance's VPC security groups are put back, and the
* rollback counts as done when the update changed nothing else. Any other in-place change needs
* a snapshot this provisioner does not keep, so the engine keeps reporting it as not rolled back.
*/
@Override
public boolean rollbackUpdate(StackResource resource) {
boolean replaced = ReplacementCleanup.rollback(resource, this::delete);
String priorRecord = resource.getAttributes().remove(DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR);
if (priorRecord != null) {
if (priorRecord.isEmpty()) {
resource.getAttributes().remove(DB_CLUSTER_CREATE_ONLY_ATTR);
} else {
resource.getAttributes().put(DB_CLUSTER_CREATE_ONLY_ATTR, priorRecord);
}
boolean replaced;
try {
replaced = ReplacementCleanup.rollback(resource, this::delete);
} finally {
restorePriorRecords(resource);
}
String priorRoles = resource.getAttributes().remove(ASSOCIATED_ROLES_PRIOR_ATTR);
if (priorRoles != null) {
if (priorRoles.isEmpty()) {
resource.getAttributes().remove(ASSOCIATED_ROLES_ATTR);
} else {
resource.getAttributes().put(ASSOCIATED_ROLES_ATTR, priorRoles);
}
if (replaced) {
resource.getAttributes().remove(DB_INSTANCE_PRIOR_IN_PLACE_ATTR);
return true;
}
return replaced;
return restoreDbInstanceInPlaceUpdate(resource);
}
private static void restorePriorRecords(StackResource resource) {
DB_CLUSTER_CREATE_ONLY.restorePrior(resource);
ASSOCIATED_ROLES.restorePrior(resource);
DB_INSTANCE_STORAGE_ENCRYPTED.restorePrior(resource);
}
private static void clearPriorRecords(StackResource resource) {
DB_CLUSTER_CREATE_ONLY.clearPrior(resource);
ASSOCIATED_ROLES.clearPrior(resource);
DB_INSTANCE_STORAGE_ENCRYPTED.clearPrior(resource);
resource.getAttributes().remove(DB_INSTANCE_PRIOR_IN_PLACE_ATTR);
}
/**
* Puts back the VPC security groups an update that kept the instance changed, and answers whether
* that undid the whole update. The saved record is dropped only once the groups are back, so an
* instance gone since the update fails the rollback, and a retried one tries again.
*/
private boolean restoreDbInstanceInPlaceUpdate(StackResource resource) {
String saved = resource.getAttributes().get(DB_INSTANCE_PRIOR_IN_PLACE_ATTR);
if (saved == null) {
return false;
}
JsonNode prior;
try {
prior = MAPPER.readTree(saved);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not read the saved in-place update of "
+ resource.getLogicalId(), e);
}
JsonNode groups = prior.path("vpcSecurityGroups");
if (groups.isArray()) {
List<String> groupIds = new ArrayList<>();
groups.forEach(group -> groupIds.add(group.asText()));
rdsService.setDbInstanceVpcSecurityGroups(prior.path("region").asText(), resource.getPhysicalId(),
groupIds);
}
resource.getAttributes().remove(DB_INSTANCE_PRIOR_IN_PLACE_ATTR);
return !prior.path("otherChanges").asBoolean(true);
}
private void provisionDbSubnetGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
@@ -322,12 +379,22 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put("DBClusterParameterGroupName", group.getDbClusterParameterGroupName());
}
/**
* A DB instance on file under the same id is updated in place, unless {@code StorageEncrypted},
* a createOnlyProperty of the {@code AWS::RDS::DBInstance} schema, changed (see
* {@link #DB_INSTANCE_STORAGE_ENCRYPTED}): the replacement is created under a distinct physical
* id and the displaced instance is deleted once the update commits, or kept when a later resource
* fails the update, as {@code provisionDbCluster} does for a cluster. A custom-named instance is
* refused that update, as CloudFormation refuses it.
*/
private void provisionDbInstance(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
ProvisionContext ctx, String region) {
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
String explicitId = resolveOptional(props, "DBInstanceIdentifier", engine);
String priorPhysicalId = r.getPhysicalId();
boolean customNamed = explicitId != null && !explicitId.isBlank();
String id;
if (explicitId != null && !explicitId.isBlank()) {
if (customNamed) {
id = explicitId;
} else if (priorPhysicalId != null) {
id = priorPhysicalId;
@@ -337,11 +404,10 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
// provision() is re-invoked on every UpdateStack for every resource, so a same-id instance
// already on file must be reconciled rather than re-created (createDbInstance throws
// DBInstanceAlreadyExists). Only password, IAM auth and subnet group are reconciled here.
// modifyDbInstance also takes DBInstanceClass, AllocatedStorage and EngineVersion now, but
// threading them through an UpdateStack is a separate change: DBInstanceClass and
// AllocatedStorage are update-in-place on the AWS::RDS::DBInstance schema while Engine is
// create-only, so passing them needs the replacement handling the DB cluster arm has.
// DBInstanceAlreadyExists). Password, IAM auth, subnet group, CA certificate, roles and VPC
// security groups are reconciled here. modifyDbInstance also takes DBInstanceClass,
// AllocatedStorage and EngineVersion now; threading them through an UpdateStack is a
// separate change.
List<DbRoleAssociation> roles = parseAssociatedRoles(props, engine);
String clusterMember = resolveOptional(props, "DBClusterIdentifier", engine);
if (!roles.isEmpty() && clusterMember != null && !clusterMember.isBlank()) {
@@ -350,9 +416,32 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
+ ", a member of DB cluster " + clusterMember
+ "; set AssociatedRoles on the AWS::RDS::DBCluster instead.", 400);
}
Boolean storageEncrypted = parseOptionalStrictBoolProp(props, "StorageEncrypted", engine);
String encryptionRecord = String.valueOf(Boolean.TRUE.equals(storageEncrypted));
List<String> vpcSecurityGroups = resolveStringList(props, "VPCSecurityGroups", engine);
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));
}
boolean replacing = instance != null && recordedEncryption != null
&& !recordedEncryption.equals(encryptionRecord);
if (replacing) {
if (customNamed) {
throw CfnExceptions.customNamedReplacement(id);
}
id = ctx.generatePhysicalName(r.getLogicalId(), 60, true);
LOG.infov("Replacing DB instance {0} with {1}: StorageEncrypted {2} -> {3}",
priorPhysicalId, id, recordedEncryption, encryptionRecord);
instance = null;
}
boolean created = instance == null;
String caCertificate = resolveOptional(props, "CACertificateIdentifier", engine);
DbInstanceInPlaceState stateBefore = created ? null : DbInstanceInPlaceState.of(instance);
// Worked out before anything changes, so that nothing can fail between the changes a
// rollback cannot undo and the groups, which it can.
List<String> desiredGroups = created ? null
: desiredVpcSecurityGroups(vpcSecurityGroups, clusterMember, id, ctx);
if (instance != null) {
// A null region keeps the default-region lookup sameNameExistingResource made.
instance = rdsService.modifyDbInstance(
@@ -375,13 +464,16 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
resolveOptional(props, "DBParameterGroupName", engine),
resolveOptional(props, "DBSubnetGroupName", engine),
resolveOptional(props, "DBClusterIdentifier", engine),
null, false, false, null, Map.of(), List.of(), null, region, true,
DbInstanceSettings.defaults().withCaCertificateIdentifier(caCertificate));
null, false, false, null, Map.of(), vpcSecurityGroups, null, region, true,
new DbInstanceSettings(storageEncrypted, null, null, null, null, null)
.withCaCertificateIdentifier(caCertificate));
}
// The roles go on before a renamed instance's predecessor is deleted, so a refused list
// deletes only the new instance and the stack still has the old one to roll back to.
instance = reconcileInstanceRoles(r, instance, roles, created, ctx.isUpdate(), region);
if (created) {
// deletes only the new instance and the stack still has the old one to roll back to. A
// replaced instance is kept until the update commits instead.
instance = reconcileInstanceRoles(r, instance, roles, created, region);
ASSOCIATED_ROLES.record(r, ctx, attributesBefore, associatedRolesRecord(roles));
if (created && !replacing) {
deleteRenamedResource(priorPhysicalId, id, rdsService::deleteDbInstance, "DB instance");
}
r.setPhysicalId(instance.getDbInstanceIdentifier());
@@ -401,6 +493,101 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
if (ca.validTill() != null) {
r.getAttributes().put("CertificateDetails.ValidTill", ca.validTill().toString());
}
if (created) {
r.getAttributes().remove(DB_INSTANCE_PRIOR_IN_PLACE_ATTR);
} else {
reconcileInstanceSecurityGroups(r, instance, desiredGroups, stateBefore, ctx);
}
DB_INSTANCE_STORAGE_ENCRYPTED.record(r, ctx, attributesBefore, encryptionRecord);
// A provision that left the resource with a new physical id for its StorageEncrypted replaced
// the instance: the displaced one is deleted once the update commits, or kept if it rolls back.
ReplacementCleanup.record(r, ctx, attributesBefore, replacing);
}
/**
* 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
* previous template declared and this one drops puts a standalone instance on its VPC's default
* security group, as AWS's handler does, and leaves them when there is no such group, as there; a
* cluster member keeps its groups, as there too. A list the stack never declared leaves groups set
* outside it alone.
*/
private List<String> desiredVpcSecurityGroups(List<String> declared, String clusterMember, String id,
ProvisionContext ctx) {
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())))) {
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);
}
return declared;
}
if (!ctx.previouslyDeclared("VPCSecurityGroups") || member) {
return null;
}
List<String> defaultGroup = rdsService.defaultVpcSecurityGroupIds(ctx.region(), id);
return defaultGroup.isEmpty() ? null : defaultGroup;
}
/**
* Brings a kept instance's VPC security groups to {@code desired}, the last change of the update:
* when an earlier step fails, the engine restores the resource without calling
* {@link #rollbackUpdate}, so only a change made after every other one can be put back there.
* What the instance had is saved first, with whether the update changed anything else, for
* {@link #rollbackUpdate}.
*/
private void reconcileInstanceSecurityGroups(StackResource r, DbInstance instance, List<String> desired,
DbInstanceInPlaceState stateBefore, ProvisionContext ctx) {
String id = instance.getDbInstanceIdentifier();
List<String> groupsBefore = stateBefore.vpcSecurityGroups();
boolean groupsChange = desired != null && !Set.copyOf(desired).equals(Set.copyOf(groupsBefore));
ObjectNode saved = MAPPER.createObjectNode().put("region", ctx.region());
if (groupsChange) {
ArrayNode priorGroups = saved.putArray("vpcSecurityGroups");
groupsBefore.forEach(priorGroups::add);
}
saved.put("otherChanges", !stateBefore.sameSettingsAs(DbInstanceInPlaceState.of(instance)));
r.getAttributes().put(DB_INSTANCE_PRIOR_IN_PLACE_ATTR, saved.toString());
if (groupsChange) {
rdsService.setDbInstanceVpcSecurityGroups(ctx.region(), id, desired);
}
}
/**
* What an update that keeps a DB instance can change on it: the settings it hands
* {@code modifyDbInstance}, the roles, and the VPC security groups, copied so the instance's later
* changes do not reach them. Only the groups have a rollback here.
*/
private record DbInstanceInPlaceState(String masterPassword, boolean iamAuthentication, String subnetGroup,
String caCertificate, Set<String> roles, List<String> vpcSecurityGroups) {
static DbInstanceInPlaceState of(DbInstance instance) {
Set<String> roles = new HashSet<>();
for (DbRoleAssociation role : instance.getAssociatedRoles()) {
roles.add(role.getRoleArn() + " " + blankToNull(role.getFeatureName()));
}
return new DbInstanceInPlaceState(instance.getMasterPassword(),
instance.isIamDatabaseAuthenticationEnabled(), instance.getDbSubnetGroupName(),
instance.getCaCertificateIdentifier(), roles, List.copyOf(instance.getVpcSecurityGroupIds()));
}
/** Whether {@code other} has the same settings and roles, whatever its groups. */
boolean sameSettingsAs(DbInstanceInPlaceState other) {
return Objects.equals(masterPassword, other.masterPassword)
&& iamAuthentication == other.iamAuthentication
&& Objects.equals(subnetGroup, other.subnetGroup)
&& Objects.equals(caCertificate, other.caCertificate)
&& roles.equals(other.roles);
}
@Override
public String toString() {
return "DbInstanceInPlaceState[groups=" + vpcSecurityGroups + "]";
}
}
/**
@@ -430,8 +617,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
id = ctx.generatePhysicalName(r.getLogicalId(), 60, true);
}
// Same re-invocation rationale as provisionDbInstance above; modifyDbCluster only reconciles
// password and IAM auth, mirroring that method's existing scope.
// Same re-invocation rationale as provisionDbInstance above; modifyDbCluster reconciles the
// password, IAM auth and the Serverless v2 scaling.
DbCluster cluster = sameNameExistingResource(priorPhysicalId, id, rdsService::getDbCluster);
String engineMode = resolveOptional(props, "EngineMode", engine);
boolean storageEncrypted = parseBoolProp(props, "StorageEncrypted", engine);
@@ -439,12 +626,10 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
Map<String, String> createOnly = dbClusterRecordedCreateOnly(props, engine);
String replacementReason = cluster == null ? null : dbClusterReplacementReason(cluster,
engineMode, storageEncrypted, databaseName,
readDbClusterCreateOnly(attributesBefore.get(DB_CLUSTER_CREATE_ONLY_ATTR)), createOnly);
readDbClusterCreateOnly(DB_CLUSTER_CREATE_ONLY.read(attributesBefore)), createOnly);
if (replacementReason != null) {
if (customNamed) {
throw new AwsException("ValidationError",
"CloudFormation cannot update a stack when a custom-named resource requires "
+ "replacing. Rename " + id + " and update the stack again.", 400);
throw CfnExceptions.customNamedReplacement(id);
}
id = ctx.generatePhysicalName(r.getLogicalId(), 60, true);
LOG.infov("Replacing DB cluster {0} with {1}: {2}", priorPhysicalId, id, replacementReason);
@@ -486,7 +671,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
serverlessV2MinCapacity, serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause,
false, null, engineMode, storageEncrypted);
}
cluster = reconcileClusterRoles(r, cluster, roles, created, ctx.isUpdate(), region);
cluster = reconcileClusterRoles(r, cluster, roles, created, region);
ASSOCIATED_ROLES.record(r, ctx, attributesBefore, associatedRolesRecord(roles));
// EnableHttpEndpoint updates with no interruption; a template that leaves it out wants it off.
if (httpEndpoint != cluster.isHttpEndpointEnabled()) {
cluster = rdsService.setHttpEndpoint(region, cluster.getDbClusterIdentifier(), httpEndpoint);
@@ -554,7 +740,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
* this template adds are associated.
*/
private DbCluster reconcileClusterRoles(StackResource r, DbCluster cluster, List<DbRoleAssociation> roles,
boolean created, boolean update, String region) {
boolean created, String region) {
String id = cluster.getDbClusterIdentifier();
if (created) {
if (!roles.isEmpty()) {
@@ -581,7 +767,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
// A role the last template already declared is left as it is. One the template newly
// declares is always added, so a role attached by hand first fails the update with
// DBClusterRoleAlreadyExists, as it does on AWS.
List<DbRoleAssociation> declared = readAssociatedRoles(r.getAttributes().get(ASSOCIATED_ROLES_ATTR));
List<DbRoleAssociation> declared = readAssociatedRoles(ASSOCIATED_ROLES.read(r.getAttributes()));
for (DbRoleAssociation role : roles) {
if (!containsRole(declared, role) || !containsRole(cluster.getAssociatedRoles(), role)) {
cluster = rdsService.addRoleToDbCluster(region, id, role.getRoleArn(), role.getFeatureName());
@@ -593,13 +779,12 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
throw e;
}
}
recordAssociatedRoles(r, roles, update);
return cluster;
}
/** As {@link #reconcileClusterRoles}, for an instance; each role is added on its own. */
private DbInstance reconcileInstanceRoles(StackResource r, DbInstance instance, List<DbRoleAssociation> roles,
boolean created, boolean update, String region) {
boolean created, String region) {
String id = instance.getDbInstanceIdentifier();
if (created) {
try {
@@ -635,7 +820,6 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
throw e;
}
}
recordAssociatedRoles(r, roles, update);
return instance;
}
@@ -698,7 +882,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
/** The roles the last template declared that this one does not. */
private static List<DbRoleAssociation> droppedRoles(StackResource r, List<DbRoleAssociation> roles) {
List<DbRoleAssociation> dropped = new ArrayList<>();
for (DbRoleAssociation previous : readAssociatedRoles(r.getAttributes().get(ASSOCIATED_ROLES_ATTR))) {
for (DbRoleAssociation previous : readAssociatedRoles(ASSOCIATED_ROLES.read(r.getAttributes()))) {
if (!containsRole(roles, previous)) {
dropped.add(previous);
}
@@ -716,11 +900,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
return value == null || value.isBlank() ? null : value;
}
private static void recordAssociatedRoles(StackResource r, List<DbRoleAssociation> roles, boolean update) {
String priorRecord = r.getAttributes().get(ASSOCIATED_ROLES_ATTR);
if (update && !r.getAttributes().containsKey(ASSOCIATED_ROLES_PRIOR_ATTR)) {
r.getAttributes().put(ASSOCIATED_ROLES_PRIOR_ATTR, priorRecord == null ? "" : priorRecord);
}
private static String associatedRolesRecord(List<DbRoleAssociation> roles) {
ArrayNode record = MAPPER.createArrayNode();
for (DbRoleAssociation role : roles) {
ObjectNode entry = record.addObject().put("RoleArn", role.getRoleArn());
@@ -728,7 +908,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
entry.put("FeatureName", role.getFeatureName());
}
}
r.getAttributes().put(ASSOCIATED_ROLES_ATTR, record.toString());
return record.toString();
}
private static List<DbRoleAssociation> readAssociatedRoles(String raw) {
@@ -809,20 +989,21 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
}
/**
* Writes the createOnly record the next update compares against. On an update that changed it
* (a replacement, or the first record of a resource that predates it) the previous record is
* kept beside it until the update commits, so {@link #rollbackUpdate} can put it back.
* Writes the createOnly record the next update compares against. An update that leaves it as it
* was writes nothing. One that changed it (a replacement, or the first record of a resource that
* predates it) keeps the previous record beside it until the update commits, so
* {@link #rollbackUpdate} can put it back.
*/
private static void recordDbClusterCreateOnly(StackResource r, ProvisionContext ctx,
Map<String, String> attributesBefore,
Map<String, String> createOnly) {
String priorRecord = attributesBefore.get(DB_CLUSTER_CREATE_ONLY_ATTR);
if (ctx.isUpdate() && !createOnly.equals(readDbClusterCreateOnly(priorRecord))) {
r.getAttributes().put(DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR, priorRecord == null ? "" : priorRecord);
Map<String, String> recorded = readDbClusterCreateOnly(DB_CLUSTER_CREATE_ONLY.read(attributesBefore));
if (ctx.isUpdate() && createOnly.equals(recorded)) {
return;
}
ObjectNode record = MAPPER.createObjectNode();
createOnly.forEach(record::put);
r.getAttributes().put(DB_CLUSTER_CREATE_ONLY_ATTR, record.toString());
DB_CLUSTER_CREATE_ONLY.record(r, ctx, attributesBefore, record.toString());
}
/** The record as a map, or null when the resource carries none or it cannot be read. */
@@ -1090,12 +1271,17 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
* {@code ValidationError} rather than a silent false.
*/
private boolean parseStrictBoolProp(JsonNode props, String name, CloudFormationTemplateEngine engine) {
return Boolean.TRUE.equals(parseOptionalStrictBoolProp(props, name, engine));
}
/** As {@link #parseStrictBoolProp}, with null for a property the template leaves out. */
private Boolean parseOptionalStrictBoolProp(JsonNode props, String name, CloudFormationTemplateEngine engine) {
if (props == null || !props.has(name)) {
return false;
return null;
}
JsonNode value = engine.resolveNodeOmittingNoValue(props.get(name));
if (value == null || value.isMissingNode() || value.isNull()) {
return false;
return null;
}
if (value.isBoolean()) {
return value.booleanValue();
@@ -3968,6 +3968,38 @@ public class RdsService implements Resettable, ResourceProvider {
return instance;
}
/**
* Gives a DB instance exactly the VPC security groups {@code groupIds}, as CloudFormation sets
* them on an update and puts them back on a rollback. ModifyDBInstance keeps the groups when the
* request names none; here an empty list leaves the instance with none, as one created without.
*/
public synchronized DbInstance setDbInstanceVpcSecurityGroups(String region, String instanceId,
List<String> groupIds) {
String effectiveRegion = effectiveRegion(region);
DbInstance instance = getDbInstance(instanceId, effectiveRegion);
requireAvailableInstance(instance, instanceId);
instance.setVpcSecurityGroupIds(groupIds);
putInstanceForScope(currentAccountId(), effectiveRegion, instanceId, instance);
LOG.infov("DB instance {0} security groups set to {1}", instanceId, groupIds);
return RESPONSE_COPIER.convertValue(instance, DbInstance.class);
}
/**
* The groups AWS's CloudFormation handler gives a standalone DB instance whose template stops
* declaring {@code VPCSecurityGroups}: the default security group of its VPC, or none when EC2
* has no default group for it.
*/
public List<String> defaultVpcSecurityGroupIds(String region, String instanceId) {
String effectiveRegion = effectiveRegion(region);
String vpcId = getDbInstance(instanceId, effectiveRegion).getVpcId();
if (isBlank(vpcId)) {
return List.of();
}
return ec2Service.defaultSecurityGroupOf(effectiveRegion, vpcId)
.map(group -> List.of(group.getGroupId()))
.orElse(List.of());
}
private static void validateInstanceSettings(DbInstanceSettings settings) {
settings.validate();
}
@@ -383,38 +383,29 @@ class CloudFormationEc2InstanceIntegrationTest {
String stackName = "cfn-ec2-lt-profile-" + Long.toString(System.nanoTime(), 36);
try (CloudFormationClient cloudFormation = AwsTestClients.create(CloudFormationClient.builder(), "test",
Region.of(REGION))) {
cloudFormation.createStack(request -> request.stackName(stackName)
.templateBody(launchTemplateProfileStack("First", false)));
try {
Stack created = CfnStackWaits.awaitStatus(cloudFormation, stackName, "CREATE_COMPLETE");
String instanceId = CfnStackWaits.output(created, "InstanceId");
assertInstanceProfile(instanceId, CfnStackWaits.output(created, "FirstArn"));
Stack created = CfnStackWaits.createStack(cloudFormation, stackName,
launchTemplateProfileStack("First", false), "CREATE_COMPLETE");
String instanceId = CfnStackWaits.output(created, "InstanceId");
assertInstanceProfile(instanceId, CfnStackWaits.output(created, "FirstArn"));
// A template version naming another profile gives the same instance that profile, a
// failed update puts it back, and a version naming none leaves the instance without one.
Stack changed = updateStack(cloudFormation, stackName, launchTemplateProfileStack("Second", false),
"UPDATE_COMPLETE");
assertEquals(instanceId, CfnStackWaits.output(changed, "InstanceId"));
assertInstanceProfile(instanceId, CfnStackWaits.output(changed, "SecondArn"));
Stack rolledBack = updateStack(cloudFormation, stackName, launchTemplateProfileStack("First", true),
"UPDATE_ROLLBACK_COMPLETE");
assertInstanceProfile(instanceId, CfnStackWaits.output(rolledBack, "SecondArn"));
Stack cleared = updateStack(cloudFormation, stackName, launchTemplateProfileStack(null, false),
"UPDATE_COMPLETE");
assertEquals(instanceId, CfnStackWaits.output(cleared, "InstanceId"));
assertInstanceProfile(instanceId, null);
} finally {
CfnStackWaits.deleteStack(stackName, CFN_AUTH);
}
// A template version naming another profile gives the same instance that profile, a
// failed update puts it back, and a version naming none leaves the instance without one.
Stack changed = CfnStackWaits.updateStack(cloudFormation, stackName,
launchTemplateProfileStack("Second", false), "UPDATE_COMPLETE");
assertEquals(instanceId, CfnStackWaits.output(changed, "InstanceId"));
assertInstanceProfile(instanceId, CfnStackWaits.output(changed, "SecondArn"));
Stack rolledBack = CfnStackWaits.updateStack(cloudFormation, stackName,
launchTemplateProfileStack("First", true), "UPDATE_ROLLBACK_COMPLETE");
assertInstanceProfile(instanceId, CfnStackWaits.output(rolledBack, "SecondArn"));
Stack cleared = CfnStackWaits.updateStack(cloudFormation, stackName,
launchTemplateProfileStack(null, false), "UPDATE_COMPLETE");
assertEquals(instanceId, CfnStackWaits.output(cleared, "InstanceId"));
assertInstanceProfile(instanceId, null);
} finally {
CfnStackWaits.deleteStack(stackName, CFN_AUTH);
}
}
private static Stack updateStack(CloudFormationClient cloudFormation, String stackName, String template,
String expectedStatus) {
cloudFormation.updateStack(request -> request.stackName(stackName).templateBody(template));
return CfnStackWaits.awaitStatus(cloudFormation, stackName, expectedStatus);
}
/**
* An instance launched from a launch template whose IamInstanceProfile names the stack's profile
* {@code profile}, First or Second, or no profile when it is null. With {@code laterFails}, a
@@ -423,10 +414,7 @@ class CloudFormationEc2InstanceIntegrationTest {
private static String launchTemplateProfileStack(String profile, boolean laterFails) {
String member = profile == null ? "" : """
, "IamInstanceProfile": {"Name": {"Ref": "%s"}}""".formatted(profile);
String later = !laterFails ? "" : """
,
"Later": {"Type": "AWS::EC2::Instance", "DependsOn": "Server", "Properties": {"LaunchTemplate": {
"LaunchTemplateId": "lt-0123456789abcdef0", "Version": "1"}}}""";
String later = laterFails ? CfnStackWaits.failingResourceAfter("Server") : "";
return """
{"Resources": {
"Role": {"Type": "AWS::IAM::Role", "Properties": {"AssumeRolePolicyDocument": {
@@ -320,24 +320,17 @@ class CloudFormationEc2MetadataOptionsIntegrationTest {
"Outputs": {"InstanceId": {"Value": {"Ref": "Inst"}}}
}
""".formatted(createdOptions);
// The second instance names a launch template that does not exist, so it fails after Inst
// has been updated, which it depends on.
String failing = """
{
"Resources": {
"Inst": {
"Type": "AWS::EC2::Instance",
"Properties": {"ImageId": "ami-12345678", "MetadataOptions": {"HttpTokens": "%s"}}
},
"Later": {
"Type": "AWS::EC2::Instance",
"DependsOn": "Inst",
"Properties": {"LaunchTemplate": {"LaunchTemplateId": "lt-0123456789abcdef0", "Version": "1"}}
}
}%s
},
"Outputs": {"InstanceId": {"Value": {"Ref": "Inst"}}}
}
""".formatted(updatedTokens);
""".formatted(updatedTokens, CfnStackWaits.failingResourceAfter("Inst"));
try {
cfn("CreateStack", stackName, created);
String instanceId = output(describeStack(stackName, "CREATE_COMPLETE"), "InstanceId");
@@ -0,0 +1,150 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.CfnStackWaits;
import io.floci.aws.testing.RdsMockProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
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.cloudformation.model.Stack;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.DBInstance;
import software.amazon.awssdk.services.rds.model.VpcSecurityGroupMembership;
import java.util.List;
import static io.floci.aws.testing.CfnStackWaits.output;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
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 and when the
* template drops them, and a change of {@code StorageEncrypted} either way replaces the instance.
*/
@QuarkusTest
@TestProfile(RdsMockProfile.class)
class CloudFormationRdsDbInstanceIntegrationTest {
private final String stackName = "cfn-rds-db-" + Long.toString(System.nanoTime(), 36);
private CloudFormationClient cloudFormation;
private RdsClient rds;
@BeforeEach
void clients() {
cloudFormation = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1);
rds = AwsTestClients.create(RdsClient.builder(), "test", Region.US_EAST_1);
}
@AfterEach
void deleteStack() {
try {
CfnStackWaits.deleteStack(stackName);
} finally {
cloudFormation.close();
rds.close();
}
}
@Test
void securityGroupsFollowTheTemplateThroughChangeRollbackAndRemoval() {
Stack created = create(template("First", false, false));
String id = output(created, "DbId");
assertEquals(List.of(output(created, "FirstId")), groups(id));
Stack changed = update(template("Second", false, false), "UPDATE_COMPLETE");
assertEquals(id, output(changed, "DbId"));
assertEquals(List.of(output(changed, "SecondId")), groups(id));
update(template("First", false, true), "UPDATE_ROLLBACK_COMPLETE");
assertEquals(List.of(output(changed, "SecondId")), groups(id));
// As AWS's handler does, a template that drops the groups puts the instance on its VPC's default group.
Stack cleared = update(template(null, false, false), "UPDATE_COMPLETE");
assertEquals(id, output(cleared, "DbId"));
assertEquals(List.of(defaultGroupOf(instance(id).dbSubnetGroup().vpcId())), groups(id));
}
@Test
void aStorageEncryptedChangeReplacesTheInstanceAndAFailedOneKeepsIt() {
String id = output(create(template(null, true, false)), "DbId");
assertTrue(instance(id).storageEncrypted());
// Dropping StorageEncrypted asks for an unencrypted instance, which only a new one can be.
update(template(null, false, true), "UPDATE_ROLLBACK_COMPLETE");
assertEquals(List.of(id), stackInstanceIds(), "the replacement is deleted again");
assertTrue(instance(id).storageEncrypted());
String unencrypted = output(update(template(null, false, false), "UPDATE_COMPLETE"), "DbId");
assertNotEquals(id, unencrypted);
assertFalse(instance(unencrypted).storageEncrypted());
assertEquals(List.of(unencrypted), stackInstanceIds(), "the prior instance is deleted once the update commits");
String encrypted = output(update(template(null, true, false), "UPDATE_COMPLETE"), "DbId");
assertNotEquals(unencrypted, encrypted);
assertTrue(instance(encrypted).storageEncrypted());
assertEquals(List.of(encrypted), stackInstanceIds());
}
private Stack create(String template) {
return CfnStackWaits.createStack(cloudFormation, stackName, template, "CREATE_COMPLETE");
}
private Stack update(String template, String expectedStatus) {
return CfnStackWaits.updateStack(cloudFormation, stackName, template, expectedStatus);
}
/**
* Two security groups and a DB instance on {@code group}, First or Second, 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}.
*/
private static String template(String group, boolean encrypted, boolean laterFails) {
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"}},
"Db": {"Type": "AWS::RDS::DBInstance", "Properties": {"Engine": "postgres",
"DBInstanceClass": "db.t3.micro", "AllocatedStorage": 20, "MasterUsername": "dbadmin",
"MasterUserPassword": "password123"%s%s}}%s
}, "Outputs": {
"DbId": {"Value": {"Ref": "Db"}},
"FirstId": {"Value": {"Fn::GetAtt": ["First", "GroupId"]}},
"SecondId": {"Value": {"Fn::GetAtt": ["Second", "GroupId"]}}
}}
""".formatted(groups, encrypted ? ", \"StorageEncrypted\": true" : "",
laterFails ? CfnStackWaits.failingResourceAfter("Db") : "");
}
private DBInstance instance(String id) {
return rds.describeDBInstances(request -> request.dbInstanceIdentifier(id)).dbInstances().getFirst();
}
private List<String> groups(String id) {
return instance(id).vpcSecurityGroups().stream().map(VpcSecurityGroupMembership::vpcSecurityGroupId).toList();
}
/** The instances this stack's {@code Db} resource has, by the name CloudFormation generates for it. */
private List<String> stackInstanceIds() {
return rds.describeDBInstances().dbInstances().stream().map(DBInstance::dbInstanceIdentifier)
.filter(id -> id.startsWith(stackName + "-db-")).toList();
}
private static String defaultGroupOf(String vpcId) {
try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) {
return ec2.describeSecurityGroups(request -> request.filters(
filter -> filter.name("vpc-id").values(vpcId),
filter -> filter.name("group-name").values("default")))
.securityGroups().getFirst().groupId();
}
}
}
@@ -34,14 +34,17 @@ import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
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.assertNotEquals;
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.anyBoolean;
@@ -135,20 +138,45 @@ class RdsCfnProvisionerTest {
/** Any {@code createDbInstance} call returns {@code instance}. */
private void stubCreateDbInstance(DbInstance instance) {
stubCreateDbInstance(invocation -> instance);
}
private void stubCreateDbInstance(Answer<DbInstance> answer) {
when(rdsService.createDbInstance(any(), any(), any(), any(), any(), any(), any(),
anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(),
any(), anyMap(), anyList(), nullable(String.class), nullable(String.class),
anyBoolean(), any(DbInstanceSettings.class))).thenReturn(instance);
anyBoolean(), any(DbInstanceSettings.class))).thenAnswer(answer);
}
/** Any {@code createDbInstance} call returns an instance named {@code id}, which this returns. */
private DbInstance stubCreatedInstance(String id) {
DbInstance created = dbInstance(id);
stubCreateDbInstance(created);
return created;
}
/** RdsService has an instance named {@code id} on file and hands it back from an in-place modify. */
private DbInstance stubInstanceOnFile(String id) {
DbInstance onFile = dbInstance(id);
when(rdsService.getDbInstance(id)).thenReturn(onFile);
when(rdsService.modifyDbInstance(eq(id), any(), any(), any(), any(), any(), any(), any(),
any(DbInstanceSettings.class))).thenReturn(onFile);
return onFile;
}
/** A DB instance named {@code id}; stubbed with doReturn so it can be built inside an Answer. */
private static DbInstance dbInstance(String id) {
DbInstance instance = mock(DbInstance.class);
doReturn(id).when(instance).getDbInstanceIdentifier();
return instance;
}
@Test
void provisionsDbInstanceWithMappedArgsAndEndpointAttributes() {
DbInstance instance = mock(DbInstance.class);
when(instance.getDbInstanceIdentifier()).thenReturn("mydb");
DbInstance instance = stubCreatedInstance("mydb");
when(instance.getEndpoint()).thenReturn(new DbEndpoint("mydb.local", 5432));
when(instance.getDbInstanceArn()).thenReturn("arn:aws:rds:us-east-1:000000000000:db:mydb");
when(instance.getDbiResourceId()).thenReturn("db-ABCDEFGHIJKLMNOP");
stubCreateDbInstance(instance);
StackResource r = provision("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres","EngineVersion":"16",
@@ -173,9 +201,7 @@ class RdsCfnProvisionerTest {
@Test
void aDbInstanceTakesItsCaCertificateAndExposesItsDetails() {
DbInstance instance = mock(DbInstance.class);
when(instance.getDbInstanceIdentifier()).thenReturn("mydb");
stubCreateDbInstance(instance);
DbInstance instance = stubCreatedInstance("mydb");
when(rdsService.instanceCertificate(instance)).thenReturn(
new RdsService.InstanceCertificate("rds-ca-ecc384-g1", Instant.parse("2121-05-25T23:41:55Z")));
@@ -195,9 +221,7 @@ class RdsCfnProvisionerTest {
@Test
void deletesANewDbInstanceWhoseAssociatedRolesAreRefused() {
DbInstance instance = mock(DbInstance.class);
when(instance.getDbInstanceIdentifier()).thenReturn("mydb");
stubCreateDbInstance(instance);
DbInstance instance = stubCreatedInstance("mydb");
when(rdsService.addRoleToDbInstance("us-east-1", "mydb", "arn:aws:iam::000000000000:role/a", "s3Import"))
.thenReturn(instance);
when(rdsService.addRoleToDbInstance("us-east-1", "mydb", "arn:aws:iam::000000000000:role/b", "s3Import"))
@@ -217,9 +241,7 @@ class RdsCfnProvisionerTest {
@Test
void provisionsDbInstanceInStackRegion() {
DbInstance instance = mock(DbInstance.class);
when(instance.getDbInstanceIdentifier()).thenReturn("mydb");
stubCreateDbInstance(instance);
stubCreatedInstance("mydb");
provision("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres","MasterUsername":"admin",
@@ -437,9 +459,7 @@ class RdsCfnProvisionerTest {
"{\"username\":\"resolved-user\",\"password\":\"resolved-secret\"}");
when(secretsManagerService.getSecretValue(any(), any(), any(), any())).thenReturn(version);
DbInstance instance = mock(DbInstance.class);
when(instance.getDbInstanceIdentifier()).thenReturn("mydb");
stubCreateDbInstance(instance);
stubCreatedInstance("mydb");
provision("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres",
@@ -722,9 +742,7 @@ class RdsCfnProvisionerTest {
Parameter param = new Parameter("/db/password", "resolved-secure", "SecureString");
when(ssmService.getParameter("/db/password", "us-east-1")).thenReturn(param);
DbInstance instance = mock(DbInstance.class);
when(instance.getDbInstanceIdentifier()).thenReturn("mydb");
stubCreateDbInstance(instance);
stubCreatedInstance("mydb");
StackResource resource = provision("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres",
@@ -1408,12 +1426,7 @@ class RdsCfnProvisionerTest {
@Test
void updateStackReconcilesExistingDbInstanceInsteadOfRecreating() {
DbInstance existing = mock(DbInstance.class);
when(rdsService.getDbInstance("mydb")).thenReturn(existing);
DbInstance reconciled = mock(DbInstance.class);
when(reconciled.getDbInstanceIdentifier()).thenReturn("mydb");
when(rdsService.modifyDbInstance(eq("mydb"), any(), any(), any(), any(), any(), any(), any(),
any(DbInstanceSettings.class))).thenReturn(reconciled);
stubInstanceOnFile("mydb");
StackResource r = provisionUpdate("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres","MasterUsername":"admin",
@@ -1431,11 +1444,7 @@ class RdsCfnProvisionerTest {
@Test
void updateStackChangesAnExistingDbInstancesCaCertificate() {
when(rdsService.getDbInstance("mydb")).thenReturn(mock(DbInstance.class));
DbInstance reconciled = mock(DbInstance.class);
when(reconciled.getDbInstanceIdentifier()).thenReturn("mydb");
when(rdsService.modifyDbInstance(eq("mydb"), any(), any(), any(), any(), any(), any(), any(),
any(DbInstanceSettings.class))).thenReturn(reconciled);
stubInstanceOnFile("mydb");
provisionUpdate("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres","MasterUsername":"admin",
@@ -1614,17 +1623,11 @@ class RdsCfnProvisionerTest {
String old = "arn:aws:iam::000000000000:role/old";
String lambda = "arn:aws:iam::000000000000:role/lambda";
String refused = "arn:aws:iam::000000000000:role/refused";
DbInstance before = mock(DbInstance.class);
when(before.getDbInstanceIdentifier()).thenReturn("mydb");
DbInstance before = stubInstanceOnFile("mydb");
when(before.getAssociatedRoles()).thenReturn(List.of(new DbRoleAssociation(old, "s3Import")));
DbInstance withoutOld = mock(DbInstance.class);
when(withoutOld.getDbInstanceIdentifier()).thenReturn("mydb");
DbInstance withLambda = mock(DbInstance.class);
when(withLambda.getDbInstanceIdentifier()).thenReturn("mydb");
DbInstance withoutOld = dbInstance("mydb");
DbInstance withLambda = dbInstance("mydb");
when(withLambda.getAssociatedRoles()).thenReturn(List.of(new DbRoleAssociation(lambda, "Lambda")));
when(rdsService.getDbInstance("mydb")).thenReturn(before);
when(rdsService.modifyDbInstance(eq("mydb"), any(), any(), any(), any(), any(), any(), any(),
any(DbInstanceSettings.class))).thenReturn(before);
when(rdsService.removeRoleFromDbInstance("us-east-1", "mydb", old, "s3Import")).thenReturn(withoutOld);
when(rdsService.addRoleToDbInstance("us-east-1", "mydb", lambda, "Lambda")).thenReturn(withLambda);
when(rdsService.addRoleToDbInstance("us-east-1", "mydb", refused, "s3Export"))
@@ -1632,7 +1635,7 @@ class RdsCfnProvisionerTest {
StackResource r = provisionExisting("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres","MasterUsername":"admin",
"MasterUserPassword":"secret","AssociatedRoles":[
"MasterUserPassword":"secret","VPCSecurityGroups":["sg-new"],"AssociatedRoles":[
{"RoleArn":"arn:aws:iam::000000000000:role/lambda","FeatureName":"Lambda"},
{"RoleArn":"arn:aws:iam::000000000000:role/refused","FeatureName":"s3Export"}]}
""", "us-east-1", "mydb", Map.of("DBInstanceIdentifier", "mydb",
@@ -1643,15 +1646,16 @@ class RdsCfnProvisionerTest {
undo.verify(rdsService).removeRoleFromDbInstance("us-east-1", "mydb", lambda, "Lambda");
undo.verify(rdsService).addRoleToDbInstance("us-east-1", "mydb", old, "s3Import");
verify(rdsService, never()).deleteDbInstance(any(), any());
// The groups change last, so the engine, which restores this resource without calling
// rollbackUpdate, is right that the instance still has the groups it had.
verify(rdsService, never()).setDbInstanceVpcSecurityGroups(any(), any(), any());
}
@Test
void renamedDbInstanceKeepsItsPredecessorWhenTheNewRolesAreRefused() {
// The roles go on before the renamed instance's predecessor is deleted, so a refused list
// costs only the new instance.
DbInstance renamed = mock(DbInstance.class);
when(renamed.getDbInstanceIdentifier()).thenReturn("newdb");
stubCreateDbInstance(renamed);
stubCreatedInstance("newdb");
when(rdsService.addRoleToDbInstance(any(), eq("newdb"), any(), any()))
.thenThrow(new AwsException("InvalidParameterValue", "feature not supported", 400));
@@ -1716,12 +1720,16 @@ class RdsCfnProvisionerTest {
}
@Test
void dbClusterCleanupTreatsAnAlreadyGoneClusterAsDeleted() {
void replacementCleanupTreatsAnAlreadyGoneClusterOrInstanceAsDeleted() {
doThrow(new AwsException("DBClusterNotFoundFault", "DB cluster gone not found.", 404))
.when(rdsService).deleteDbCluster("gone", "us-east-1");
doThrow(new AwsException("DBInstanceNotFound", "DB instance gone not found.", 404))
.when(rdsService).deleteDbInstance("gone", "us-east-1");
assertDoesNotThrow(() -> provisioner.delete("AWS::RDS::DBCluster", "gone", "us-east-1"));
assertDoesNotThrow(() -> provisioner.delete("AWS::RDS::DBInstance", "gone", "us-east-1"));
verify(rdsService).deleteDbCluster("gone", "us-east-1");
verify(rdsService).deleteDbInstance("gone", "us-east-1");
}
@Test
@@ -2057,6 +2065,309 @@ class RdsCfnProvisionerTest {
verify(rdsService, never()).modifyDbCluster(any(), any(), any(), any(), any(), any(), any());
}
// ── VPCSecurityGroups and StorageEncrypted of AWS::RDS::DBInstance ──
private static final String ENCRYPTION_ATTR = "__FlociDbInstanceStorageEncrypted";
private static final String IN_PLACE_ATTR = "__FlociDbInstancePriorInPlaceUpdate";
private static final String PLAIN = "{\"Engine\":\"postgres\"}";
private static final String SG_FIRST = "{\"Engine\":\"postgres\",\"VPCSecurityGroups\":[\"sg-first\"]}";
private static final String SG_SECOND = "{\"Engine\":\"postgres\",\"VPCSecurityGroups\":[\"sg-second\"]}";
private static final String ENCRYPTED = "{\"Engine\":\"postgres\",\"StorageEncrypted\":true}";
private static final String MEMBER = "{\"DBClusterIdentifier\":\"cluster\"";
/** What one {@code createDbInstance} call asked for, of what these tests read. */
private record CreateRequest(String id, List<String> groups, DbInstanceSettings settings) { }
/**
* A DB instance a CreateStack of {@code template} left on file as {@code onFile}, and every
* {@code createDbInstance} call made since, that one first.
*/
private record Created(StackResource resource, String id, String template, DbInstance onFile,
List<CreateRequest> requests) { }
/**
* A CreateStack of the unnamed instance {@code json}. RdsService then has it on file with
* {@code groupsOnFile}, and modifies it in place without changing anything else.
*/
private Created createInstance(String json, String... groupsOnFile) {
List<CreateRequest> requests = new ArrayList<>();
stubCreateDbInstance(invocation -> {
requests.add(new CreateRequest(invocation.getArgument(0), invocation.getArgument(17),
invocation.getArgument(21)));
return dbInstance(invocation.getArgument(0));
});
StackResource created = provision("Db", "AWS::RDS::DBInstance", json);
assertEquals("CREATE_COMPLETE", created.getStatus(), created.getStatusReason());
DbInstance onFile = stubInstanceOnFile(created.getPhysicalId());
when(onFile.getVpcSecurityGroupIds()).thenReturn(List.of(groupsOnFile));
return new Created(created, created.getPhysicalId(), json, onFile, requests);
}
/** 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",
"000000000000", "my-stack", created.id(), created.resource().getAttributes(), event -> { },
props(created.template()));
}
/** An instance created on {@code sg-first}, then updated to {@code json}; it is kept, under the same id. */
private StackResource updateFromFirstGroup(String json) {
return updateFromFirstGroup(json, created -> { });
}
/** As {@link #updateFromFirstGroup(String)}, with {@code beforeUpdate} given the created instance first. */
private StackResource updateFromFirstGroup(String json, Consumer<Created> beforeUpdate) {
Created created = createInstance(SG_FIRST, "sg-first");
beforeUpdate.accept(created);
return updateInstance(created, json);
}
/** An instance created encrypted, then replaced by an update that drops StorageEncrypted. */
private Created replaceEncryptedInstance() {
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());
}
/** How many times the provisioner asked RdsService to modify an instance, whatever the arguments. */
private long modifyCalls() {
return Mockito.mockingDetails(rdsService).getInvocations().stream()
.filter(invocation -> invocation.getMethod().getName().equals("modifyDbInstance"))
.count();
}
@Test
void aDbInstanceIsCreatedWithItsVpcSecurityGroupsAndStorageEncrypted() {
Created created = createInstance("""
{"Engine":"postgres","VPCSecurityGroups":["sg-first","sg-second"],"StorageEncrypted":true}
""");
assertEquals(List.of(new CreateRequest(created.id(), List.of("sg-first", "sg-second"),
new DbInstanceSettings(true, null, null, null, null, null))), created.requests());
assertEquals("true", created.resource().getAttributes().get(ENCRYPTION_ATTR));
}
@Test
void aMalformedStorageEncryptedFailsInsteadOfLeavingTheInstanceUnencrypted() {
stubCreateDbInstance(mock(DbInstance.class));
StackResource r = provision("Db", "AWS::RDS::DBInstance", """
{"Engine":"postgres","StorageEncrypted":"yes"}
""");
assertEquals("CREATE_FAILED", r.getStatus());
assertTrue(r.getStatusReason().contains("StorageEncrypted must be true or false"), r.getStatusReason());
}
/** Every group the instance had comes back, however many, and an instance that had none gets none. */
@ParameterizedTest
@ValueSource(strings = {"sg-first", "sg-first,sg-other", ""})
void anUpdateMovesTheInstanceToTheNewGroupsLastAndARollbackPutsTheOldOnesBack(String groupsOnFile) {
String[] before = groupsOnFile.isEmpty() ? new String[0] : groupsOnFile.split(",");
StackResource r = updateInstance(createInstance(PLAIN, before), SG_SECOND);
assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());
InOrder order = inOrder(rdsService);
order.verify(rdsService).modifyDbInstance(eq(r.getPhysicalId()), any(), any(), any(), any(), any(), any(),
any(), any(DbInstanceSettings.class));
order.verify(rdsService).setDbInstanceVpcSecurityGroups("us-east-1", r.getPhysicalId(), List.of("sg-second"));
assertTrue(provisioner.rollbackUpdate(r), "the groups were all the update changed");
verify(rdsService).setDbInstanceVpcSecurityGroups("us-east-1", r.getPhysicalId(), List.of(before));
assertFalse(r.getAttributes().containsKey(IN_PLACE_ATTR));
}
@Test
void droppedGroupsPutTheInstanceOnItsVpcsDefaultGroupAndARollbackPutsThemBack() {
when(rdsService.defaultVpcSecurityGroupIds(eq("us-east-1"), any())).thenReturn(List.of("sg-default"));
StackResource r = updateFromFirstGroup(PLAIN);
verify(rdsService).setDbInstanceVpcSecurityGroups("us-east-1", r.getPhysicalId(), List.of("sg-default"));
assertTrue(provisioner.rollbackUpdate(r));
verify(rdsService).setDbInstanceVpcSecurityGroups("us-east-1", r.getPhysicalId(), List.of("sg-first"));
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
PLAIN + " | " + PLAIN + " | sg-default",
MEMBER + ",\"VPCSecurityGroups\":[\"sg-first\"]} | " + MEMBER + "} | sg-default",
SG_FIRST + " | " + PLAIN + " |"
})
void theGroupsStayWhenTheTemplateNeverDeclaredThemAMemberDropsThemOrTheVpcHasNoDefault(
String template, String updated, String defaultGroup) {
// AWS's handler gives the VPC's default group only to a standalone instance whose previous
// template declared groups, and only when there is such a group; a member's are its cluster's.
when(rdsService.defaultVpcSecurityGroupIds(eq("us-east-1"), any()))
.thenReturn(defaultGroup == null ? List.of() : List.of(defaultGroup));
Created created = createInstance(template, "sg-manual");
StackResource r = updateInstance(created, updated);
assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());
verify(rdsService, never()).setDbInstanceVpcSecurityGroups(any(), any(), any());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
MEMBER + ",\"VPCSecurityGroups\":[\"sg-first\"]} | " + MEMBER + ",\"VPCSecurityGroups\":[\"sg-second\"]}",
MEMBER + "} | " + MEMBER + ",\"VPCSecurityGroups\":[\"sg-cluster\"]}"
})
void aClusterMemberWhoseTemplateChangesItsGroupsFailsBeforeAnythingChanges(String template, String updated) {
// 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);
assertEquals("CREATE_FAILED", r.getStatus());
assertTrue(r.getStatusReason().contains("Modify vpc security group for the DB Cluster"), r.getStatusReason());
assertEquals(0, modifyCalls());
verify(rdsService, never()).setDbInstanceVpcSecurityGroups(any(), any(), any());
}
@Test
void aClusterMemberWhoseTemplateKeepsItsGroupsIsGivenThemAndNotRefused() {
// A member a stack created before Floci applied VPCSecurityGroups has none of them on file, but
// its template did not change them, so AWS's handler would send RDS nothing to refuse.
String template = MEMBER + ",\"VPCSecurityGroups\":[\"sg-first\"]}";
StackResource r = updateInstance(createInstance(template), template);
assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());
verify(rdsService).setDbInstanceVpcSecurityGroups("us-east-1", r.getPhysicalId(), List.of("sg-first"));
}
@Test
void aRollbackOfAnUpdateThatAlsoChangedOtherSettingsPutsTheGroupsBackButIsNotComplete() {
// The instance reports IAM authentication off when the update starts and on once modified.
StackResource r = updateFromFirstGroup("""
{"Engine":"postgres","VPCSecurityGroups":["sg-second"],"EnableIAMDatabaseAuthentication":true}
""", created -> when(created.onFile().isIamDatabaseAuthenticationEnabled()).thenReturn(false, true));
assertFalse(provisioner.rollbackUpdate(r), "IAM authentication has no rollback here");
verify(rdsService).setDbInstanceVpcSecurityGroups("us-east-1", r.getPhysicalId(), List.of("sg-first"));
}
@Test
void aRollbackThatFindsTheInstanceGoneFailsAndKeepsWhatItOwes() {
StackResource r = updateFromFirstGroup(SG_SECOND);
doThrow(new AwsException("DBInstanceNotFound", "DB instance not found.", 404))
.when(rdsService).setDbInstanceVpcSecurityGroups("us-east-1", r.getPhysicalId(), List.of("sg-first"));
AwsException failure = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
assertEquals("DBInstanceNotFound", failure.getErrorCode());
assertTrue(r.getAttributes().containsKey(IN_PLACE_ATTR), "a retried rollback tries again");
}
@Test
void aCommittedInPlaceUpdateDropsWhatARollbackWouldHavePutBack() {
// An in-place update owes no cleanup, so the engine calls completeUpdate and not clearUpdate;
// a record left here would be put back by the rollback of the next update.
StackResource r = updateFromFirstGroup(SG_SECOND);
assertTrue(r.getAttributes().containsKey("__FlociAssociatedRolesPrior"));
assertFalse(provisioner.completeUpdate(r).applicable());
assertFalse(r.getAttributes().containsKey("__FlociAssociatedRolesPrior"));
assertFalse(r.getAttributes().containsKey(ENCRYPTION_ATTR + "Prior"));
assertFalse(r.getAttributes().containsKey(IN_PLACE_ATTR));
}
@Test
void aRollbackPutsBackTheRolesRecordTheUpdateFoundAndNotOneAnOlderFlociLeftBehind() {
// Before completeUpdate dropped it, a committed in-place update left the roles record it
// overwrote on the resource, and a stack can still carry one from then. The update found one
// record, writes another, and the rollback has to put back the one it found.
String found = "[{\"RoleArn\":\"arn:aws:iam::000000000000:role/declared\"}]";
StackResource r = updateFromFirstGroup(SG_SECOND, created -> created.resource().getAttributes().putAll(Map.of(
"__FlociAssociatedRoles", found,
"__FlociAssociatedRolesPrior", "[{\"RoleArn\":\"arn:aws:iam::000000000000:role/old\"}]")));
assertEquals("[]", r.getAttributes().get("__FlociAssociatedRoles"));
assertTrue(provisioner.rollbackUpdate(r));
assertEquals(found, r.getAttributes().get("__FlociAssociatedRoles"));
}
@Test
void aStorageEncryptedChangeCreatesTheReplacementAndDeletesTheOldInstanceOnlyOnCommit() {
// Dropping StorageEncrypted: true is the change to an unencrypted instance, which AWS can
// only make by creating another one.
Created replaced = replaceEncryptedInstance();
String replacement = replaced.resource().getPhysicalId();
assertEquals(new CreateRequest(replacement, List.of(), DbInstanceSettings.defaults()),
replaced.requests().get(1));
assertEquals(0, modifyCalls());
verify(rdsService, never()).deleteDbInstance(any(), any());
verify(rdsService, never()).deleteDbInstance(any());
verify(rdsService, never()).setDbInstanceVpcSecurityGroups(any(), any(), any());
assertEquals(replaced.id(), provisioner.updateCleanupPhysicalId(replaced.resource()));
assertTrue(provisioner.completeUpdate(replaced.resource()).complete());
verify(rdsService).deleteDbInstance(replaced.id(), "us-east-1");
assertEquals("false", replaced.resource().getAttributes().get(ENCRYPTION_ATTR));
}
@Test
void aRolledBackReplacementIsDeletedAndTheRecordFollowsTheOldInstanceBack() {
Created replaced = replaceEncryptedInstance();
String replacement = replaced.resource().getPhysicalId();
assertTrue(provisioner.rollbackUpdate(replaced.resource()));
assertEquals(replaced.id(), replaced.resource().getPhysicalId());
verify(rdsService).deleteDbInstance(replacement, "us-east-1");
verify(rdsService, never()).deleteDbInstance(replaced.id(), "us-east-1");
assertEquals("true", replaced.resource().getAttributes().get(ENCRYPTION_ATTR));
}
@Test
void aReplacementWhoseDeleteFailsStillLeavesTheRecordWithTheOldInstance() {
// The resource names the old instance again before the delete is tried, so a rollback the
// stack later skips, rather than retries, must not leave the replacement's record behind.
Created replaced = replaceEncryptedInstance();
doThrow(new AwsException("InvalidDBInstanceState", "DB instance is busy.", 400))
.when(rdsService).deleteDbInstance(replaced.resource().getPhysicalId(), "us-east-1");
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(replaced.resource()));
assertEquals(replaced.id(), replaced.resource().getPhysicalId());
assertEquals("true", replaced.resource().getAttributes().get(ENCRYPTION_ATTR));
}
@Test
void aCustomNamedInstanceRefusesAStorageEncryptedChange() {
Created created = createInstance("{\"DBInstanceIdentifier\":\"mydb\",\"Engine\":\"postgres\"}");
StackResource r = updateInstance(created, """
{"DBInstanceIdentifier":"mydb","Engine":"postgres","StorageEncrypted":true}
""");
assertEquals("CREATE_FAILED", r.getStatus());
assertTrue(r.getStatusReason().contains(
"custom-named resource requires replacing. Rename mydb and update the stack again."));
assertEquals(1, created.requests().size());
assertEquals(0, modifyCalls());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {ENCRYPTED + " | false", PLAIN + " | 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);
StackResource r = updateInstance(created, updated);
assertEquals(replaced, !created.id().equals(r.getPhysicalId()));
assertEquals(String.valueOf(!replaced), r.getAttributes().get(ENCRYPTION_ATTR));
}
@Test
void deleteDelegatesToRdsServiceForEachRdsType() {
// Stack deletion tears down RDS resources via the physical id set at provision time.
@@ -1562,7 +1562,7 @@ class RdsServiceTest {
}
@Test
void createAndModifyDbInstancePersistVpcSecurityGroups() {
void vpcSecurityGroupsPersistThroughCreateModifyAndCloudFormationsExactSet() {
DbInstance instance = rdsService.createDbInstance("mydb", "postgres", "13",
"admin", "password", "dbname", "db.t3.micro",
20, false, null, null, null, null, false, false, null,
@@ -1575,6 +1575,17 @@ class RdsServiceTest {
assertEquals(List.of("sg-updated-a", "sg-updated-b"), modified.getVpcSecurityGroupIds());
assertEquals(List.of("sg-updated-a", "sg-updated-b"), rdsService.getDbInstance("mydb").getVpcSecurityGroupIds());
// ModifyDBInstance cannot leave an instance without groups; CloudFormation's rollback can.
assertEquals(List.of(), rdsService.setDbInstanceVpcSecurityGroups("us-east-1", "mydb", List.of())
.getVpcSecurityGroupIds());
assertEquals(List.of(), rdsService.getDbInstance("mydb").getVpcSecurityGroupIds());
SecurityGroup defaultGroup = new SecurityGroup();
defaultGroup.setGroupId("sg-default");
when(ec2Service.defaultSecurityGroupOf("us-east-1", rdsService.getDbInstance("mydb").getVpcId()))
.thenReturn(Optional.of(defaultGroup));
assertEquals(List.of("sg-default"), rdsService.defaultVpcSecurityGroupIds("us-east-1", "mydb"));
}
@Test
@@ -139,6 +139,32 @@ public final class CfnStackWaits {
stack.stackStatusReason() == null ? "" : stack.stackStatusReason())));
}
/** Creates {@code stackName} from {@code template} through the SDK and waits for {@code expectedStatus}. */
public static Stack createStack(CloudFormationClient client, String stackName, String template,
String expectedStatus) {
client.createStack(request -> request.stackName(stackName).templateBody(template));
return awaitStatus(client, stackName, expectedStatus);
}
/** Updates {@code stackName} to {@code template} through the SDK and waits for {@code expectedStatus}. */
public static Stack updateStack(CloudFormationClient client, String stackName, String template,
String expectedStatus) {
client.updateStack(request -> request.stackName(stackName).templateBody(template));
return awaitStatus(client, stackName, expectedStatus);
}
/**
* A resource to append to a template's {@code Resources}, after the one named {@code logicalId}:
* an instance that names a launch template that does not exist, so it fails once that resource
* is done, and an update that changed it rolls back.
*/
public static String failingResourceAfter(String logicalId) {
return """
,
"Later": {"Type": "AWS::EC2::Instance", "DependsOn": "%s", "Properties": {"LaunchTemplate": {
"LaunchTemplateId": "lt-0123456789abcdef0", "Version": "1"}}}""".formatted(logicalId);
}
/** The value of {@code stack}'s output {@code key}; fails when the stack has no such output. */
public static String output(Stack stack, String key) {
return stack.outputs().stream().filter(output -> key.equals(output.outputKey())).findFirst()
@@ -535,14 +535,12 @@ AWS::RDS::DBInstance SourceDBInstanceAutomatedBackupsArn accepted and ignored
AWS::RDS::DBInstance SourceDBInstanceIdentifier accepted and ignored
AWS::RDS::DBInstance SourceDbiResourceId accepted and ignored
AWS::RDS::DBInstance SourceRegion accepted and ignored
AWS::RDS::DBInstance StorageEncrypted accepted and ignored
AWS::RDS::DBInstance StorageThroughput accepted and ignored
AWS::RDS::DBInstance StorageType accepted and ignored
AWS::RDS::DBInstance Tags accepted and ignored
AWS::RDS::DBInstance Timezone accepted and ignored
AWS::RDS::DBInstance UseDefaultProcessorFeatures accepted and ignored
AWS::RDS::DBInstance UseLatestRestorableTime accepted and ignored
AWS::RDS::DBInstance VPCSecurityGroups accepted and ignored
AWS::RDS::DBParameterGroup Parameters accepted and ignored
AWS::RDS::DBParameterGroup Tags accepted and ignored
AWS::RDS::DBProxyTargetGroup Tags accepted and ignored
1 AWS::ApiGateway::ApiKey StageKeys accepted and ignored, as the ApiGatewayApiKeyCfnProvisioner javadoc records
535 AWS::RDS::DBInstance SourceDBInstanceIdentifier accepted and ignored
536 AWS::RDS::DBInstance SourceDbiResourceId accepted and ignored
537 AWS::RDS::DBInstance SourceRegion accepted and ignored
AWS::RDS::DBInstance StorageEncrypted accepted and ignored
538 AWS::RDS::DBInstance StorageThroughput accepted and ignored
539 AWS::RDS::DBInstance StorageType accepted and ignored
540 AWS::RDS::DBInstance Tags accepted and ignored
541 AWS::RDS::DBInstance Timezone accepted and ignored
542 AWS::RDS::DBInstance UseDefaultProcessorFeatures accepted and ignored
543 AWS::RDS::DBInstance UseLatestRestorableTime accepted and ignored
AWS::RDS::DBInstance VPCSecurityGroups accepted and ignored
544 AWS::RDS::DBParameterGroup Parameters accepted and ignored
545 AWS::RDS::DBParameterGroup Tags accepted and ignored
546 AWS::RDS::DBProxyTargetGroup Tags accepted and ignored