diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEc2KeyPairTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEc2KeyPairTest.java new file mode 100644 index 0000000000..76956ae943 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEc2KeyPairTest.java @@ -0,0 +1,202 @@ +package com.floci.test; + +import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; +import org.bouncycastle.crypto.util.OpenSSHPrivateKeyUtil; +import org.bouncycastle.crypto.util.OpenSSHPublicKeyUtil; +import org.bouncycastle.openssl.PEMKeyPair; +import org.bouncycastle.openssl.PEMParser; +import org.bouncycastle.util.io.pem.PemReader; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.CloudFormationException; +import software.amazon.awssdk.services.cloudformation.model.Output; +import software.amazon.awssdk.services.cloudformation.model.Stack; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.Ec2Exception; +import software.amazon.awssdk.services.ec2.model.KeyPairInfo; +import software.amazon.awssdk.services.ec2.model.KeyType; +import software.amazon.awssdk.services.ssm.SsmClient; +import software.amazon.awssdk.services.ssm.model.Parameter; +import software.amazon.awssdk.services.ssm.model.ParameterNotFoundException; +import software.amazon.awssdk.services.ssm.model.ParameterType; + +import java.io.StringReader; +import java.security.MessageDigest; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("CloudFormation AWS::EC2::KeyPair") +class CloudFormationEc2KeyPairTest { + + private static CloudFormationClient cfn; + private static Ec2Client ec2; + private static SsmClient ssm; + private String stackName; + private boolean stackCreated; + + @BeforeAll + static void clients() { + cfn = TestFixtures.cloudFormationClient(); + ec2 = TestFixtures.ec2Client(); + ssm = TestFixtures.ssmClient(); + } + + @BeforeEach + void setup() { + stackName = TestFixtures.uniqueName("compat-cfn-key-pair"); + } + + @AfterEach + void cleanup() throws InterruptedException { + deleteStack(); + } + + @AfterAll + static void closeClients() { + cfn.close(); + ec2.close(); + ssm.close(); + } + + @Test + @DisplayName("An RSA key keeps its PEM private key in /ec2/keypair/, fingerprinted as AWS fingerprints a created RSA key") + void rsaKeyKeepsItsPrivateKeyInParameterStore() throws Exception { + String name = stackName + "-rsa"; + createStack(name, null); + + KeyPairInfo key = assertIdentity(name, KeyType.RSA); + String privateKey = privateKeyParameter(key.keyPairId()); + // Checked without printing it: it is a private key. + assertThat(privateKey.startsWith("-----BEGIN RSA PRIVATE KEY-----\n")).as("a PEM RSA private key").isTrue(); + PEMKeyPair pem; + try (PEMParser parser = new PEMParser(new StringReader(privateKey))) { + pem = (PEMKeyPair) parser.readObject(); + } + // "the SHA-1 digest of the DER encoded private key", in PKCS#8 as AWS digests it + String fingerprint = HexFormat.ofDelimiter(":").formatHex( + MessageDigest.getInstance("SHA-1").digest(pem.getPrivateKeyInfo().getEncoded())); + assertThat(key.keyFingerprint()).as("the parameter holds this key pair's own private key") + .isEqualTo(fingerprint); + + deleteStack(); + assertGone(name, key.keyPairId()); + } + + @Test + @DisplayName("An ED25519 key keeps its OpenSSH private key in /ec2/keypair/, fingerprinted with SHA-256") + void ed25519KeyKeepsItsPrivateKeyInParameterStore() throws Exception { + String name = stackName + "-ed25519"; + createStack(name, "ed25519"); + + KeyPairInfo key = assertIdentity(name, KeyType.ED25519); + String privateKey = privateKeyParameter(key.keyPairId()); + // Checked without printing it: it is a private key. + assertThat(privateKey.startsWith("-----BEGIN OPENSSH PRIVATE KEY-----\n")).as("an OpenSSH private key").isTrue(); + Ed25519PrivateKeyParameters parsed; + try (PemReader reader = new PemReader(new StringReader(privateKey))) { + parsed = (Ed25519PrivateKeyParameters) OpenSSHPrivateKeyUtil.parsePrivateKeyBlob( + reader.readPemObject().getContent()); + } + byte[] publicBlob = OpenSSHPublicKeyUtil.encodePublicKey(parsed.generatePublicKey()); + assertThat(key.keyFingerprint()).as("the parameter holds this key pair's own private key") + .isEqualTo(Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(publicBlob))); + + deleteStack(); + assertGone(name, key.keyPairId()); + } + + /** Ref is the key name, and the GetAtt attributes are the key DescribeKeyPairs describes. */ + private KeyPairInfo assertIdentity(String name, KeyType keyType) { + KeyPairInfo key = ec2.describeKeyPairs(r -> r.keyNames(name)).keyPairs().get(0); + assertThat(key.keyType()).isEqualTo(keyType); + assertThat(outputs()).containsExactlyInAnyOrderEntriesOf(Map.of( + "Name", name, "Id", key.keyPairId(), "Fingerprint", key.keyFingerprint())); + return key; + } + + private String privateKeyParameter(String keyPairId) { + Parameter parameter = ssm.getParameter(r -> r.name("/ec2/keypair/" + keyPairId).withDecryption(true)) + .parameter(); + assertThat(parameter.type()).isEqualTo(ParameterType.SECURE_STRING); + return parameter.value(); + } + + private static void assertGone(String name, String keyPairId) { + assertThatThrownBy(() -> ec2.describeKeyPairs(r -> r.keyNames(name))) + .isInstanceOfSatisfying(Ec2Exception.class, e -> + assertThat(e.awsErrorDetails().errorCode()).isEqualTo("InvalidKeyPair.NotFound")); + assertThatThrownBy(() -> ssm.getParameter(r -> r.name("/ec2/keypair/" + keyPairId))) + .isInstanceOf(ParameterNotFoundException.class); + } + + private void createStack(String keyName, String keyType) throws InterruptedException { + String template = """ + { + "Resources": { + "Key": { + "Type": "AWS::EC2::KeyPair", + "Properties": {"KeyName": "%s"%s} + } + }, + "Outputs": { + "Name": {"Value": {"Ref": "Key"}}, + "Id": {"Value": {"Fn::GetAtt": ["Key", "KeyPairId"]}}, + "Fingerprint": {"Value": {"Fn::GetAtt": ["Key", "KeyFingerprint"]}} + } + } + """.formatted(keyName, keyType == null ? "" : ", \"KeyType\": \"" + keyType + "\""); + cfn.createStack(r -> r.stackName(stackName).templateBody(template)); + stackCreated = true; + TestFixtures.await(() -> { + Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0); + String status = stack.stackStatusAsString(); + if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) { + throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason()); + } + return "CREATE_COMPLETE".equals(status); + }, stackName, "CREATE_COMPLETE", 60_000_000_000L, 100); + } + + private Map outputs() { + List outputs = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0).outputs(); + return outputs.stream().collect(Collectors.toMap(Output::outputKey, Output::outputValue)); + } + + private void deleteStack() throws InterruptedException { + if (!stackCreated) { + return; + } + cfn.deleteStack(r -> r.stackName(stackName)); + TestFixtures.await(() -> { + try { + List stacks = cfn.describeStacks(r -> r.stackName(stackName)).stacks(); + if (stacks.isEmpty()) { + return true; + } + Stack stack = stacks.get(0); + if ("DELETE_FAILED".equals(stack.stackStatusAsString())) { + throw new AssertionError(stackName + " deletion failed: " + stack.stackStatusReason()); + } + return "DELETE_COMPLETE".equals(stack.stackStatusAsString()); + } catch (CloudFormationException e) { + if ("ValidationError".equals(e.awsErrorDetails().errorCode()) + && e.getMessage().contains("does not exist")) { + return true; + } + throw e; + } + }, stackName, "stack deletion", 60_000_000_000L, 100); + stackCreated = false; + } +} diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 387a198494..1d519b806a 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -189,7 +189,7 @@ cross-resource references. | ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `SubnetGroup`, `User` (Tags are ignored), `UserGroup` (Tags are ignored), `ServerlessCache` (GetAtt uses the dotted Endpoint.* and ReaderEndpoint.* form) | | Redshift | `Cluster` (single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported), `ClusterParameterGroup`, `ClusterSubnetGroup`, `ClusterSecurityGroup` (accepted; no EC2-Classic security group model), `EventSubscription` | | Redshift Serverless | `Namespace` (Managed admin credentials use Secrets Manager; GetAtt uses the dotted Namespace.* form), `Workgroup` (starts a real container; one workgroup per namespace; capacity, VPC and price-performance settings are stored only; snapshot restore properties are ignored; GetAtt uses the dotted Workgroup.* form) | -| EC2 | `VPC` (deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway` (zonal, primary address only; `AvailabilityMode` regional and the `Secondary*` address properties fail), `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog`, `PrefixList` (updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails) | +| EC2 | `VPC` (deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway` (zonal, primary address only; `AvailabilityMode` regional and the `Secondary*` address properties fail), `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog`, `KeyPair` (a created key's private key is stored in the `SecureString` parameter `/ec2/keypair/`, as on AWS, and deleted with the key), `PrefixList` (updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails) | | Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` | | Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook`, `ScalingPolicy` | | Application Auto Scaling | `ScalableTarget` (`ScheduledActions` are accepted and not run; Floci has no scheduled scaling), `ScalingPolicy` | diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CreateOnlyInputs.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CreateOnlyInputs.java new file mode 100644 index 0000000000..ba1b738503 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CreateOnlyInputs.java @@ -0,0 +1,55 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; + +import java.util.Map; + +/** + * Keeps a resource's resolved create-only inputs and the record a replacement displaced. + * Provisioners own the input format and comparison; this helper preserves their attribute names. + * {@link ReplacementCleanup} restores public attributes only, so a rollback restores this record + * separately, even when deleting the replacement fails after its identity has been reverted. + */ +public final class CreateOnlyInputs { + + private final String currentAttribute; + private final String priorAttribute; + + public CreateOnlyInputs(String currentAttribute, String priorAttribute) { + this.currentAttribute = currentAttribute; + this.priorAttribute = priorAttribute; + } + + public String read(Map attributes) { + return attributes.get(currentAttribute); + } + + /** Records the created entity's inputs, keeping the prior record until the update ends. */ + public void record(StackResource resource, ProvisionContext ctx, Map attributesBefore, + String inputs) { + if (ctx.isUpdate()) { + resource.getAttributes().put(priorAttribute, attributesBefore.getOrDefault(currentAttribute, "")); + } + resource.getAttributes().put(currentAttribute, inputs); + } + + public boolean hasPrior(StackResource resource) { + return resource.getAttributes().containsKey(priorAttribute); + } + + /** Restores the record, including its absence on a resource that predates input tracking. */ + public void restorePrior(StackResource resource) { + String prior = resource.getAttributes().remove(priorAttribute); + if (prior != null) { + if (prior.isEmpty()) { + resource.getAttributes().remove(currentAttribute); + } else { + resource.getAttributes().put(currentAttribute, prior); + } + } + } + + public void clearPrior(StackResource resource) { + resource.getAttributes().remove(priorAttribute); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2KeyPairCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2KeyPairCfnProvisioner.java new file mode 100644 index 0000000000..97c147ff87 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2KeyPairCfnProvisioner.java @@ -0,0 +1,394 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.NullNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.KeyPair; +import io.github.hectorvent.floci.services.ec2.model.Tag; +import io.github.hectorvent.floci.services.ssm.SsmService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +/** + * Provisions {@code AWS::EC2::KeyPair}. The key name is the physical id and {@code Ref}; + * {@code Fn::GetAtt} exposes {@code KeyPairId} and {@code KeyFingerprint}. + * + *

Without {@code PublicKeyMaterial} the key is made by CreateKeyPair, of the {@code KeyType} and + * in the {@code KeyFormat} the template asks for, and its private key is stored, as on AWS, in the + * {@code SecureString} parameter {@code /ec2/keypair/}. 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. + * + *

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 + * CloudFormation refuses it; one that changes the name creates the new key and leaves the displaced + * one to the {@link ReplacementCleanup} record. + */ +@ApplicationScoped +public class Ec2KeyPairCfnProvisioner implements CfnResourceProvisioner { + + private static final Logger LOG = Logger.getLogger(Ec2KeyPairCfnProvisioner.class); + private static final String TYPE = "AWS::EC2::KeyPair"; + /** The registry schema's enums; EC2 itself takes the same values. */ + private static final List KEY_TYPES = List.of("rsa", "ed25519"); + private static final List KEY_FORMATS = List.of("pem", "ppk"); + private static final CreateOnlyInputs CREATE_ONLY_INPUTS = + new CreateOnlyInputs("__FlociKeyPairInputs", "__FlociKeyPairPriorInputs"); + /** + * The keys CreateKeyPair made that the resource no longer names but still owes a delete, by + * name to id: those a rename displaced and a replacement a rollback undoes. The cleanup deletes + * them by name alone, so this keeps the id whose parameter goes too when the key is already gone. + * An entry leaves once its delete succeeds. + */ + private static final String CREATED_KEYS_ATTR = "__FlociKeyPairCreatedKeys"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final Ec2Service ec2Service; + private final SsmService ssmService; + + @Inject + public Ec2KeyPairCfnProvisioner(Ec2Service ec2Service, SsmService ssmService) { + this.ec2Service = ec2Service; + this.ssmService = ssmService; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + if (ctx.isUpdate()) { + // Rolling this update back undoes it alone; only ContinueUpdateRollback retries the + // delete the last rollback could not make. + ReplacementCleanup.endRollbackRetry(r); + } + String name = resolveProperty(props, "KeyName", ctx); + if (name == null || name.isBlank()) { + throw new AwsException("ValidationError", TYPE + " requires KeyName.", 400); + } + String keyType = resolveProperty(props, "KeyType", ctx); + String keyFormat = resolveProperty(props, "KeyFormat", ctx); + String publicKeyMaterial = resolveProperty(props, "PublicKeyMaterial", ctx); + requireAllowed("KeyType", keyType, KEY_TYPES); + requireAllowed("KeyFormat", keyFormat, KEY_FORMATS); + List tags = Ec2Tags.validatedTags(ctx.resolveTags(props, "Tags")); + ObjectNode inputs = inputs(name, keyType, keyFormat, publicKeyMaterial, tags); + + Map attributesBefore = new HashMap<>(r.getAttributes()); + // 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)) { + // No property changed, and a key has nothing that changes in place. + ReplacementCleanup.record(r, ctx, attributesBefore); + return; + } + if (name.equals(ctx.priorPhysicalId())) { + throw CfnExceptions.customNamedReplacement(name); + } + } + + if (publicKeyMaterial != null && publicKeyMaterial.isEmpty()) { + // What ImportKeyPair answers for an empty PublicKeyMaterial. + throw new AwsException("MissingParameter", "The request must contain the parameter PublicKeyMaterial", 400); + } + KeyPair key = publicKeyMaterial == null + ? ec2Service.createKeyPair(ctx.region(), name, keyType, keyFormat) + : ec2Service.importKeyPair(ctx.region(), name, publicKeyMaterial); + r.setPhysicalId(key.getKeyName()); + r.getAttributes().put("KeyPairId", key.getKeyPairId()); + r.getAttributes().put("KeyFingerprint", key.getKeyFingerprint()); + CREATE_ONLY_INPUTS.record(r, ctx, attributesBefore, inputs.toString()); + if (ctx.isUpdate()) { + String priorCreatedId = createdKeyId(attributesBefore, r); + if (priorCreatedId != null) { + Map owed = createdKeys(r); + owed.put(ctx.priorPhysicalId(), priorCreatedId); + putCreatedKeys(r, owed); + } + } + try { + CfnRollback.guarded(r, ctx, true, + () -> deleteKeyPair(key, ctx.region()), + () -> { }, + () -> { + 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()); + } + }); + } catch (RuntimeException failure) { + if (publicKeyMaterial == null + && "true".equals(r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR))) { + Map owed = createdKeys(r); + owed.put(key.getKeyName(), key.getKeyPairId()); + putCreatedKeys(r, owed); + } + throw failure; + } + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + /** + * 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 + * string included, so a value a parameter supplies acts as the same value written literally. + */ + private static String resolveProperty(JsonNode props, String name, ProvisionContext ctx) { + if (props == null || !props.has(name) || props.get(name).isNull()) { + return null; + } + JsonNode value = ctx.engine().omitNoValue(props.get(name)); + return value.isMissingNode() ? null : ctx.engine().resolve(value); + } + + private static void requireAllowed(String property, String value, List allowed) { + if (value != null && !allowed.contains(value)) { + throw new AwsException("ValidationError", + TYPE + " " + property + " must be " + String.join(" or ", allowed) + ", got '" + value + "'", 400); + } + } + + /** + * The create-only properties as resolved, null when absent; tags as a sorted map, because their + * order is no change, and null when there are none. + */ + private static ObjectNode inputs(String name, String keyType, String keyFormat, String publicKeyMaterial, + List tags) { + ObjectNode inputs = MAPPER.createObjectNode(); + inputs.put("KeyName", name); + inputs.put("KeyType", keyType); + inputs.put("KeyFormat", keyFormat); + inputs.put("PublicKeyMaterial", publicKeyMaterial); + if (tags.isEmpty()) { + inputs.putNull("Tags"); + } else { + Map sortedTags = new TreeMap<>(); + tags.forEach(tag -> sortedTags.put(tag.getKey(), tag.getValue())); + inputs.set("Tags", MAPPER.valueToTree(sortedTags)); + } + return inputs; + } + + /** The inputs a key was recorded with, or null when the resource carries none it can read. */ + private static JsonNode readInputs(String recorded, StackResource r) { + if (recorded == null || recorded.isEmpty()) { + return null; + } + try { + return MAPPER.readTree(recorded); + } catch (JsonProcessingException e) { + LOG.warnv("Unreadable key pair inputs on {0}, treating them as unknown: {1}", + r.getLogicalId(), e.getMessage()); + return null; + } + } + + /** + * Whether a key recorded with {@code recorded} was made from {@code inputs}, compared property by + * property; a property the record lacks counts as absent, so a record written before a property + * was tracked still matches a template that leaves it out. + */ + private static boolean madeFrom(JsonNode recorded, ObjectNode inputs) { + if (recorded == null) { + return false; + } + for (Map.Entry input : inputs.properties()) { + JsonNode was = recorded.path(input.getKey()); + if (!(was.isMissingNode() ? NullNode.getInstance() : was).equals(input.getValue())) { + return false; + } + } + return true; + } + + private static String parameterName(String keyPairId) { + return "/ec2/keypair/" + keyPairId; + } + + private void deletePrivateKeyParameter(String keyPairId, String region) { + String parameter = parameterName(keyPairId); + CfnDeletes.safeDelete("EC2 key pair private key parameter", parameter, + () -> ssmService.deleteParameter(parameter, region), "ParameterNotFound"); + } + + /** + * Deletes the key the resource's name holds, as a Cloud Control DeleteResource names it by that + * identifier alone, with its parameter first when CreateKeyPair made it. The name is all this + * goes by, so once this resource's key was deleted outside the stack, a key made under the same + * name since then is the one deleted. When the name no longer holds the key this resource + * recorded, the recorded key's parameter is deleted as well, so no private key outlives its key. + */ + @Override + public void delete(StackResource resource, String region) { + // A stub left from before this type had a provisioner names no key. + if (CfnResourceDispatcher.isStub(resource.getPhysicalId(), resource.getAttributes())) { + return; + } + deleteNamed(resource.getPhysicalId(), createdKeyId(resource.getAttributes(), resource), region); + } + + /** + * Deletes the key the name holds, which is all a displaced or rolled-back key is recorded by, and + * first the parameter holding its private key when CreateKeyPair made it: an imported key has + * none. A key or parameter that is already gone counts as deleted; any other failure keeps the + * key, so a retry still finds it. + */ + @Override + public void delete(String resourceType, String physicalId, String region) { + deleteNamed(physicalId, null, region); + } + + /** + * 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) { + KeyPair current = findKeyPair(name, region); + if (current != null) { + deleteKeyPair(current, region); + } + if (createdKeyId != null && (current == null || !createdKeyId.equals(current.getKeyPairId()))) { + deletePrivateKeyParameter(createdKeyId, region); + } + } + + /** The recorded KeyPairId when the recorded inputs show CreateKeyPair made the key, else null. */ + private static String createdKeyId(Map attributes, StackResource r) { + String recordedId = attributes.get("KeyPairId"); + JsonNode inputs = readInputs(CREATE_ONLY_INPUTS.read(attributes), r); + return recordedId != null && inputs != null && !inputs.path("PublicKeyMaterial").isTextual() + ? recordedId : null; + } + + private static Map createdKeys(StackResource r) { + Map owed = new TreeMap<>(); + JsonNode recorded = readInputs(r.getAttributes().get(CREATED_KEYS_ATTR), r); + if (recorded != null) { + recorded.properties().forEach(e -> owed.put(e.getKey(), e.getValue().asText())); + } + return owed; + } + + private static void putCreatedKeys(StackResource r, Map owed) { + if (owed.isEmpty()) { + r.getAttributes().remove(CREATED_KEYS_ATTR); + } else { + r.getAttributes().put(CREATED_KEYS_ATTR, MAPPER.valueToTree(owed).toString()); + } + } + + /** + * Deletes a key the cleanup names, with the parameter of the created key recorded under that + * name, and drops the record once the delete succeeds. + */ + private ReplacementCleanup.Deleter owedDeleter(StackResource r) { + return (type, name, region) -> { + Map owed = createdKeys(r); + deleteNamed(name, owed.get(name), region); + if (owed.remove(name) != null) { + putCreatedKeys(r, owed); + } + }; + } + + /** The key pair {@code name} holds, or null when there is none. */ + private KeyPair findKeyPair(String name, String region) { + try { + return ec2Service.describeKeyPairs(region, List.of(name), List.of()).getFirst(); + } catch (AwsException e) { + if (!"InvalidKeyPair.NotFound".equals(e.getErrorCode())) { + throw e; + } + return null; + } + } + + private void deleteKeyPair(KeyPair key, String region) { + if (key.getKeyMaterial() != null) { + deletePrivateKeyParameter(key.getKeyPairId(), region); + } + ec2Service.deleteKeyPair(region, null, key.getKeyPairId()); + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + CREATE_ONLY_INPUTS.clearPrior(resource); + return ReplacementCleanup.complete(resource, owedDeleter(resource)); + } + + @Override + public void clearUpdate(StackResource resource) { + CREATE_ONLY_INPUTS.clearPrior(resource); + resource.getAttributes().remove(CREATED_KEYS_ATTR); + ReplacementCleanup.clear(resource); + } + + @Override + public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) { + Map owed = createdKeys(previous); + createdKeys(attempted).forEach((name, id) -> { + if (!name.equals(previous.getPhysicalId())) { + owed.putIfAbsent(name, id); + } + }); + putCreatedKeys(previous, owed); + } + + /** + * A rename is undone through the cleanup record, which names the displaced key again and deletes + * the replacement; the displaced key's inputs are put back here, even when that delete fails, as + * the resource names the displaced key from then on. Any other update changed nothing, so there + * is nothing to undo. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + String replacement = resource.getPhysicalId(); + boolean hasPriorInputs = CREATE_ONLY_INPUTS.hasPrior(resource); + String replacementCreatedId = createdKeyId(resource.getAttributes(), resource); + if (hasPriorInputs && replacementCreatedId != null) { + Map owed = createdKeys(resource); + owed.put(replacement, replacementCreatedId); + putCreatedKeys(resource, owed); + } + try { + ReplacementCleanup.rollback(resource, owedDeleter(resource)); + } finally { + if (hasPriorInputs && !replacement.equals(resource.getPhysicalId())) { + CREATE_ONLY_INPUTS.restorePrior(resource); + Map owed = createdKeys(resource); + if (owed.remove(resource.getPhysicalId()) != null) { + putCreatedKeys(resource, owed); + } + } + } + return true; + } +} diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index 2818e46bc3..10be1a38aa 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -273,6 +273,13 @@ "SubnetId" ], "AWS::EC2::InternetGateway": [], + "AWS::EC2::KeyPair": [ + "KeyName", + "KeyType", + "KeyFormat", + "PublicKeyMaterial", + "Tags" + ], "AWS::EC2::LaunchTemplate": [ "LaunchTemplateName" ], diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index 36a85a29ca..7fbd2374f9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -55,6 +55,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.DsqlCfnPr import io.github.hectorvent.floci.services.cloudformation.provisioners.DynamoDbCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2FlowLogCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2InstanceCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2KeyPairCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2LaunchTemplateCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkAclCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkCfnProvisioner; @@ -497,6 +498,9 @@ final class CfnProvisionerFixture { discovered.add(new Ec2LaunchTemplateCfnProvisioner(ec2Service)); discovered.add(new Ec2NetworkCfnProvisioner(ec2Service)); } + if (ec2Service != null && ssmService != null) { + discovered.add(new Ec2KeyPairCfnProvisioner(ec2Service, ssmService)); + } if (route53Service != null) { discovered.add(new Route53CfnProvisioner(route53Service)); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2KeyPairIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2KeyPairIntegrationTest.java new file mode 100644 index 0000000000..1431e53aa9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2KeyPairIntegrationTest.java @@ -0,0 +1,462 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.XmlParser; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ssm.SsmService; +import io.github.hectorvent.floci.testing.CfnStackWaits; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.mockito.InjectSpy; +import io.restassured.path.json.JsonPath; +import io.restassured.path.xml.XmlPath; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.mockito.ArgumentCaptor; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +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.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.ArgumentMatchers.startsWith; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.verify; + +/** + * {@code AWS::EC2::KeyPair} through real stack operations. A created key, of the type and in the + * format the template asks for, keeps its private key in the {@code SecureString} parameter + * {@code /ec2/keypair/} and an imported one writes none; {@code Ref} and + * {@code Fn::GetAtt} report the key DescribeKeyPairs describes; a rename replaces the key, and a + * change to another property under the same name is refused, as every property is create-only; and + * the stack delete, a create rollback, a committed rename and a rolled-back rename each take a key's + * parameter with it. A failing operation ends in a Secrets Manager secret that cannot be created. + */ +@QuarkusTest +class CloudFormationEc2KeyPairIntegrationTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String REGION = "us-east-1"; + /** The public key of the import example in the {@code AWS::EC2::KeyPair} reference. */ + private static final String ED25519_PUBLIC_KEY = + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICfp1F7DhdWZdqkYAUGCzcBsLmJeu9izpIyGpmmg7eCz example"; + + @Inject + Ec2Service ec2Service; + + @InjectSpy + SsmService ssmService; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + /** One {@code AWS::EC2::KeyPair}; a null property is left out of the template. */ + private record Key(String name, String keyType, String keyFormat, String publicKeyMaterial, + Map tags) { + static Key named(String name) { + return new Key(name, null, null, null, Map.of()); + } + } + + @ParameterizedTest + @CsvSource({ + ",,rsa,-----BEGIN RSA PRIVATE KEY-----", + "ed25519,,ed25519,-----BEGIN OPENSSH PRIVATE KEY-----", + "rsa,ppk,rsa,PuTTY-User-Key-File-2: ssh-rsa", + "ed25519,ppk,ed25519,PuTTY-User-Key-File-2: ssh-ed25519" + }) + void aCreatedKeyKeepsItsPrivateKeyInASecureStringParameterUntilTheStackIsDeleted( + String keyType, String keyFormat, String describedType, String firstLine) throws Exception { + String stack = unique("cfn-key-create"); + String name = stack + "-key"; + deploy("CreateStack", stack, template(new Key(name, keyType, keyFormat, null, Map.of("team", "infra")), false)); + assertStatus(stack, "CREATE_COMPLETE"); + + XmlPath described = describeKeyPair(name); + String id = described.getString("DescribeKeyPairsResponse.keySet.item.keyPairId"); + assertEquals(Map.of("Name", name, "Id", id, + "Fingerprint", described.getString("DescribeKeyPairsResponse.keySet.item.keyFingerprint")), + outputs(stack)); + assertEquals(describedType, described.getString("DescribeKeyPairsResponse.keySet.item.keyType")); + assertEquals("team", described.getString("DescribeKeyPairsResponse.keySet.item.tagSet.item.key")); + assertEquals("infra", described.getString("DescribeKeyPairsResponse.keySet.item.tagSet.item.value")); + assertEquals(name, physicalId(stack)); + + JsonPath parameter = parameter("/ec2/keypair/" + id); + assertEquals("SecureString", parameter.getString("Parameter.Type")); + String privateKey = parameter.getString("Parameter.Value"); + // Checked without printing either side: both are private keys. + assertTrue(privateKey.startsWith(firstLine + "\n"), "the private key is in the format the template asks for"); + assertTrue(privateKey.equals(storedPrivateKey(id)), "the parameter holds the key pair's own private key"); + + deleteStack(stack); + assertKeyPairMissing(name); + assertParameterMissing("/ec2/keypair/" + id); + } + + @Test + void aFailureAfterSavingThePrivateKeyRollsBackTheKeyAndParameter() throws Exception { + String stack = unique("cfn-key-partial-write"); + String name = stack + "-key"; + String failureReason = "simulated failure after saving the private key"; + doAnswer(invocation -> { + invocation.callRealMethod(); + throw new IllegalStateException(failureReason); + }).when(ssmService).putParameter(startsWith("/ec2/keypair/"), anyString(), + eq("SecureString"), isNull(), eq(false), eq(REGION)); + + deploy("CreateStack", stack, template(Key.named(name), false)); + assertStatus(stack, "ROLLBACK_COMPLETE"); + + assertTrue(events(stack).stream().anyMatch(event -> "Key".equals(event.get("LogicalResourceId")) + && "CREATE_FAILED".equals(event.get("ResourceStatus")) + && event.getOrDefault("ResourceStatusReason", "").contains(failureReason))); + ArgumentCaptor parameterName = ArgumentCaptor.forClass(String.class); + verify(ssmService).putParameter(parameterName.capture(), anyString(), + eq("SecureString"), isNull(), eq(false), eq(REGION)); + assertKeyPairMissing(name); + assertParameterMissing(parameterName.getValue()); + deleteStack(stack); + } + + @Test + void anImportedKeyTakesItsTypeFromTheMaterialAndWritesNoParameter() throws Exception { + String stack = unique("cfn-key-import"); + String name = stack + "-key"; + // KeyType is ignored when PublicKeyMaterial is given: the material says what the key is. + deploy("CreateStack", stack, template(new Key(name, "rsa", null, ED25519_PUBLIC_KEY, Map.of()), false)); + assertStatus(stack, "CREATE_COMPLETE"); + + XmlPath described = describeKeyPair(name); + String id = described.getString("DescribeKeyPairsResponse.keySet.item.keyPairId"); + assertEquals("ed25519", described.getString("DescribeKeyPairsResponse.keySet.item.keyType")); + assertEquals(Map.of("Name", name, "Id", id, + "Fingerprint", described.getString("DescribeKeyPairsResponse.keySet.item.keyFingerprint")), + outputs(stack)); + assertParameterMissing("/ec2/keypair/" + id); + + deleteStack(stack); + assertKeyPairMissing(name); + } + + @Test + void renamingTheKeyReplacesItAndTheCommittedUpdateDeletesTheOldKeyWithItsParameter() throws Exception { + String stack = unique("cfn-key-rename"); + String first = stack + "-first"; + String next = stack + "-next"; + deploy("CreateStack", stack, template(Key.named(first), false)); + assertStatus(stack, "CREATE_COMPLETE"); + String firstId = keyPairId(first); + + deploy("UpdateStack", stack, template(Key.named(next), false)); + assertStatus(stack, "UPDATE_COMPLETE"); + + assertKeyPairMissing(first); + assertParameterMissing("/ec2/keypair/" + firstId); + String nextId = keyPairId(next); + assertEquals("SecureString", parameter("/ec2/keypair/" + nextId).getString("Parameter.Type")); + assertEquals(next, outputs(stack).get("Name")); + assertEquals(nextId, outputs(stack).get("Id")); + assertTrue(events(stack).stream().anyMatch(event -> first.equals(event.get("PhysicalResourceId")) + && "DELETE_COMPLETE".equals(event.get("ResourceStatus"))), + "the update's cleanup reports the displaced key deleted"); + + deleteStack(stack); + assertKeyPairMissing(next); + assertParameterMissing("/ec2/keypair/" + nextId); + } + + @Test + void aFailedUpdateRollsARenameBackAndDeletesTheReplacementWithItsParameter() throws Exception { + String stack = unique("cfn-key-rollback"); + String first = stack + "-first"; + String next = stack + "-next"; + deploy("CreateStack", stack, template(Key.named(first), false)); + assertStatus(stack, "CREATE_COMPLETE"); + String firstId = keyPairId(first); + Set parametersBefore = keyPairParameters(); + + deploy("UpdateStack", stack, template(Key.named(next), true)); + assertStatus(stack, "UPDATE_ROLLBACK_COMPLETE"); + + assertTrue(hasEvent(stack, next, "UPDATE_COMPLETE"), "the failed update created the replacement"); + assertKeyPairMissing(next); + assertEquals(parametersBefore, keyPairParameters(), "the replacement's parameter is deleted with it"); + assertEquals(firstId, keyPairId(first)); + assertEquals(first, outputs(stack).get("Name")); + assertEquals(firstId, outputs(stack).get("Id")); + assertEquals(first, physicalId(stack)); + + // Nothing was left under the new name, so the rename can be made again. + deploy("UpdateStack", stack, template(Key.named(next), false)); + assertStatus(stack, "UPDATE_COMPLETE"); + String nextId = keyPairId(next); + assertKeyPairMissing(first); + deleteStack(stack); + assertKeyPairMissing(next); + assertParameterMissing("/ec2/keypair/" + nextId); + } + + @Test + void changingAnotherPropertyUnderTheSameNameIsRefusedAndKeepsTheKey() throws Exception { + String stack = unique("cfn-key-same-name"); + String name = stack + "-key"; + deploy("CreateStack", stack, template(Key.named(name), false)); + assertStatus(stack, "CREATE_COMPLETE"); + String id = keyPairId(name); + + deploy("UpdateStack", stack, template(new Key(name, "ed25519", null, null, Map.of()), false)); + assertStatus(stack, "UPDATE_ROLLBACK_COMPLETE"); + + assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. " + + "Rename " + name + " and update the stack again.", CfnStackWaits.failedResourceReason(stack)); + XmlPath described = describeKeyPair(name); + assertEquals(id, described.getString("DescribeKeyPairsResponse.keySet.item.keyPairId")); + assertEquals("rsa", described.getString("DescribeKeyPairsResponse.keySet.item.keyType")); + assertEquals("SecureString", parameter("/ec2/keypair/" + id).getString("Parameter.Type")); + + deleteStack(stack); + assertKeyPairMissing(name); + assertParameterMissing("/ec2/keypair/" + id); + } + + @Test + void aCreateThatFailsLaterDeletesTheKeyAndItsParameter() throws Exception { + String stack = unique("cfn-key-create-rollback"); + String name = stack + "-key"; + Set parametersBefore = keyPairParameters(); + + deploy("CreateStack", stack, template(Key.named(name), true)); + assertStatus(stack, "ROLLBACK_COMPLETE"); + + assertTrue(hasEvent(stack, name, "CREATE_COMPLETE"), "the failed create made the key"); + assertTrue(hasEvent(stack, name, "DELETE_COMPLETE"), "the rollback deleted it"); + assertKeyPairMissing(name); + assertEquals(parametersBefore, keyPairParameters(), "the key's parameter is deleted with it"); + deleteStack(stack); + } + + /** + * Only {@code AWS::NoValue} leaves a property out: an empty string a parameter supplies is a + * value, which an import refuses as it refuses the same string written literally. + */ + @Test + void noValueLeavesPublicKeyMaterialOutButABlankParameterDoesNot() throws Exception { + String stack = unique("cfn-key-no-value"); + String name = stack + "-key"; + Map material = Map.of("Fn::If", List.of("Import", Map.of("Ref", "Material"), + Map.of("Ref", "AWS::NoValue"))); + deploy("CreateStack", stack, parameterTemplate(name, material, "false")); + assertStatus(stack, "CREATE_COMPLETE"); + String id = keyPairId(name); + assertEquals("SecureString", parameter("/ec2/keypair/" + id).getString("Parameter.Type")); + deleteStack(stack); + assertKeyPairMissing(name); + + String blank = unique("cfn-key-blank"); + deploy("CreateStack", blank, parameterTemplate(blank + "-key", Map.of("Ref", "Material"), "true")); + assertStatus(blank, "ROLLBACK_COMPLETE"); + assertEquals("The request must contain the parameter PublicKeyMaterial", + CfnStackWaits.failedResourceReason(blank)); + assertKeyPairMissing(blank + "-key"); + deleteStack(blank); + } + + @Test + void aNameTakenOutsideTheStackFailsTheCreateAndLeavesThatKeyAlone() throws Exception { + String stack = unique("cfn-key-taken"); + String name = stack + "-key"; + String outsideId = ec2("CreateKeyPair").formParam("KeyName", name).post("/") + .then().statusCode(200).extract().xmlPath().getString("CreateKeyPairResponse.keyPairId"); + try { + deploy("CreateStack", stack, template(Key.named(name), false)); + assertStatus(stack, "ROLLBACK_COMPLETE"); + + assertEquals("The keypair '" + name + "' already exists", CfnStackWaits.failedResourceReason(stack)); + assertEquals(outsideId, keyPairId(name)); + deleteStack(stack); + assertEquals(outsideId, keyPairId(name)); + } finally { + ec2("DeleteKeyPair").formParam("KeyPairId", outsideId).post("/").then().statusCode(200); + } + } + + @Test + void aChangeSetReportsAChangedNameOrTypeAsAReplacement() throws Exception { + String stack = unique("cfn-key-change-set"); + String name = stack + "-key"; + deploy("CreateStack", stack, template(new Key(name, "rsa", null, null, Map.of()), false)); + assertStatus(stack, "CREATE_COMPLETE"); + + assertEquals("True", replacement(stack, "renamed", + template(new Key(name + "-next", "rsa", null, null, Map.of()), false))); + assertEquals("True", replacement(stack, "retyped", + template(new Key(name, "ed25519", null, null, Map.of()), false))); + + deleteStack(stack); + assertKeyPairMissing(name); + } + + private static String template(Key key, boolean failAfterKey) throws JsonProcessingException { + Map properties = new LinkedHashMap<>(); + properties.put("KeyName", key.name()); + if (key.keyType() != null) { + properties.put("KeyType", key.keyType()); + } + if (key.keyFormat() != null) { + properties.put("KeyFormat", key.keyFormat()); + } + if (key.publicKeyMaterial() != null) { + properties.put("PublicKeyMaterial", key.publicKeyMaterial()); + } + if (!key.tags().isEmpty()) { + properties.put("Tags", key.tags().entrySet().stream() + .map(tag -> Map.of("Key", tag.getKey(), "Value", tag.getValue())).toList()); + } + Map resources = new LinkedHashMap<>(); + resources.put("Key", Map.of("Type", "AWS::EC2::KeyPair", "Properties", properties)); + if (failAfterKey) { + resources.put("Failure", Map.of("Type", "AWS::SecretsManager::Secret", "DependsOn", List.of("Key"), + "Properties", Map.of("SecretString", "explicit", + "GenerateSecretString", Map.of("PasswordLength", 32)))); + } + Map outputs = Map.of( + "Name", Map.of("Value", Map.of("Ref", "Key")), + "Id", Map.of("Value", Map.of("Fn::GetAtt", List.of("Key", "KeyPairId"))), + "Fingerprint", Map.of("Value", Map.of("Fn::GetAtt", List.of("Key", "KeyFingerprint")))); + return MAPPER.writeValueAsString(Map.of("Resources", resources, "Outputs", outputs)); + } + + /** A key whose PublicKeyMaterial is {@code material}, with a blank Material parameter. */ + private static String parameterTemplate(String name, Object material, String useImport) + throws JsonProcessingException { + return MAPPER.writeValueAsString(Map.of( + "Parameters", Map.of( + "Material", Map.of("Type", "String", "Default", ""), + "UseImport", Map.of("Type", "String", "Default", useImport)), + "Conditions", Map.of("Import", Map.of("Fn::Equals", List.of(Map.of("Ref", "UseImport"), "true"))), + "Resources", Map.of("Key", Map.of("Type", "AWS::EC2::KeyPair", + "Properties", Map.of("KeyName", name, "PublicKeyMaterial", material))))); + } + + private static void deploy(String action, String stack, String template) { + cfn(action, stack).formParam("TemplateBody", template).post("/").then().statusCode(200); + } + + private static void assertStatus(String stack, String expected) { + CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack); + assertEquals(expected, state.status(), state.reason()); + } + + private static void deleteStack(String stack) { + cfn("DeleteStack", stack).post("/").then().statusCode(200); + CfnStackWaits.awaitStackDeleted(stack); + } + + private static Map outputs(String stack) { + String body = cfn("DescribeStacks", stack).post("/").then().statusCode(200).extract().asString(); + return XmlParser.extractPairs(body, "Outputs", "OutputKey", "OutputValue"); + } + + private static String physicalId(String stack) { + String body = cfn("DescribeStackResources", stack).post("/").then().statusCode(200).extract().asString(); + return XmlParser.extractPairs(body, "StackResources", "LogicalResourceId", "PhysicalResourceId").get("Key"); + } + + private static boolean hasEvent(String stack, String physicalId, String status) { + return events(stack).stream().anyMatch(event -> "Key".equals(event.get("LogicalResourceId")) + && physicalId.equals(event.get("PhysicalResourceId")) && status.equals(event.get("ResourceStatus"))); + } + + private static List> events(String stack) { + String body = cfn("DescribeStackEvents", stack).post("/").then().statusCode(200).extract().asString(); + return XmlParser.extractGroups(body, "member"); + } + + /** The {@code Replacement} a change set to {@code template} reports for the key. */ + private static String replacement(String stack, String changeSet, String template) { + cfn("CreateChangeSet", stack).formParam("ChangeSetName", changeSet).formParam("ChangeSetType", "UPDATE") + .formParam("TemplateBody", template).post("/").then().statusCode(200); + return cfn("DescribeChangeSet", stack).formParam("ChangeSetName", changeSet).post("/") + .then().statusCode(200).extract().xmlPath() + .getString("**.find { it.name() == 'ResourceChange' }.Replacement"); + } + + private static RequestSpecification ec2(String action) { + return given().contentType("application/x-www-form-urlencoded").formParam("Action", action); + } + + private static XmlPath describeKeyPair(String name) { + return ec2("DescribeKeyPairs").formParam("KeyName.1", name).post("/") + .then().statusCode(200).extract().xmlPath(); + } + + private static String keyPairId(String name) { + return describeKeyPair(name).getString("DescribeKeyPairsResponse.keySet.item.keyPairId"); + } + + private static void assertKeyPairMissing(String name) { + Response response = ec2("DescribeKeyPairs").formParam("KeyName.1", name).post("/"); + assertEquals(400, response.statusCode(), response.asString()); + assertTrue(response.asString().contains("InvalidKeyPair.NotFound"), response.asString()); + } + + /** The private key EC2 holds for the key pair, read past the API, which never returns it again. */ + private String storedPrivateKey(String keyPairId) { + return ec2Service.describeKeyPairs(REGION, List.of(), List.of(keyPairId)).getFirst().getKeyMaterial(); + } + + private static Response ssm(String operation, Map body) throws JsonProcessingException { + return given().contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AmazonSSM." + operation).body(MAPPER.writeValueAsString(body)).post("/"); + } + + private static JsonPath parameter(String name) throws JsonProcessingException { + Response response = ssm("GetParameter", Map.of("Name", name, "WithDecryption", true)); + assertEquals(200, response.statusCode(), "GetParameter " + name); + return response.jsonPath(); + } + + private static void assertParameterMissing(String name) throws JsonProcessingException { + Response response = ssm("GetParameter", Map.of("Name", name)); + assertEquals(400, response.statusCode(), response.asString()); + assertTrue(response.asString().contains("ParameterNotFound"), response.asString()); + } + + /** The names of every parameter under {@code /ec2/keypair}, the path the stack stores private keys in. */ + private static Set keyPairParameters() throws JsonProcessingException { + Set names = new TreeSet<>(); + String token = null; + do { + Map request = new LinkedHashMap<>(); + request.put("Path", "/ec2/keypair"); + if (token != null) { + request.put("NextToken", token); + } + JsonPath page = ssm("GetParametersByPath", request).then().statusCode(200).extract().jsonPath(); + names.addAll(page.getList("Parameters.Name", String.class)); + token = page.getString("NextToken"); + } while (token != null && !token.isEmpty()); + return names; + } + + private static String unique(String prefix) { + return prefix + "-" + Long.toString(System.nanoTime(), 36); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2KeyPairCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2KeyPairCfnProvisionerTest.java new file mode 100644 index 0000000000..fe11c0e3cb --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2KeyPairCfnProvisionerTest.java @@ -0,0 +1,781 @@ +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 io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.KeyPair; +import io.github.hectorvent.floci.services.ec2.model.Tag; +import io.github.hectorvent.floci.services.ssm.SsmEventPublisher; +import io.github.hectorvent.floci.services.ssm.SsmService; +import io.github.hectorvent.floci.services.ssm.model.Parameter; +import io.github.hectorvent.floci.services.ssm.model.ParameterHistory; +import io.github.hectorvent.floci.testing.InMemoryStorageFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +/** + * {@code AWS::EC2::KeyPair} in isolation: the name backs {@code Ref} and the key's id and fingerprint + * back {@code Fn::GetAtt}; a created key keeps its private key in the {@code SecureString} parameter + * {@code /ec2/keypair/} and an imported one writes none; every property is create-only, so + * an update either changes nothing, renames the key by replacing it, or is refused; and each way a key + * leaves the stack takes its parameter with it. + */ +class Ec2KeyPairCfnProvisionerTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT_ID = "000000000000"; + private static final String CUSTOM_NAMED_REPLACEMENT = "CloudFormation cannot update a stack when a " + + "custom-named resource requires replacing. Rename deploy and update the stack again."; + + 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(); + + @Test + void aCreatedKeyBacksRefAndGetAttAndKeepsItsPrivateKeyInASecureStringParameter() throws Exception { + when(ec2.createKeyPair(REGION, "deploy", null, null)).thenReturn(created("deploy", "key-1")); + + StackResource r = resource(); + provisioner.provision(r, props("{\"KeyName\": \"deploy\"}"), ctx(null)); + + assertEquals("deploy", r.getPhysicalId()); + assertEquals("key-1", r.getAttributes().get("KeyPairId")); + assertEquals("fingerprint-key-1", r.getAttributes().get("KeyFingerprint")); + verify(ssm).putParameter("/ec2/keypair/key-1", "private-key-1", "SecureString", null, false, REGION); + assertFalse(r.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR)); + assertFalse(r.getAttributes().containsValue("private-key-1"), + "the private key lives in the parameter only, never on the stack resource"); + } + + @ParameterizedTest + @CsvSource({"ed25519,", ",ppk", "rsa,ppk", "ed25519,ppk", "rsa,pem"}) + void keyTypeAndKeyFormatReachCreateKeyPair(String keyType, String keyFormat) throws Exception { + when(ec2.createKeyPair(REGION, "deploy", keyType, keyFormat)).thenReturn(created("deploy", "key-1")); + StringBuilder json = new StringBuilder("{\"KeyName\": \"deploy\""); + if (keyType != null) { + json.append(", \"KeyType\": \"").append(keyType).append('"'); + } + if (keyFormat != null) { + json.append(", \"KeyFormat\": \"").append(keyFormat).append('"'); + } + + provisioner.provision(resource(), props(json.append('}').toString()), ctx(null)); + + verify(ec2).createKeyPair(REGION, "deploy", keyType, keyFormat); + verify(ssm).putParameter("/ec2/keypair/key-1", "private-key-1", "SecureString", null, false, REGION); + } + + @Test + void anImportedKeyIgnoresKeyTypeAndKeyFormatAndWritesNoParameter() throws Exception { + when(ec2.importKeyPair(REGION, "deploy", "ssh-ed25519 AAAA")).thenReturn(imported("deploy", "key-2")); + + StackResource r = resource(); + provisioner.provision(r, props("{\"KeyName\": \"deploy\", \"PublicKeyMaterial\": \"ssh-ed25519 AAAA\"," + + " \"KeyType\": \"rsa\", \"KeyFormat\": \"ppk\"}"), ctx(null)); + + assertEquals("deploy", r.getPhysicalId()); + assertEquals("key-2", r.getAttributes().get("KeyPairId")); + assertEquals("fingerprint-key-2", r.getAttributes().get("KeyFingerprint")); + verify(ec2, never()).createKeyPair(anyString(), anyString(), any(), any()); + verifyNoInteractions(ssm); + } + + /** {@code AWS::NoValue} leaves the property out. */ + @Test + void noValueLeavesAPropertyOut() throws Exception { + when(ec2.createKeyPair(REGION, "deploy", null, null)).thenReturn(created("deploy", "key-1")); + + provisioner.provision(resource(), props("{\"KeyName\": \"deploy\"," + + " \"PublicKeyMaterial\": {\"Ref\": \"AWS::NoValue\"}, \"KeyType\": {\"Ref\": \"AWS::NoValue\"}}"), + ctx(null)); + + verify(ec2).createKeyPair(REGION, "deploy", null, null); + verify(ec2, never()).importKeyPair(anyString(), anyString(), anyString()); + } + + /** An empty string a parameter supplies is a value, as the same string written literally is. */ + @Test + void aBlankValueFromAParameterIsNotLeftOut() throws Exception { + AwsException refused = assertThrows(AwsException.class, () -> provisioner.provision(resource(), + props("{\"KeyName\": \"deploy\", \"PublicKeyMaterial\": {\"Ref\": \"Blank\"}}"), ctx(null))); + assertEquals("MissingParameter", refused.getErrorCode()); + assertEquals("The request must contain the parameter PublicKeyMaterial", refused.getMessage()); + AwsException badType = assertThrows(AwsException.class, () -> provisioner.provision(resource(), + props("{\"KeyName\": \"deploy\", \"KeyType\": {\"Ref\": \"Blank\"}}"), ctx(null))); + assertEquals("ValidationError", badType.getErrorCode()); + + verifyNoInteractions(ec2, ssm); + } + + /** Only an empty material is missing; whitespace is material, which ImportKeyPair judges itself. */ + @Test + void whitespaceMaterialIsLeftToImportKeyPair() throws Exception { + when(ec2.importKeyPair(REGION, "deploy", " ")) + .thenThrow(new AwsException("InvalidKey.Format", "Key is not in valid OpenSSH public key format", 400)); + + AwsException refused = assertThrows(AwsException.class, () -> provisioner.provision(resource(), + props("{\"KeyName\": \"deploy\", \"PublicKeyMaterial\": \" \"}"), ctx(null))); + + assertEquals("InvalidKey.Format", refused.getErrorCode()); + verifyNoInteractions(ssm); + } + + @Test + void tagsAreWrittenToTheNewKeyBeforeItsParameter() throws Exception { + when(ec2.createKeyPair(REGION, "deploy", null, null)).thenReturn(created("deploy", "key-1")); + + provisioner.provision(resource(), props("{\"KeyName\": \"deploy\"," + + " \"Tags\": [{\"Key\": \"team\", \"Value\": \"infra\"}]}"), ctx(null)); + + InOrder order = inOrder(ec2, ssm); + @SuppressWarnings("unchecked") + ArgumentCaptor> tags = ArgumentCaptor.forClass(List.class); + order.verify(ec2).createTags(eq(REGION), eq(List.of("key-1")), tags.capture()); + order.verify(ssm).putParameter("/ec2/keypair/key-1", "private-key-1", "SecureString", null, false, REGION); + assertEquals(Map.of("team", "infra"), + tags.getValue().stream().collect(Collectors.toMap(Tag::getKey, Tag::getValue))); + } + + @ParameterizedTest + @ValueSource(strings = { + "{}", + "{\"KeyName\": \"\"}", + "{\"KeyName\": \"deploy\", \"KeyType\": \"dsa\"}", + "{\"KeyName\": \"deploy\", \"KeyFormat\": \"der\"}", + "{\"KeyName\": \"deploy\", \"PublicKeyMaterial\": \"ssh-ed25519 AAAA\", \"KeyType\": \"dsa\"}", + "{\"KeyName\": \"deploy\", \"Tags\": [{\"Key\": \"aws:reserved\", \"Value\": \"x\"}]}", + "{\"KeyName\": \"deploy\", \"PublicKeyMaterial\": \"\"}" + }) + void invalidPropertiesFailBeforeAnythingIsCreated(String json) { + AwsException failure = assertThrows(AwsException.class, + () -> provisioner.provision(resource(), props(json), ctx(null))); + + assertTrue(Set.of("ValidationError", "InvalidParameterValue", "MissingParameter") + .contains(failure.getErrorCode()), failure.getErrorCode()); + verifyNoInteractions(ec2, ssm); + } + + @Test + void aFailedParameterWriteDeletesTheNewKeyAndReportsTheWriteFailure() { + when(ec2.createKeyPair(REGION, "deploy", null, null)).thenReturn(created("deploy", "key-1")); + AwsException writeFailure = new AwsException("InternalServerError", "simulated write failure", 500); + when(ssm.putParameter(anyString(), anyString(), anyString(), any(), anyBoolean(), anyString())) + .thenThrow(writeFailure); + + StackResource r = resource(); + assertSame(writeFailure, assertThrows(AwsException.class, + () -> provisioner.provision(r, props("{\"KeyName\": \"deploy\"}"), ctx(null)))); + + verify(ec2).deleteKeyPair(REGION, null, "key-1"); + verify(ssm).deleteParameter("/ec2/keypair/key-1", REGION); + assertFalse(r.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR)); + } + + @Test + void aFailedHistoryWriteRemovesTheSavedPrivateKeyParameter() { + InMemoryStorage parameters = new InMemoryStorage<>(); + InMemoryStorage> history = spy(new InMemoryStorage<>()); + SsmService realSsm = realSsm(parameters, history); + IllegalStateException writeFailure = new IllegalStateException("simulated history write failure"); + doThrow(writeFailure).when(history).put(anyString(), anyList()); + when(ec2.createKeyPair(REGION, "deploy", null, null)).thenReturn(created("deploy", "key-1")); + Ec2KeyPairCfnProvisioner realProvisioner = new Ec2KeyPairCfnProvisioner(ec2, realSsm); + StackResource resource = resource(); + + assertSame(writeFailure, assertThrows(IllegalStateException.class, + () -> realProvisioner.provision(resource, props("{\"KeyName\": \"deploy\"}"), ctx(null)))); + + AwsException missing = assertThrows(AwsException.class, + () -> realSsm.getParameter("/ec2/keypair/key-1", REGION)); + assertEquals("ParameterNotFound", missing.getErrorCode()); + verify(ec2).deleteKeyPair(REGION, null, "key-1"); + assertFalse(resource.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR)); + } + + @Test + void aFailedParameterUndoRetainsTheKeyForTheStackRollback() throws Exception { + InMemoryStorage parameters = spy(new InMemoryStorage<>()); + InMemoryStorage> history = spy(new InMemoryStorage<>()); + SsmService realSsm = realSsm(parameters, history); + IllegalStateException writeFailure = new IllegalStateException("simulated history write failure"); + IllegalStateException undoFailure = new IllegalStateException("simulated parameter delete failure"); + doThrow(writeFailure).when(history).put(anyString(), anyList()); + doThrow(undoFailure).doCallRealMethod().when(parameters).delete(anyString()); + when(ec2.createKeyPair(REGION, "deploy", null, null)).thenReturn(created("deploy", "key-1")); + Ec2KeyPairCfnProvisioner realProvisioner = new Ec2KeyPairCfnProvisioner(ec2, realSsm); + StackResource resource = resource(); + + assertSame(writeFailure, assertThrows(IllegalStateException.class, + () -> realProvisioner.provision(resource, props("{\"KeyName\": \"deploy\"}"), ctx(null)))); + + assertEquals("true", resource.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR)); + assertArrayEquals(new Throwable[]{undoFailure}, writeFailure.getSuppressed()); + verify(ec2, never()).deleteKeyPair(anyString(), any(), any()); + + when(ec2.describeKeyPairs(REGION, List.of("deploy"), List.of())) + .thenReturn(List.of(created("deploy", "key-1"))); + realProvisioner.delete(resource, REGION); + + assertEquals("ParameterNotFound", assertThrows(AwsException.class, + () -> realSsm.getParameter("/ec2/keypair/key-1", REGION)).getErrorCode()); + verify(ec2).deleteKeyPair(REGION, null, "key-1"); + } + + @Test + void aFailedReplacementRetainsItsParameterIdWhenTheKeyDisappearsBeforeCleanup() throws Exception { + InMemoryStorage parameters = spy(new InMemoryStorage<>()); + InMemoryStorage> history = spy(new InMemoryStorage<>()); + SsmService realSsm = realSsm(parameters, history); + 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)); + IllegalStateException writeFailure = new IllegalStateException("simulated history write failure"); + doThrow(writeFailure).when(history).put(anyString(), anyList()); + doThrow(new IllegalStateException("simulated parameter delete failure")) + .doCallRealMethod().when(parameters).delete(anyString()); + StackResource attempted = resource(); + attempted.setPhysicalId(previous.getPhysicalId()); + attempted.getAttributes().putAll(previous.getAttributes()); + + assertSame(writeFailure, assertThrows(IllegalStateException.class, + () -> realProvisioner.provision(attempted, props("{\"KeyName\": \"next\"}"), ctx("first")))); + ReplacementCleanup.mergeDisplaced(previous, attempted); + realProvisioner.mergeFailedUpdateResourceTracking(previous, attempted); + when(ec2.describeKeyPairs(REGION, List.of("next"), List.of())) + .thenThrow(new AwsException("InvalidKeyPair.NotFound", "The key was deleted outside the stack", 400)); + + assertTrue(realProvisioner.completeUpdate(previous).complete()); + + assertEquals("ParameterNotFound", assertThrows(AwsException.class, + () -> realSsm.getParameter("/ec2/keypair/key-2", REGION)).getErrorCode()); + assertEquals("private-key-1", realSsm.getParameter("/ec2/keypair/key-1", REGION).getValue()); + verify(ec2, never()).deleteKeyPair(anyString(), any(), any()); + } + + @Test + void aFailedTagWriteDeletesTheNewKeyAndToleratesItsMissingParameter() { + 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()); + } + + /** The engine's create rollback deletes a key the provision's own undo could not. */ + @Test + void aKeyTheUndoCouldNotDeleteStaysOwnedForTheStackRollback() throws Exception { + 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()); + when(ec2.deleteKeyPair(REGION, null, "key-1")) + .thenThrow(new AwsException("InternalServerError", "simulated delete failure", 500)) + .thenReturn(null); + + StackResource r = resource(); + assertSame(tagFailure, assertThrows(AwsException.class, () -> provisioner.provision(r, + props("{\"KeyName\": \"deploy\", \"Tags\": [{\"Key\": \"team\", \"Value\": \"infra\"}]}"), + ctx(null)))); + assertEquals(1, tagFailure.getSuppressed().length); + assertEquals("deploy", r.getPhysicalId()); + assertEquals("true", r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR)); + + when(ec2.describeKeyPairs(REGION, List.of("deploy"), List.of())) + .thenReturn(List.of(created("deploy", "key-1"))); + provisioner.delete(r, REGION); + + verify(ec2, times(2)).deleteKeyPair(REGION, null, "key-1"); + } + + @Test + void anUpdateThatChangesNoPropertyKeepsTheKey() throws Exception { + when(ec2.createKeyPair(REGION, "deploy", "ed25519", null)).thenReturn(created("deploy", "key-1")); + String template = "{\"KeyName\": \"deploy\", \"KeyType\": \"ed25519\"," + + " \"Tags\": [{\"Key\": \"a\", \"Value\": \"1\"}, {\"Key\": \"b\", \"Value\": \"2\"}]}"; + StackResource r = resource(); + provisioner.provision(r, props(template), ctx(null)); + + // Tags are a set: the same tags in another order are no change. + provisioner.provision(r, props("{\"KeyName\": \"deploy\", \"KeyType\": \"ed25519\"," + + " \"Tags\": [{\"Key\": \"b\", \"Value\": \"2\"}, {\"Key\": \"a\", \"Value\": \"1\"}]}"), + ctx("deploy")); + + assertEquals("deploy", r.getPhysicalId()); + assertEquals("key-1", r.getAttributes().get("KeyPairId")); + verify(ec2, times(1)).createKeyPair(anyString(), anyString(), any(), any()); + verify(ssm, times(1)).putParameter(anyString(), anyString(), anyString(), any(), anyBoolean(), anyString()); + assertFalse(provisioner.hasReplacementUpdate(r)); + assertTrue(provisioner.rollbackUpdate(r), "an update that changed nothing has nothing to undo"); + verify(ec2, never()).deleteKeyPair(anyString(), any(), any()); + } + + /** A property the inputs record lacks counts as absent, so the template that leaves it out matches. */ + @Test + void aRecordWithoutAPropertyStillMatchesATemplateThatLeavesItOut() throws Exception { + StackResource r = resource(); + r.setPhysicalId("deploy"); + r.getAttributes().put("KeyPairId", "key-1"); + r.getAttributes().put("__FlociKeyPairInputs", "{\"KeyName\":\"deploy\",\"KeyType\":null}"); + + provisioner.provision(r, props("{\"KeyName\": \"deploy\"}"), ctx("deploy")); + + assertEquals("key-1", r.getAttributes().get("KeyPairId")); + verifyNoInteractions(ec2, ssm); + } + + /** A property the inputs record lacks is absent, so a template that now sets it changes the key. */ + @Test + void aRecordWithoutAPropertyDoesNotMatchATemplateThatSetsIt() throws Exception { + StackResource r = resource(); + r.setPhysicalId("deploy"); + r.getAttributes().put("KeyPairId", "key-1"); + r.getAttributes().put("__FlociKeyPairInputs", "{\"KeyName\":\"deploy\",\"KeyType\":null}"); + + AwsException refused = assertThrows(AwsException.class, () -> provisioner.provision(r, + props("{\"KeyName\": \"deploy\", \"Tags\": [{\"Key\": \"team\", \"Value\": \"infra\"}]}"), + ctx("deploy"))); + + assertEquals(CUSTOM_NAMED_REPLACEMENT, refused.getMessage()); + verifyNoInteractions(ec2, ssm); + } + + /** Dropping a property is a change too: the key made with it is not the key the template asks for. */ + @ParameterizedTest + @ValueSource(strings = { + "{\"KeyName\": \"deploy\", \"KeyType\": \"ed25519\"}", + "{\"KeyName\": \"deploy\", \"KeyFormat\": \"ppk\"}", + "{\"KeyName\": \"deploy\", \"Tags\": [{\"Key\": \"team\", \"Value\": \"infra\"}]}" + }) + void droppingAPropertyUnderTheSameNameIsRefusedToo(String json) throws Exception { + when(ec2.createKeyPair(eq(REGION), eq("deploy"), any(), any())).thenReturn(created("deploy", "key-1")); + StackResource r = resource(); + provisioner.provision(r, props(json), ctx(null)); + + AwsException refused = assertThrows(AwsException.class, + () -> provisioner.provision(r, props("{\"KeyName\": \"deploy\"}"), ctx("deploy"))); + + assertEquals(CUSTOM_NAMED_REPLACEMENT, refused.getMessage()); + verify(ec2, times(1)).createKeyPair(anyString(), anyString(), any(), any()); + assertEquals("key-1", r.getAttributes().get("KeyPairId")); + } + + @ParameterizedTest + @ValueSource(strings = { + "{\"KeyName\": \"deploy\", \"KeyType\": \"ed25519\"}", + "{\"KeyName\": \"deploy\", \"KeyType\": \"rsa\"}", + "{\"KeyName\": \"deploy\", \"KeyFormat\": \"ppk\"}", + "{\"KeyName\": \"deploy\", \"PublicKeyMaterial\": \"ssh-ed25519 AAAA\"}", + "{\"KeyName\": \"deploy\", \"PublicKeyMaterial\": \"\"}", + "{\"KeyName\": \"deploy\", \"Tags\": [{\"Key\": \"team\", \"Value\": \"infra\"}]}" + }) + void changingAnotherPropertyUnderTheSameNameIsRefusedAsCloudFormationRefusesIt(String json) throws Exception { + when(ec2.createKeyPair(REGION, "deploy", null, null)).thenReturn(created("deploy", "key-1")); + StackResource r = resource(); + provisioner.provision(r, props("{\"KeyName\": \"deploy\"}"), ctx(null)); + + AwsException refused = assertThrows(AwsException.class, + () -> provisioner.provision(r, props(json), ctx("deploy"))); + + assertEquals("ValidationError", refused.getErrorCode()); + assertEquals(CUSTOM_NAMED_REPLACEMENT, refused.getMessage()); + verify(ec2, times(1)).createKeyPair(anyString(), anyString(), any(), any()); + verify(ec2, never()).importKeyPair(anyString(), anyString(), anyString()); + assertEquals("key-1", r.getAttributes().get("KeyPairId")); + } + + @Test + void aRenameCreatesTheNewKeyAndTheCommittedUpdateDeletesTheOldOneWithItsParameter() throws Exception { + StackResource r = renamed(); + + assertEquals("next", r.getPhysicalId()); + assertEquals("key-2", r.getAttributes().get("KeyPairId")); + assertEquals("fingerprint-key-2", r.getAttributes().get("KeyFingerprint")); + verify(ssm).putParameter("/ec2/keypair/key-2", "private-key-2", "SecureString", null, false, REGION); + assertTrue(provisioner.hasReplacementUpdate(r)); + assertEquals("first", provisioner.updateCleanupPhysicalId(r)); + + when(ec2.describeKeyPairs(REGION, List.of("first"), List.of())).thenReturn(List.of(created("first", "key-1"))); + UpdateCleanupResult result = provisioner.completeUpdate(r); + provisioner.clearUpdate(r); + + assertTrue(result.complete(), String.valueOf(result)); + verify(ssm).deleteParameter("/ec2/keypair/key-1", REGION); + verify(ec2).deleteKeyPair(REGION, null, "key-1"); + verify(ec2, never()).deleteKeyPair(REGION, null, "key-2"); + assertFalse(provisioner.hasReplacementUpdate(r)); + } + + @Test + void aRolledBackRenameNamesTheOriginalKeyAgainAndDeletesTheReplacement() throws Exception { + StackResource r = renamed(); + when(ec2.describeKeyPairs(REGION, List.of("next"), List.of())).thenReturn(List.of(created("next", "key-2"))); + + assertTrue(provisioner.rollbackUpdate(r)); + + assertEquals("first", r.getPhysicalId()); + assertEquals("key-1", r.getAttributes().get("KeyPairId")); + assertEquals("fingerprint-key-1", r.getAttributes().get("KeyFingerprint")); + verify(ssm).deleteParameter("/ec2/keypair/key-2", REGION); + verify(ec2).deleteKeyPair(REGION, null, "key-2"); + verify(ec2, never()).deleteKeyPair(REGION, null, "key-1"); + assertFalse(provisioner.hasReplacementUpdate(r)); + + // The original template is again no change to the key it names. + provisioner.provision(r, props("{\"KeyName\": \"first\"}"), ctx("first")); + verify(ec2, times(1)).createKeyPair(REGION, "first", null, null); + assertEquals("key-1", r.getAttributes().get("KeyPairId")); + } + + /** A rollback whose delete of the replacement fails is finished by ContinueUpdateRollback. */ + @Test + void aReplacementTheRollbackCouldNotDeleteIsDeletedByTheRetry() throws Exception { + StackResource r = renamed(); + when(ec2.describeKeyPairs(REGION, List.of("next"), List.of())).thenReturn(List.of(created("next", "key-2"))); + when(ec2.deleteKeyPair(REGION, null, "key-2")) + .thenThrow(new AwsException("InternalServerError", "simulated delete failure", 500)) + .thenReturn(null); + + assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)); + assertEquals("first", r.getPhysicalId()); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(ec2, times(2)).deleteKeyPair(REGION, null, "key-2"); + assertFalse(provisioner.hasReplacementUpdate(r)); + provisioner.provision(r, props("{\"KeyName\": \"first\"}"), ctx("first")); + verify(ec2, times(1)).createKeyPair(REGION, "first", null, null); + } + + /** + * Pins the {@link ReplacementCleanup#endRollbackRetry} contract: a rollback of a later update + * that failed before creating anything does not retry the delete an earlier rollback left, and + * the next committed update still deletes that replacement. The engine does not reach this today, + * since it restores the previous resource when a key pair update fails instead of rolling the + * attempt back; it would once the provisioner kept its failed update state. + */ + @Test + void aLaterFailedUpdateDoesNotRetryTheDeleteAnEarlierRollbackLeft() throws Exception { + StackResource r = renamed(); + when(ec2.describeKeyPairs(REGION, List.of("next"), List.of())).thenReturn(List.of(created("next", "key-2"))); + when(ec2.deleteKeyPair(REGION, null, "key-2")) + .thenThrow(new AwsException("InternalServerError", "simulated delete failure", 500)) + .thenReturn(null); + assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)); + + assertThrows(AwsException.class, + () -> provisioner.provision(r, props("{\"KeyName\": \"first\", \"KeyType\": \"ed25519\"}"), ctx("first"))); + assertTrue(provisioner.rollbackUpdate(r)); + verify(ec2, times(1)).deleteKeyPair(REGION, null, "key-2"); + + provisioner.provision(r, props("{\"KeyName\": \"first\"}"), ctx("first")); + assertTrue(provisioner.completeUpdate(r).complete()); + verify(ec2, times(2)).deleteKeyPair(REGION, null, "key-2"); + verify(ec2, never()).deleteKeyPair(REGION, null, "key-1"); + } + + /** The cleanup goes by name, yet a displaced key deleted outside the stack still takes its parameter. */ + @Test + void theCommittedRenameRemovesTheParameterOfADisplacedKeyDeletedOutsideTheStack() throws Exception { + StackResource r = renamed(); + when(ec2.describeKeyPairs(REGION, List.of("first"), List.of())) + .thenThrow(new AwsException("InvalidKeyPair.NotFound", "The key pair 'first' does not exist", 400)); + + assertTrue(provisioner.completeUpdate(r).complete()); + provisioner.clearUpdate(r); + + verify(ssm).deleteParameter("/ec2/keypair/key-1", REGION); + verify(ssm, never()).deleteParameter("/ec2/keypair/key-2", REGION); + verify(ec2, never()).deleteKeyPair(anyString(), any(), any()); + assertFalse(r.getAttributes().containsKey("__FlociKeyPairCreatedKeys")); + } + + @Test + void aRolledBackRenameRemovesTheParameterOfAReplacementDeletedOutsideTheStack() throws Exception { + StackResource r = renamed(); + when(ec2.describeKeyPairs(REGION, List.of("next"), List.of())) + .thenThrow(new AwsException("InvalidKeyPair.NotFound", "The key pair 'next' does not exist", 400)); + + assertTrue(provisioner.rollbackUpdate(r)); + + assertEquals("first", r.getPhysicalId()); + verify(ssm).deleteParameter("/ec2/keypair/key-2", REGION); + verify(ssm, never()).deleteParameter("/ec2/keypair/key-1", REGION); + verify(ec2, never()).deleteKeyPair(anyString(), any(), any()); + assertFalse(r.getAttributes().containsKey("__FlociKeyPairCreatedKeys")); + } + + /** The retry runs after the revert, when the resource records the original key, not the replacement. */ + @Test + void theRollbackRetryStillRemovesTheParameterOfAReplacementGoneSinceTheFirstAttempt() throws Exception { + StackResource r = renamed(); + when(ec2.describeKeyPairs(REGION, List.of("next"), List.of())) + .thenReturn(List.of(created("next", "key-2"))) + .thenThrow(new AwsException("InvalidKeyPair.NotFound", "The key pair 'next' does not exist", 400)); + when(ec2.deleteKeyPair(REGION, null, "key-2")) + .thenThrow(new AwsException("InternalServerError", "simulated delete failure", 500)); + + assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)); + assertTrue(provisioner.rollbackUpdate(r)); + + verify(ssm, times(2)).deleteParameter("/ec2/keypair/key-2", REGION); + verify(ssm, never()).deleteParameter("/ec2/keypair/key-1", REGION); + assertFalse(provisioner.hasReplacementUpdate(r)); + assertFalse(r.getAttributes().containsKey("__FlociKeyPairCreatedKeys")); + } + + @Test + void aDisplacedImportedKeyDeletedOutsideTheStackLeavesParameterStoreAlone() throws Exception { + when(ec2.importKeyPair(REGION, "first", "ssh-ed25519 AAAA")).thenReturn(imported("first", "key-1")); + when(ec2.createKeyPair(REGION, "next", null, null)).thenReturn(created("next", "key-2")); + StackResource r = resource(); + provisioner.provision(r, props("{\"KeyName\": \"first\", \"PublicKeyMaterial\": \"ssh-ed25519 AAAA\"}"), ctx(null)); + provisioner.provision(r, props("{\"KeyName\": \"next\"}"), ctx("first")); + when(ec2.describeKeyPairs(REGION, List.of("first"), List.of())) + .thenThrow(new AwsException("InvalidKeyPair.NotFound", "The key pair 'first' does not exist", 400)); + + assertTrue(provisioner.completeUpdate(r).complete()); + + verify(ssm, never()).deleteParameter(anyString(), anyString()); + } + + /** A key deleted outside the stack still has its parameter removed when the stack is deleted. */ + @Test + void stackDeleteRemovesTheParameterOfAKeyDeletedOutsideTheStack() throws Exception { + StackResource created = provisioned("{\"KeyName\": \"deploy\"}"); + when(ec2.describeKeyPairs(REGION, List.of("deploy"), List.of())) + .thenThrow(new AwsException("InvalidKeyPair.NotFound", "The key pair 'deploy' does not exist", 400)); + + provisioner.delete(created, REGION); + + verify(ssm).deleteParameter("/ec2/keypair/key-1", REGION); + verify(ec2, never()).deleteKeyPair(anyString(), any(), any()); + } + + /** + * The delete follows the name, as Cloud Control's DeleteResource names the key by it alone: a key + * made under the name outside the stack is the one deleted, with its parameter, and the parameter + * the stack's own key left is deleted too. + */ + @Test + void stackDeleteFollowsTheNameAndStillRemovesTheRecordedKeysParameter() throws Exception { + StackResource created = provisioned("{\"KeyName\": \"deploy\"}"); + when(ec2.describeKeyPairs(REGION, List.of("deploy"), List.of())) + .thenReturn(List.of(created("deploy", "key-9"))); + + provisioner.delete(created, REGION); + + verify(ssm).deleteParameter("/ec2/keypair/key-9", REGION); + verify(ec2).deleteKeyPair(REGION, null, "key-9"); + verify(ssm).deleteParameter("/ec2/keypair/key-1", REGION); + } + + /** An imported key has no parameter, whether or not it is still there. */ + @Test + void stackDeleteOfAnImportedKeyLeavesParameterStoreAlone() throws Exception { + when(ec2.importKeyPair(REGION, "deploy", "ssh-ed25519 AAAA")).thenReturn(imported("deploy", "key-2")); + StackResource imported = resource(); + provisioner.provision(imported, + props("{\"KeyName\": \"deploy\", \"PublicKeyMaterial\": \"ssh-ed25519 AAAA\"}"), ctx(null)); + when(ec2.describeKeyPairs(REGION, List.of("deploy"), List.of())) + .thenReturn(List.of(imported("deploy", "key-2"))) + .thenThrow(new AwsException("InvalidKeyPair.NotFound", "The key pair 'deploy' does not exist", 400)); + + provisioner.delete(imported, REGION); + provisioner.delete(imported, REGION); + + verify(ec2, times(1)).deleteKeyPair(REGION, null, "key-2"); + verifyNoInteractions(ssm); + } + + @Test + void deletingACreatedKeyDeletesItsParameterThenTheKey() { + when(ec2.describeKeyPairs(REGION, List.of("deploy"), List.of())) + .thenReturn(List.of(created("deploy", "key-1"))); + + provisioner.delete("AWS::EC2::KeyPair", "deploy", REGION); + + InOrder order = inOrder(ssm, ec2); + order.verify(ssm).deleteParameter("/ec2/keypair/key-1", REGION); + order.verify(ec2).deleteKeyPair(REGION, null, "key-1"); + } + + @Test + void deletingAnImportedKeyLeavesParameterStoreAlone() { + when(ec2.describeKeyPairs(REGION, List.of("deploy"), List.of())) + .thenReturn(List.of(imported("deploy", "key-2"))); + + provisioner.delete("AWS::EC2::KeyPair", "deploy", REGION); + + verify(ec2).deleteKeyPair(REGION, null, "key-2"); + verifyNoInteractions(ssm); + } + + @Test + void deletingAKeyThatIsAlreadyGoneSucceeds() { + when(ec2.describeKeyPairs(REGION, List.of("deploy"), List.of())) + .thenThrow(new AwsException("InvalidKeyPair.NotFound", "The key pair 'deploy' does not exist", 400)); + + assertDoesNotThrow(() -> provisioner.delete("AWS::EC2::KeyPair", "deploy", REGION)); + + verify(ec2, never()).deleteKeyPair(anyString(), any(), any()); + verifyNoInteractions(ssm); + } + + @Test + void aParameterThatIsAlreadyGoneStillLetsTheKeyBeDeleted() { + when(ec2.describeKeyPairs(REGION, List.of("deploy"), List.of())) + .thenReturn(List.of(created("deploy", "key-1"))); + doThrow(new AwsException("ParameterNotFound", "Parameter /ec2/keypair/key-1 not found.", 400)) + .when(ssm).deleteParameter("/ec2/keypair/key-1", REGION); + + provisioner.delete("AWS::EC2::KeyPair", "deploy", REGION); + + verify(ec2).deleteKeyPair(REGION, null, "key-1"); + } + + @Test + void aParameterDeleteThatFailsKeepsTheKeyForTheRetry() { + when(ec2.describeKeyPairs(REGION, List.of("deploy"), List.of())) + .thenReturn(List.of(created("deploy", "key-1"))); + doThrow(new AwsException("AccessDeniedException", "simulated denial", 400)) + .when(ssm).deleteParameter("/ec2/keypair/key-1", REGION); + + assertThrows(AwsException.class, () -> provisioner.delete("AWS::EC2::KeyPair", "deploy", REGION)); + + verify(ec2, never()).deleteKeyPair(anyString(), any(), any()); + } + + /** A stack created while this type was stubbed holds a stub, which names no key. */ + @Test + void aStubFromBeforeThisTypeWasProvisionedIsReplacedByARealKey() throws Exception { + StackResource stub = resource(); + stub.setPhysicalId("Key-0a1b2c3d"); + stub.getAttributes().put("Arn", CfnResourceDispatcher.STUB_ARN_PREFIX + "Key"); + provisioner.delete(stub, REGION); + verifyNoInteractions(ec2, ssm); + + when(ec2.createKeyPair(REGION, "deploy", null, null)).thenReturn(created("deploy", "key-1")); + provisioner.provision(stub, props("{\"KeyName\": \"deploy\"}"), ctx("Key-0a1b2c3d")); + + assertEquals("deploy", stub.getPhysicalId()); + assertEquals("key-1", stub.getAttributes().get("KeyPairId")); + assertFalse(provisioner.hasReplacementUpdate(stub), "a stub created nothing, so nothing is owed a delete"); + } + + @Test + void rollingBackAStubMigrationRestoresItsMissingInputs() throws Exception { + StackResource stub = resource(); + stub.setPhysicalId("Key-0a1b2c3d"); + stub.getAttributes().put("Arn", CfnResourceDispatcher.STUB_ARN_PREFIX + "Key"); + when(ec2.createKeyPair(REGION, "deploy", null, null)).thenReturn(created("deploy", "key-1")); + provisioner.provision(stub, props("{\"KeyName\": \"deploy\"}"), ctx("Key-0a1b2c3d")); + when(ec2.describeKeyPairs(REGION, List.of("deploy"), List.of())) + .thenReturn(List.of(created("deploy", "key-1"))); + + assertTrue(provisioner.rollbackUpdate(stub)); + + assertEquals("Key-0a1b2c3d", stub.getPhysicalId()); + assertTrue(CfnResourceDispatcher.isStub(stub.getPhysicalId(), stub.getAttributes())); + assertFalse(stub.getAttributes().containsKey("__FlociKeyPairInputs")); + verify(ssm).deleteParameter("/ec2/keypair/key-1", REGION); + verify(ec2).deleteKeyPair(REGION, null, "key-1"); + } + + /** A resource whose key {@code deploy}, {@code key-1}, CreateKeyPair made from {@code json}. */ + private StackResource provisioned(String json) throws Exception { + when(ec2.createKeyPair(eq(REGION), eq("deploy"), any(), any())).thenReturn(created("deploy", "key-1")); + StackResource r = resource(); + provisioner.provision(r, props(json), ctx(null)); + return r; + } + + /** A stack whose key {@code first} was renamed to {@code next} by an update that has not ended. */ + private StackResource renamed() throws Exception { + when(ec2.createKeyPair(REGION, "first", null, null)).thenReturn(created("first", "key-1")); + when(ec2.createKeyPair(REGION, "next", null, null)).thenReturn(created("next", "key-2")); + StackResource r = resource(); + provisioner.provision(r, props("{\"KeyName\": \"first\"}"), ctx(null)); + provisioner.provision(r, props("{\"KeyName\": \"next\"}"), ctx("first")); + return r; + } + + private static KeyPair created(String name, String id) { + KeyPair key = imported(name, id); + key.setKeyMaterial("private-" + id); + return key; + } + + private static KeyPair imported(String name, String id) { + KeyPair key = new KeyPair(); + key.setKeyName(name); + key.setKeyPairId(id); + key.setKeyFingerprint("fingerprint-" + id); + return key; + } + + private ProvisionContext ctx(String priorPhysicalId) { + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null ? null : node.asText(); + }); + when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + when(engine.omitNoValue(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return "AWS::NoValue".equals(node.path("Ref").asText()) ? MissingNode.getInstance() : node; + }); + return new ProvisionContext(engine, REGION, "000000000000", "stack", priorPhysicalId); + } + + private JsonNode props(String json) throws Exception { + return mapper.readTree(json); + } + + private static SsmService realSsm(InMemoryStorage parameters, + InMemoryStorage> history) { + InMemoryStorageFactory factory = new InMemoryStorageFactory(ACCOUNT_ID) + .withStore("ssm-parameters.json", parameters) + .withStore("ssm-history.json", history); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().ssm().maxParameterHistory()).thenReturn(5); + return new SsmService(factory, config, new RegionResolver(REGION, ACCOUNT_ID), + null, null, mock(SsmEventPublisher.class)); + } + + private static StackResource resource() { + StackResource r = new StackResource(); + r.setLogicalId("Key"); + r.setResourceType("AWS::EC2::KeyPair"); + return r; + } +} diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 1f2af7b3eb..5e09d52f14 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -77,6 +77,7 @@ AWS::EC2::EIP Ec2NetworkCfnProvisioner AWS::EC2::FlowLog Ec2FlowLogCfnProvisioner AWS::EC2::Instance Ec2InstanceCfnProvisioner AWS::EC2::InternetGateway Ec2NetworkCfnProvisioner +AWS::EC2::KeyPair Ec2KeyPairCfnProvisioner AWS::EC2::LaunchTemplate Ec2LaunchTemplateCfnProvisioner AWS::EC2::NatGateway Ec2NetworkCfnProvisioner AWS::EC2::NetworkAcl Ec2NetworkAclCfnProvisioner diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index d103549018..f2c8cdb16d 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -189,6 +189,7 @@ notes: AWS::Lambda::WebFunctionRevision: every property is createOnly, so a change mints a new revision AWS::EC2::VPC: 'deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS' AWS::EC2::SecurityGroup: inline `SecurityGroupIngress`/`SecurityGroupEgress` supported + AWS::EC2::KeyPair: 'a created key''s private key is stored in the `SecureString` parameter `/ec2/keypair/`, as on AWS, and deleted with the key' AWS::EC2::NatGateway: 'zonal, primary address only; `AvailabilityMode` regional and the `Secondary*` address properties fail' AWS::EC2::PrefixList: 'updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails' AWS::ApplicationAutoScaling::ScalableTarget: '`ScheduledActions` are accepted and not run; Floci has no scheduled scaling'