fix(ec2): reject duplicate key pair names in ImportKeyPair (#1848)

ImportKeyPair accepted any KeyName even when a key pair with the same
name already existed in the region, so DescribeKeyPairs could list
multiple entries with the same name (e.g. after repeated terraform
apply runs). Real AWS rejects this with InvalidKeyPair.Duplicate.

Apply the same duplicate-name check that CreateKeyPair already
performs, scoped to the region.

Fixes #1845
This commit is contained in:
Ankit1324 authored and GitHub committed 2026-07-14 22:27:15 -04:00
1 parent 483cc5b180
commit f9360cbf86
3 files changed
+52

No files matched your search

@@ -895,6 +895,21 @@ class Ec2IntegrationTest {
.body("ImportKeyPairResponse.keyPairId", startsWith("key-"));
}
@Test
@Order(41)
void importKeyPairRejectsDuplicateKeyName() {
given()
.formParam("Action", "ImportKeyPair")
.formParam("KeyName", "imported-key")
.formParam("PublicKeyMaterial", "c3NoLXJzYSBBQUFBQjNOemFDMXljMkVBQUFBREFRQUJBQUFCQVFD")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidKeyPair.Duplicate"));
}
@Test
@Order(42)
void createLaunchTemplateRejectsMalformedUserData() {
@@ -265,6 +265,38 @@ class Ec2ServiceTest {
assertEquals("InvalidAMIName.Duplicate", error.getErrorCode());
}
@Test
void importKeyPairRejectsDuplicateKeyName() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory());
service.importKeyPair("us-east-1", "duplicate-key", "c3NoLXJzYSBBQUFB");
AwsException error = assertThrows(AwsException.class,
() -> service.importKeyPair("us-east-1", "duplicate-key", "c3NoLXJzYSBBQUFB"));
assertEquals("InvalidKeyPair.Duplicate", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
// same name in another region is allowed
service.importKeyPair("us-west-2", "duplicate-key", "c3NoLXJzYSBBQUFB");
}
@Test
void importKeyPairRejectsNameAlreadyUsedByCreateKeyPair() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory());
service.createKeyPair("us-east-1", "shared-key-name");
AwsException error = assertThrows(AwsException.class,
() -> service.importKeyPair("us-east-1", "shared-key-name", "c3NoLXJzYSBBQUFB"));
assertEquals("InvalidKeyPair.Duplicate", error.getErrorCode());
}
@Test
void registerImageReusingSnapshotDoesNotOverwriteSnapshotMetadata() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),