mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudformation): preserve concurrent KeyPair parameter writes (#7367)
* fix(cloudformation): preserve concurrent KeyPair parameter writes * refactor(cloudformation): share tracked resource sets Signed-off-by: Jackson Price <jxnprice@amazon.com> --------- Signed-off-by: Jackson Price <jxnprice@amazon.com>
This commit is contained in:
1 parent
7b07cee8c6
commit
c0906b88d0
7 files changed
+225
-73
No files matched your search
+36
@@ -0,0 +1,36 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/** Sets of identifiers persisted in a resource's internal tracking attributes. */
|
||||
public final class CfnTrackedSets {
|
||||
|
||||
private CfnTrackedSets() {
|
||||
}
|
||||
|
||||
/** Returns a mutable set so a provisioner can update the recorded identifiers. */
|
||||
public static Set<String> read(StackResource resource, String attribute) {
|
||||
String raw = resource.getAttributes().get(attribute);
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
return new LinkedHashSet<>();
|
||||
}
|
||||
return new LinkedHashSet<>(List.of(raw.split("\n")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Newline separated because an IAM policy name may contain a comma, per the
|
||||
* {@code [\w+=,.@-]+} pattern CloudFormation documents for {@code PolicyName}.
|
||||
*/
|
||||
public static void write(StackResource resource, String attribute, Collection<String> values) {
|
||||
if (values.isEmpty()) {
|
||||
resource.getAttributes().remove(attribute);
|
||||
return;
|
||||
}
|
||||
resource.getAttributes().put(attribute, String.join("\n", values));
|
||||
}
|
||||
}
|
||||
+56
-12
@@ -30,7 +30,8 @@ import java.util.TreeMap;
|
||||
* {@code SecureString} parameter {@code /ec2/keypair/<KeyPairId>}. With it the key is imported, its
|
||||
* type read from the material, so {@code KeyType} is ignored as AWS documents and {@code KeyFormat}
|
||||
* has no private key to format, and nothing is written to Parameter Store. Failed writes clean up
|
||||
* any parameter they may have saved before deleting the key, retaining its id if cleanup needs a retry.
|
||||
* any parameter they may have saved before deleting the key. A parameter another client wrote after
|
||||
* the new key became visible is preserved, including during cleanup retries.
|
||||
*
|
||||
* <p>Every property is create-only and {@code KeyName} is required, so the resource is always
|
||||
* custom-named. An update that changes another property under the same name is refused, as
|
||||
@@ -54,8 +55,14 @@ public class Ec2KeyPairCfnProvisioner implements CfnResourceProvisioner {
|
||||
* An entry leaves once its delete succeeds.
|
||||
*/
|
||||
private static final String CREATED_KEYS_ATTR = "__FlociKeyPairCreatedKeys";
|
||||
private static final String UNOWNED_PARAMETERS_ATTR = "__FlociKeyPairUnownedParameters";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private enum ParameterOwnership {
|
||||
OWNED,
|
||||
UNOWNED
|
||||
}
|
||||
|
||||
private final Ec2Service ec2Service;
|
||||
private final SsmService ssmService;
|
||||
|
||||
@@ -90,6 +97,7 @@ public class Ec2KeyPairCfnProvisioner implements CfnResourceProvisioner {
|
||||
ObjectNode inputs = inputs(name, keyType, keyFormat, publicKeyMaterial, tags);
|
||||
|
||||
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
|
||||
Set<String> unownedParameterIds = CfnTrackedSets.read(r, UNOWNED_PARAMETERS_ATTR);
|
||||
// A dispatcher stub created nothing, so a key that takes over its id is a create.
|
||||
if (ctx.isUpdate() && !CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore)) {
|
||||
if (madeFrom(readInputs(CREATE_ONLY_INPUTS.read(attributesBefore), r), inputs)) {
|
||||
@@ -121,17 +129,20 @@ public class Ec2KeyPairCfnProvisioner implements CfnResourceProvisioner {
|
||||
putCreatedKeys(r, owed);
|
||||
}
|
||||
}
|
||||
if (publicKeyMaterial == null) {
|
||||
unownedParameterIds.add(key.getKeyPairId());
|
||||
CfnTrackedSets.write(r, UNOWNED_PARAMETERS_ATTR, unownedParameterIds);
|
||||
}
|
||||
try {
|
||||
CfnRollback.guarded(r, ctx, true,
|
||||
() -> deleteKeyPair(key, ctx.region()),
|
||||
() -> deleteKeyPair(key, ctx.region(), CfnTrackedSets.read(r, UNOWNED_PARAMETERS_ATTR)),
|
||||
() -> { },
|
||||
() -> {
|
||||
if (!tags.isEmpty()) {
|
||||
ec2Service.createTags(ctx.region(), List.of(key.getKeyPairId()), tags);
|
||||
}
|
||||
if (publicKeyMaterial == null) {
|
||||
ssmService.putParameter(parameterName(key.getKeyPairId()), key.getKeyMaterial(),
|
||||
"SecureString", null, false, ctx.region());
|
||||
storePrivateKeyParameter(r, key, ctx.region());
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException failure) {
|
||||
@@ -146,6 +157,33 @@ public class Ec2KeyPairCfnProvisioner implements CfnResourceProvisioner {
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
|
||||
private void storePrivateKeyParameter(StackResource resource, KeyPair key, String region) {
|
||||
// PutParameter can fail after saving the value, so its undo must assume a write was made.
|
||||
recordParameterOwnership(resource, key.getKeyPairId(), ParameterOwnership.OWNED);
|
||||
try {
|
||||
ssmService.putParameter(parameterName(key.getKeyPairId()), key.getKeyMaterial(),
|
||||
"SecureString", null, false, region);
|
||||
} catch (AwsException failure) {
|
||||
if ("ParameterAlreadyExists".equals(failure.getErrorCode())) {
|
||||
// DescribeKeyPairs exposes the new id before this write; another client can claim
|
||||
// the parameter in that gap. Record that this write owns nothing, including on a retry.
|
||||
recordParameterOwnership(resource, key.getKeyPairId(), ParameterOwnership.UNOWNED);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private static void recordParameterOwnership(StackResource resource, String keyPairId,
|
||||
ParameterOwnership ownership) {
|
||||
Set<String> ids = CfnTrackedSets.read(resource, UNOWNED_PARAMETERS_ATTR);
|
||||
if (ownership == ParameterOwnership.UNOWNED) {
|
||||
ids.add(keyPairId);
|
||||
} else {
|
||||
ids.remove(keyPairId);
|
||||
}
|
||||
CfnTrackedSets.write(resource, UNOWNED_PARAMETERS_ATTR, ids);
|
||||
}
|
||||
|
||||
/**
|
||||
* The resolved property, or null when it is absent or {@code AWS::NoValue}, directly or as the
|
||||
* {@code Fn::If} branch its condition chooses. Every other value is kept as resolved, an empty
|
||||
@@ -242,7 +280,8 @@ public class Ec2KeyPairCfnProvisioner implements CfnResourceProvisioner {
|
||||
if (CfnResourceDispatcher.isStub(resource.getPhysicalId(), resource.getAttributes())) {
|
||||
return;
|
||||
}
|
||||
deleteNamed(resource.getPhysicalId(), createdKeyId(resource.getAttributes(), resource), region);
|
||||
deleteNamed(resource.getPhysicalId(), createdKeyId(resource.getAttributes(), resource), region,
|
||||
CfnTrackedSets.read(resource, UNOWNED_PARAMETERS_ATTR));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -253,19 +292,20 @@ public class Ec2KeyPairCfnProvisioner implements CfnResourceProvisioner {
|
||||
*/
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
deleteNamed(physicalId, null, region);
|
||||
deleteNamed(physicalId, null, region, Set.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the key {@code name} holds, and, when {@code createdKeyId} names a key CreateKeyPair made
|
||||
* for this resource that the name no longer holds, that key's parameter too.
|
||||
*/
|
||||
private void deleteNamed(String name, String createdKeyId, String region) {
|
||||
private void deleteNamed(String name, String createdKeyId, String region, Set<String> unownedParameters) {
|
||||
KeyPair current = findKeyPair(name, region);
|
||||
if (current != null) {
|
||||
deleteKeyPair(current, region);
|
||||
deleteKeyPair(current, region, unownedParameters);
|
||||
}
|
||||
if (createdKeyId != null && (current == null || !createdKeyId.equals(current.getKeyPairId()))) {
|
||||
if (createdKeyId != null && !unownedParameters.contains(createdKeyId)
|
||||
&& (current == null || !createdKeyId.equals(current.getKeyPairId()))) {
|
||||
deletePrivateKeyParameter(createdKeyId, region);
|
||||
}
|
||||
}
|
||||
@@ -302,7 +342,7 @@ public class Ec2KeyPairCfnProvisioner implements CfnResourceProvisioner {
|
||||
private ReplacementCleanup.Deleter owedDeleter(StackResource r) {
|
||||
return (type, name, region) -> {
|
||||
Map<String, String> owed = createdKeys(r);
|
||||
deleteNamed(name, owed.get(name), region);
|
||||
deleteNamed(name, owed.get(name), region, CfnTrackedSets.read(r, UNOWNED_PARAMETERS_ATTR));
|
||||
if (owed.remove(name) != null) {
|
||||
putCreatedKeys(r, owed);
|
||||
}
|
||||
@@ -321,8 +361,8 @@ public class Ec2KeyPairCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteKeyPair(KeyPair key, String region) {
|
||||
if (key.getKeyMaterial() != null) {
|
||||
private void deleteKeyPair(KeyPair key, String region, Set<String> unownedParameters) {
|
||||
if (key.getKeyMaterial() != null && !unownedParameters.contains(key.getKeyPairId())) {
|
||||
deletePrivateKeyParameter(key.getKeyPairId(), region);
|
||||
}
|
||||
ec2Service.deleteKeyPair(region, null, key.getKeyPairId());
|
||||
@@ -348,11 +388,15 @@ public class Ec2KeyPairCfnProvisioner implements CfnResourceProvisioner {
|
||||
public void clearUpdate(StackResource resource) {
|
||||
CREATE_ONLY_INPUTS.clearPrior(resource);
|
||||
resource.getAttributes().remove(CREATED_KEYS_ATTR);
|
||||
resource.getAttributes().remove(UNOWNED_PARAMETERS_ATTR);
|
||||
ReplacementCleanup.clear(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) {
|
||||
Set<String> unowned = CfnTrackedSets.read(previous, UNOWNED_PARAMETERS_ATTR);
|
||||
unowned.addAll(CfnTrackedSets.read(attempted, UNOWNED_PARAMETERS_ATTR));
|
||||
CfnTrackedSets.write(previous, UNOWNED_PARAMETERS_ATTR, unowned);
|
||||
Map<String, String> owed = createdKeys(previous);
|
||||
createdKeys(attempted).forEach((name, id) -> {
|
||||
if (!name.equals(previous.getPhysicalId())) {
|
||||
|
||||
+4
-25
@@ -10,7 +10,6 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
@@ -131,8 +130,8 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
|
||||
// What the previous execution of this resource wrote, so an update can take out what the
|
||||
// template stopped declaring. Only these names are removed, which leaves inline policies and
|
||||
// attachments added out of band alone.
|
||||
Set<String> previousInlineNames = readTrackedSet(r, INLINE_NAMES_ATTR);
|
||||
Set<String> previousManagedArns = readTrackedSet(r, MANAGED_ARNS_ATTR);
|
||||
Set<String> previousInlineNames = CfnTrackedSets.read(r, INLINE_NAMES_ATTR);
|
||||
Set<String> previousManagedArns = CfnTrackedSets.read(r, MANAGED_ARNS_ATTR);
|
||||
|
||||
Set<String> originalPolicyArns = new HashSet<>(role.getAttachedPolicyArns());
|
||||
LinkedHashSet<String> attachedByThisAttempt = new LinkedHashSet<>();
|
||||
@@ -295,28 +294,8 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
// What the next execution compares its template against.
|
||||
writeTrackedSet(r, INLINE_NAMES_ATTR, inlineWrittenByThisAttempt);
|
||||
writeTrackedSet(r, MANAGED_ARNS_ATTR, managedPolicyArns);
|
||||
}
|
||||
|
||||
private static Set<String> readTrackedSet(StackResource r, String attribute) {
|
||||
String raw = r.getAttributes().get(attribute);
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
return Set.of();
|
||||
}
|
||||
return new LinkedHashSet<>(List.of(raw.split("\n")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Newline separated because an IAM policy name may contain a comma, per the
|
||||
* {@code [\w+=,.@-]+} pattern CloudFormation documents for {@code PolicyName}.
|
||||
*/
|
||||
private static void writeTrackedSet(StackResource r, String attribute, Collection<String> values) {
|
||||
if (values.isEmpty()) {
|
||||
r.getAttributes().remove(attribute);
|
||||
return;
|
||||
}
|
||||
r.getAttributes().put(attribute, String.join("\n", values));
|
||||
CfnTrackedSets.write(r, INLINE_NAMES_ATTR, inlineWrittenByThisAttempt);
|
||||
CfnTrackedSets.write(r, MANAGED_ARNS_ATTR, managedPolicyArns);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+6
-23
@@ -12,7 +12,6 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
@@ -106,9 +105,9 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
|
||||
r.getAttributes().put("Arn", user.getArn());
|
||||
r.getAttributes().put(USER_ID_ATTR, user.getUserId());
|
||||
|
||||
Set<String> previousInlineNames = readTrackedSet(r, INLINE_NAMES_ATTR);
|
||||
Set<String> previousManagedArns = readTrackedSet(r, MANAGED_ARNS_ATTR);
|
||||
Set<String> previousGroups = readTrackedSet(r, GROUPS_ATTR);
|
||||
Set<String> previousInlineNames = CfnTrackedSets.read(r, INLINE_NAMES_ATTR);
|
||||
Set<String> previousManagedArns = CfnTrackedSets.read(r, MANAGED_ARNS_ATTR);
|
||||
Set<String> previousGroups = CfnTrackedSets.read(r, GROUPS_ATTR);
|
||||
|
||||
Set<String> originalGroups = new HashSet<>(user.getGroupNames());
|
||||
Set<String> originalPolicyArns = new HashSet<>(user.getAttachedPolicyArns());
|
||||
@@ -323,25 +322,9 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
|
||||
throw failure;
|
||||
}
|
||||
|
||||
writeTrackedSet(r, INLINE_NAMES_ATTR, inlineWrittenByThisAttempt);
|
||||
writeTrackedSet(r, MANAGED_ARNS_ATTR, managedPolicyArns);
|
||||
writeTrackedSet(r, GROUPS_ATTR, groups);
|
||||
}
|
||||
|
||||
private static Set<String> readTrackedSet(StackResource r, String attribute) {
|
||||
String raw = r.getAttributes().get(attribute);
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
return Set.of();
|
||||
}
|
||||
return new LinkedHashSet<>(List.of(raw.split("\n")));
|
||||
}
|
||||
|
||||
private static void writeTrackedSet(StackResource r, String attribute, Collection<String> values) {
|
||||
if (values.isEmpty()) {
|
||||
r.getAttributes().remove(attribute);
|
||||
return;
|
||||
}
|
||||
r.getAttributes().put(attribute, String.join("\n", values));
|
||||
CfnTrackedSets.write(r, INLINE_NAMES_ATTR, inlineWrittenByThisAttempt);
|
||||
CfnTrackedSets.write(r, MANAGED_ARNS_ATTR, managedPolicyArns);
|
||||
CfnTrackedSets.write(r, GROUPS_ATTR, groups);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+39
@@ -25,10 +25,12 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.CfnRequests.cfn;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@@ -135,6 +137,43 @@ class CloudFormationEc2KeyPairIntegrationTest {
|
||||
deleteStack(stack);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConcurrentParameterWriterSurvivesTheFailedKeyCreation() throws Exception {
|
||||
String stack = unique("cfn-key-parameter-race");
|
||||
String name = stack + "-key";
|
||||
String outsideValue = "another-client-value";
|
||||
AtomicReference<String> outsideParameter = new AtomicReference<>();
|
||||
doAnswer(invocation -> {
|
||||
String parameterName = invocation.getArgument(0);
|
||||
assertEquals("/ec2/keypair/" + keyPairId(name), parameterName,
|
||||
"the newly generated key ID is already visible through DescribeKeyPairs");
|
||||
ssm("PutParameter", Map.of("Name", parameterName, "Value", outsideValue,
|
||||
"Type", "SecureString", "Overwrite", false)).then().statusCode(200);
|
||||
outsideParameter.set(parameterName);
|
||||
return invocation.callRealMethod();
|
||||
}).when(ssmService).putParameter(startsWith("/ec2/keypair/"), anyString(),
|
||||
eq("SecureString"), isNull(), eq(false), eq(REGION));
|
||||
|
||||
deploy("CreateStack", stack, template(Key.named(name), false));
|
||||
try {
|
||||
assertStatus(stack, "ROLLBACK_COMPLETE");
|
||||
assertEquals("The parameter already exists. To overwrite this value, set the overwrite option "
|
||||
+ "in the request to true.", CfnStackWaits.failedResourceReason(stack));
|
||||
assertKeyPairMissing(name);
|
||||
String parameterName = outsideParameter.get();
|
||||
assertNotNull(parameterName, "the other client's write completed before the stack's write");
|
||||
assertEquals(outsideValue, parameter(parameterName).getString("Parameter.Value"));
|
||||
assertEquals(List.of(outsideValue),
|
||||
ssm("GetParameterHistory", Map.of("Name", parameterName, "WithDecryption", true))
|
||||
.then().statusCode(200).extract().jsonPath().getList("Parameters.Value", String.class));
|
||||
} finally {
|
||||
deleteStack(stack);
|
||||
if (outsideParameter.get() != null) {
|
||||
ssm("DeleteParameter", Map.of("Name", outsideParameter.get()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImportedKeyTakesItsTypeFromTheMaterialAndWritesNoParameter() throws Exception {
|
||||
String stack = unique("cfn-key-import");
|
||||
|
||||
+77
-6
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.MissingNode;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -50,7 +51,7 @@ class Ec2KeyPairCfnProvisionerTest {
|
||||
private final Ec2Service ec2 = mock(Ec2Service.class);
|
||||
private final SsmService ssm = mock(SsmService.class);
|
||||
private final Ec2KeyPairCfnProvisioner provisioner = new Ec2KeyPairCfnProvisioner(ec2, ssm);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
|
||||
@Test
|
||||
void aCreatedKeyBacksRefAndGetAttAndKeepsItsPrivateKeyInASecureStringParameter() throws Exception {
|
||||
@@ -213,6 +214,22 @@ class Ec2KeyPairCfnProvisionerTest {
|
||||
assertFalse(resource.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPreexistingParameterSurvivesARejectedCreate() {
|
||||
SsmService realSsm = realSsm(new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
realSsm.putParameter("/ec2/keypair/key-1", "preexisting-value", "SecureString", null, false, REGION);
|
||||
when(ec2.createKeyPair(REGION, "deploy", null, null)).thenReturn(created("deploy", "key-1"));
|
||||
Ec2KeyPairCfnProvisioner realProvisioner = new Ec2KeyPairCfnProvisioner(ec2, realSsm);
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> realProvisioner.provision(resource(), props("{\"KeyName\": \"deploy\"}"), ctx(null)));
|
||||
|
||||
assertEquals("ParameterAlreadyExists", failure.getErrorCode());
|
||||
assertEquals("preexisting-value", realSsm.getParameter("/ec2/keypair/key-1", REGION).getValue());
|
||||
assertEquals(1, realSsm.getParameterHistory("/ec2/keypair/key-1", REGION).size());
|
||||
verify(ec2).deleteKeyPair(REGION, null, "key-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedParameterUndoRetainsTheKeyForTheStackRollback() throws Exception {
|
||||
InMemoryStorage<String, Parameter> parameters = spy(new InMemoryStorage<>());
|
||||
@@ -242,6 +259,63 @@ class Ec2KeyPairCfnProvisionerTest {
|
||||
verify(ec2).deleteKeyPair(REGION, null, "key-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPreexistingParameterSurvivesTheStackRollbackAfterKeyDeletionFails() throws Exception {
|
||||
SsmService realSsm = realSsm(new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
realSsm.putParameter("/ec2/keypair/key-1", "private-key-1", "SecureString", null, false, REGION);
|
||||
when(ec2.createKeyPair(REGION, "deploy", null, null)).thenReturn(created("deploy", "key-1"));
|
||||
when(ec2.deleteKeyPair(REGION, null, "key-1"))
|
||||
.thenThrow(new IllegalStateException("simulated key delete failure"))
|
||||
.thenReturn(null);
|
||||
Ec2KeyPairCfnProvisioner realProvisioner = new Ec2KeyPairCfnProvisioner(ec2, realSsm);
|
||||
StackResource resource = resource();
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> realProvisioner.provision(resource, props("{\"KeyName\": \"deploy\"}"), ctx(null)));
|
||||
assertEquals("ParameterAlreadyExists", failure.getErrorCode());
|
||||
assertEquals("true", resource.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
|
||||
when(ec2.describeKeyPairs(REGION, List.of("deploy"), List.of()))
|
||||
.thenReturn(List.of(created("deploy", "key-1")));
|
||||
realProvisioner.delete(resource, REGION);
|
||||
|
||||
assertEquals("private-key-1", realSsm.getParameter("/ec2/keypair/key-1", REGION).getValue());
|
||||
verify(ec2, times(2)).deleteKeyPair(REGION, null, "key-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedReplacementCarriesItsUnownedParameterIntoCleanup() throws Exception {
|
||||
SsmService realSsm = realSsm(new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
when(ec2.createKeyPair(REGION, "first", null, null)).thenReturn(created("first", "key-1"));
|
||||
when(ec2.createKeyPair(REGION, "next", null, null)).thenReturn(created("next", "key-2"));
|
||||
Ec2KeyPairCfnProvisioner realProvisioner = new Ec2KeyPairCfnProvisioner(ec2, realSsm);
|
||||
StackResource previous = resource();
|
||||
realProvisioner.provision(previous, props("{\"KeyName\": \"first\"}"), ctx(null));
|
||||
realSsm.putParameter("/ec2/keypair/key-2", "preexisting-value", "SecureString", null, false, REGION);
|
||||
when(ec2.deleteKeyPair(REGION, null, "key-2"))
|
||||
.thenThrow(new IllegalStateException("simulated key delete failure"))
|
||||
.thenReturn(null);
|
||||
StackResource attempted = resource();
|
||||
attempted.setPhysicalId(previous.getPhysicalId());
|
||||
attempted.getAttributes().putAll(previous.getAttributes());
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> realProvisioner.provision(attempted, props("{\"KeyName\": \"next\"}"), ctx("first")));
|
||||
assertEquals("ParameterAlreadyExists", failure.getErrorCode());
|
||||
ReplacementCleanup.mergeDisplaced(previous, attempted);
|
||||
realProvisioner.mergeFailedUpdateResourceTracking(previous, attempted);
|
||||
when(ec2.describeKeyPairs(REGION, List.of("next"), List.of()))
|
||||
.thenReturn(List.of(created("next", "key-2")));
|
||||
|
||||
StackResource restored = mapper.readValue(mapper.writeValueAsBytes(previous), StackResource.class);
|
||||
assertTrue(realProvisioner.completeUpdate(restored).complete());
|
||||
|
||||
assertEquals("preexisting-value", realSsm.getParameter("/ec2/keypair/key-2", REGION).getValue());
|
||||
assertEquals("private-key-1", realSsm.getParameter("/ec2/keypair/key-1", REGION).getValue());
|
||||
verify(ec2, times(2)).deleteKeyPair(REGION, null, "key-2");
|
||||
verify(ec2, never()).deleteKeyPair(REGION, null, "key-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedReplacementRetainsItsParameterIdWhenTheKeyDisappearsBeforeCleanup() throws Exception {
|
||||
InMemoryStorage<String, Parameter> parameters = spy(new InMemoryStorage<>());
|
||||
@@ -276,20 +350,17 @@ class Ec2KeyPairCfnProvisionerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedTagWriteDeletesTheNewKeyAndToleratesItsMissingParameter() {
|
||||
void aFailedTagWriteDeletesTheNewKeyBeforeAnyParameterIsWritten() {
|
||||
when(ec2.createKeyPair(REGION, "deploy", null, null)).thenReturn(created("deploy", "key-1"));
|
||||
AwsException tagFailure = new AwsException("TagLimitExceeded", "simulated tag failure", 400);
|
||||
doThrow(tagFailure).when(ec2).createTags(anyString(), anyList(), anyList());
|
||||
doThrow(new AwsException("ParameterNotFound", "The parameter was never written", 400))
|
||||
.when(ssm).deleteParameter("/ec2/keypair/key-1", REGION);
|
||||
|
||||
assertSame(tagFailure, assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(resource(), props("{\"KeyName\": \"deploy\","
|
||||
+ " \"Tags\": [{\"Key\": \"team\", \"Value\": \"infra\"}]}"), ctx(null))));
|
||||
|
||||
verify(ec2).deleteKeyPair(REGION, null, "key-1");
|
||||
verify(ssm).deleteParameter("/ec2/keypair/key-1", REGION);
|
||||
verify(ssm, never()).putParameter(anyString(), anyString(), anyString(), any(), anyBoolean(), anyString());
|
||||
verifyNoInteractions(ssm);
|
||||
}
|
||||
|
||||
/** The engine's create rollback deletes a key the provision's own undo could not. */
|
||||
|
||||
+7
-7
@@ -213,8 +213,8 @@ class IamRoleCfnProvisionerTest {
|
||||
// stay on the role while the stack still reported UPDATE_COMPLETE.
|
||||
IamRole existing = new IamRole("AROAapp-role", "app-role", "/",
|
||||
"arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST);
|
||||
existing.getInlinePolicies().put("keep", EMPTY_TRUST);
|
||||
existing.getInlinePolicies().put("drop", EMPTY_TRUST);
|
||||
existing.getInlinePolicies().put("keep,policy", EMPTY_TRUST);
|
||||
existing.getInlinePolicies().put("drop,policy", EMPTY_TRUST);
|
||||
existing.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/Keep");
|
||||
existing.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/Drop");
|
||||
when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of()), any()))
|
||||
@@ -224,7 +224,7 @@ class IamRoleCfnProvisionerTest {
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("app-role");
|
||||
r.getAttributes().put("RoleId", "AROAapp-role");
|
||||
r.getAttributes().put("__FlociInlinePolicyNames", "keep\ndrop");
|
||||
r.getAttributes().put("__FlociInlinePolicyNames", "keep,policy\ndrop,policy");
|
||||
r.getAttributes().put("__FlociManagedPolicyArns",
|
||||
"arn:aws:iam::aws:policy/Keep\narn:aws:iam::aws:policy/Drop");
|
||||
|
||||
@@ -233,16 +233,16 @@ class IamRoleCfnProvisionerTest {
|
||||
"RoleName": "app-role",
|
||||
"ManagedPolicyArns": ["arn:aws:iam::aws:policy/Keep"],
|
||||
"Policies": [
|
||||
{"PolicyName": "keep", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
|
||||
{"PolicyName": "keep,policy", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
|
||||
]
|
||||
}
|
||||
"""), ctx());
|
||||
|
||||
verify(iam).deleteRolePolicy("app-role", "drop");
|
||||
verify(iam).deleteRolePolicy("app-role", "drop,policy");
|
||||
verify(iam).detachRolePolicy("app-role", "arn:aws:iam::aws:policy/Drop");
|
||||
verify(iam, never()).deleteRolePolicy("app-role", "keep");
|
||||
verify(iam, never()).deleteRolePolicy("app-role", "keep,policy");
|
||||
verify(iam, never()).detachRolePolicy("app-role", "arn:aws:iam::aws:policy/Keep");
|
||||
assertEquals("keep", r.getAttributes().get("__FlociInlinePolicyNames"));
|
||||
assertEquals("keep,policy", r.getAttributes().get("__FlociInlinePolicyNames"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user