mirror of
https://github.com/floci-io/floci.git
synced 2026-11-28 16:11:48 -05:00
feat(cloudformation): provision AWS::EC2::KeyPair with its private key in Parameter Store (#7128)
* feat(cloudformation): provision AWS::EC2::KeyPair with its private key in Parameter Store AWS::EC2::KeyPair had no provisioner, so a stack stubbed it: the stack reached CREATE_COMPLETE without creating a key, Ref returned a made-up id and Fn::GetAtt returned the literal "Key.KeyPairId". A template that creates a key pair for an instance, as the AWS::EC2::KeyPair reference shows, got nothing to log in with. The new provisioner does what that reference describes: - Without PublicKeyMaterial it calls CreateKeyPair with the template's KeyType and KeyFormat, so rsa and ed25519 keys and pem and ppk files all work, and stores the private key in the SecureString parameter /ec2/keypair/<KeyPairId>. With PublicKeyMaterial it imports the key, takes the key's type from the material (KeyType is ignored, as documented) and writes no parameter. - Ref is the key name; Fn::GetAtt KeyPairId and KeyFingerprint are the key's own. - Tags are applied once the key exists and the parameter is written last, so a step that fails leaves only the key to undo. Deleting a created key deletes its parameter first, on stack delete, rollback and replacement cleanup alike; a key or parameter already gone counts as deleted. A key is deleted by its name, as Cloud Control's DeleteResource names it; a key deleted outside the stack still has its parameter deleted with the stack. - Only AWS::NoValue leaves a property out; an empty string a parameter supplies is a value, as the same string written literally is. An empty PublicKeyMaterial fails with the MissingParameter error ImportKeyPair gives for it. - Every property is create-only (the registry schema has no update handler) and KeyName is required. An update that changes another property under the same name is refused with CloudFormation's custom-named replacement error. A rename creates the new key, then deletes the old one with its parameter once the update commits, or deletes the new one if the update rolls back. The create-only list is added to create-only-properties.json, so a change set reports a changed name or type as a replacement, and the generated resource-type table lists KeyPair. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): delete orphaned key pair parameters on cleanup Replacement cleanup and rollback delete a displaced or rolled-back AWS::EC2::KeyPair by name only. When that key had already been deleted outside the stack, its /ec2/keypair/<KeyPairId> SecureString parameter was left behind. Record the id of each created key the resource still owes a delete, keyed by name, so the cleanup, the rollback and a rollback retry also delete that key's parameter. Imported keys have no parameter and are not recorded. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): end a key pair's rollback retry when an update starts A rollback that could not delete a renamed key pair's replacement leaves it owed for ContinueUpdateRollback. Once that skipped the resource, a later update that failed before creating anything rolled back by retrying that old delete instead of undoing itself, and could end in UPDATE_ROLLBACK_FAILED. Call ReplacementCleanup.endRollbackRetry as an update starts, as the other replacing provisioners do. The replacement stays listed, so the next committed update or the stack delete still removes it. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(cloudformation): say the rollback retry test pins a helper contract The test added with the endRollbackRetry call rolls back the same resource whose update failed. The engine does not do that for a key pair today: it restores the previous resource and skips its rollback, so the earlier commit's UPDATE_ROLLBACK_FAILED scenario is not reachable yet. Say that the test pins the ReplacementCleanup contract instead. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): clean up partial KeyPair parameter writes * refactor(cloudformation): share KeyPair create-only tracking --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
1 parent
02b9669066
commit
be315bf160
10 files changed
+1908
-1
No files matched your search
+202
@@ -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/<KeyPairId>, 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/<KeyPairId>, 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<String, String> outputs() {
|
||||
List<Output> 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<Stack> 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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user