mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(ec2): reject key pair requests without KeyName (#3727)
* fix(ec2): reject key pair requests without KeyName CreateKeyPair accepted a request with no KeyName and stored a nameless key pair; the duplicate check then dereferenced that name on every later CreateKeyPair, and the Query catch-all reported it as "Unexpected error: null". CreateKeyPair and ImportKeyPair now answer MissingParameter, ImportKeyPair answers InvalidKeyPair.Format instead of an InternalFailure for material that is not base64, DeleteKeyPair requires a name or an id and returns the deleted keyPairId, and the name comparisons tolerate a nameless record already sitting in a persistent store. The EC2 docs still described the placeholder key material that #3307 replaced. Closes #3356 * fix(ec2): return InvalidKey.Format for malformed key material on ImportKeyPair The EC2 API error reference lists InvalidKey.Format as the key pair not being in a valid OpenSSH public key format, which is the message this branch sends. InvalidKeyPair.Format is a separate documented code for a different failure.
This commit is contained in:
1 parent
8d755c20d6
commit
996a680cdc
6 files changed
+214
-33
No files matched your search
@@ -488,6 +488,19 @@ class Ec2Tests {
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(18)
|
||||
@DisplayName("CreateKeyPair - missing KeyName returns MissingParameter")
|
||||
void createKeyPairWithoutNameIsRejected() {
|
||||
assertThatThrownBy(() -> ec2.createKeyPair(CreateKeyPairRequest.builder().build()))
|
||||
.isInstanceOf(Ec2Exception.class)
|
||||
.satisfies(e -> {
|
||||
Ec2Exception ec2Ex = (Ec2Exception) e;
|
||||
assertThat(ec2Ex.awsErrorDetails().errorCode()).isEqualTo("MissingParameter");
|
||||
assertThat(ec2Ex.statusCode()).isEqualTo(400);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(19)
|
||||
@DisplayName("CreateInternetGateway - create IGW")
|
||||
@@ -812,7 +825,9 @@ class Ec2Tests {
|
||||
@Order(46)
|
||||
@DisplayName("DeleteKeyPair - delete key pair")
|
||||
void deleteKeyPair() {
|
||||
ec2.deleteKeyPair(DeleteKeyPairRequest.builder().keyName(keyName).build());
|
||||
DeleteKeyPairResponse resp = ec2.deleteKeyPair(DeleteKeyPairRequest.builder().keyName(keyName).build());
|
||||
assertThat(resp.returnValue()).isTrue();
|
||||
assertThat(resp.keyPairId()).isNotNull().startsWith("key-");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -72,9 +72,9 @@ The Java metadata-driven builder lives at `io.github.hectorvent.floci.tools.ami.
|
||||
|
||||
## SSH Key Injection
|
||||
|
||||
If `KeyName` is specified at launch, Floci looks up the stored key pair's public key material (set via `ImportKeyPair`) and copies it into `/root/.ssh/authorized_keys` inside the container at boot. It then attempts to start `sshd` if present. The SSH port (container port 22) is mapped to a host port from the configured range (default 2200–2299).
|
||||
If `KeyName` is specified at launch, Floci looks up the stored key pair's public key (generated by `CreateKeyPair` or supplied to `ImportKeyPair`) and copies it into `/root/.ssh/authorized_keys` inside the container at boot. It then attempts to start `sshd` if present. The SSH port (container port 22) is mapped to a host port from the configured range (default 2200–2299).
|
||||
|
||||
Key pairs created with `CreateKeyPair` contain dummy private key material. Import a real key pair with `ImportKeyPair` to enable working SSH access.
|
||||
Key pairs created with `CreateKeyPair` return real RSA private key material, and the matching public key is injected at launch, so either a created or an imported key pair works for SSH.
|
||||
|
||||
## Security Group Port Publishing
|
||||
|
||||
@@ -866,6 +866,5 @@ aws ec2 associate-address \
|
||||
## Notes
|
||||
|
||||
- `DescribeImages` returns AMIs from the EC2 image catalog, including common AMIs and Floci-native AMI IDs.
|
||||
- Key material returned by `CreateKeyPair` is a dummy RSA PEM — not usable for real SSH. Use `ImportKeyPair` for working SSH access.
|
||||
- Security group rules are not enforced as a firewall (Docker bridge networking handles routing), but TCP ingress rules opened to a CIDR source are published on the host via socat sidecars so the instance's app is reachable from `localhost` — see [Security Group Port Publishing](#security-group-port-publishing).
|
||||
- The IMDS server identifies which instance is calling via IMDSv2 tokens (mapped at token issuance time) or by the container's bridge IP for IMDSv1.
|
||||
@@ -3029,8 +3029,18 @@ public class Ec2QueryHandler {
|
||||
|
||||
// ─── Key Pair handlers ────────────────────────────────────────────────────
|
||||
|
||||
private Response handleCreateKeyPair(MultivaluedMap<String, String> p, String region) {
|
||||
// KeyName is required on CreateKeyPair and ImportKeyPair. Accepting its absence used to store
|
||||
// a nameless key pair, and the first nameless record broke every later CreateKeyPair (#3356).
|
||||
private static String requireKeyName(MultivaluedMap<String, String> p) {
|
||||
String keyName = p.getFirst("KeyName");
|
||||
if (keyName == null || keyName.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter KeyName", 400);
|
||||
}
|
||||
return keyName;
|
||||
}
|
||||
|
||||
private Response handleCreateKeyPair(MultivaluedMap<String, String> p, String region) {
|
||||
String keyName = requireKeyName(p);
|
||||
KeyPair kp = service.createKeyPair(region, keyName);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("CreateKeyPairResponse", AwsNamespaces.EC2)
|
||||
@@ -3066,14 +3076,36 @@ public class Ec2QueryHandler {
|
||||
private Response handleDeleteKeyPair(MultivaluedMap<String, String> p, String region) {
|
||||
String keyName = p.getFirst("KeyName");
|
||||
String keyPairId = p.getFirst("KeyPairId");
|
||||
service.deleteKeyPair(region, keyName, keyPairId);
|
||||
return booleanResponse("DeleteKeyPair");
|
||||
boolean noName = keyName == null || keyName.isBlank();
|
||||
boolean noId = keyPairId == null || keyPairId.isBlank();
|
||||
if (noName && noId) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter KeyName", 400);
|
||||
}
|
||||
KeyPair deleted = service.deleteKeyPair(region, keyName, keyPairId);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DeleteKeyPairResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
.elem("return", "true");
|
||||
if (deleted != null) {
|
||||
xml.elem("keyPairId", deleted.getKeyPairId());
|
||||
}
|
||||
xml.end("DeleteKeyPairResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
private Response handleImportKeyPair(MultivaluedMap<String, String> p, String region) {
|
||||
String keyName = p.getFirst("KeyName");
|
||||
String keyName = requireKeyName(p);
|
||||
String encoded = p.getFirst("PublicKeyMaterial");
|
||||
String publicKeyMaterial = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);
|
||||
if (encoded == null || encoded.isBlank()) {
|
||||
throw new AwsException("MissingParameter",
|
||||
"The request must contain the parameter PublicKeyMaterial", 400);
|
||||
}
|
||||
String publicKeyMaterial;
|
||||
try {
|
||||
publicKeyMaterial = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("InvalidKey.Format", "Key is not in valid OpenSSH public key format", 400);
|
||||
}
|
||||
KeyPair kp = service.importKeyPair(region, keyName, publicKeyMaterial);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ImportKeyPairResponse", AwsNamespaces.EC2)
|
||||
|
||||
@@ -4546,11 +4546,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
|
||||
public KeyPair createKeyPair(String region, String keyName) {
|
||||
ensureDefaultResources(region);
|
||||
boolean exists = keyPairs.scan(k -> true).stream()
|
||||
.anyMatch(k -> k.getRegion().equals(region) && k.getKeyName().equals(keyName));
|
||||
if (exists) {
|
||||
throw new AwsException("InvalidKeyPair.Duplicate", "The keypair '" + keyName + "' already exists", 400);
|
||||
}
|
||||
requireKeyName(keyName);
|
||||
rejectDuplicateKeyName(region, keyName);
|
||||
String keyPairId = "key-" + randomHex(17);
|
||||
KeyPair kp = new KeyPair();
|
||||
kp.setKeyPairId(keyPairId);
|
||||
@@ -4594,28 +4591,30 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public void deleteKeyPair(String region, String keyName, String keyPairId) {
|
||||
/**
|
||||
* Deletes by id when one is given, otherwise by name, and returns the deleted key pair so
|
||||
* the response can carry its id. Null when nothing matched: AWS answers a delete of an
|
||||
* unknown key pair with plain success.
|
||||
*/
|
||||
public KeyPair deleteKeyPair(String region, String keyName, String keyPairId) {
|
||||
ensureDefaultResources(region);
|
||||
if (keyPairId != null && !keyPairId.isEmpty()) {
|
||||
keyPairs.delete(key(region, keyPairId));
|
||||
} else {
|
||||
// scan() returns a detached copy, so the key pair has to be resolved to its
|
||||
// store key and deleted through the backend — mutating the scan result does
|
||||
// not touch the store.
|
||||
keyPairs.scan(k -> true).stream()
|
||||
.filter(k -> k.getRegion().equals(region) && k.getKeyName().equals(keyName))
|
||||
.map(KeyPair::getKeyPairId)
|
||||
.forEach(id -> keyPairs.delete(key(region, id)));
|
||||
boolean byId = keyPairId != null && !keyPairId.isEmpty();
|
||||
// scan() returns detached copies, so each match is resolved to its store key and deleted
|
||||
// through the backend; mutating the scan result does not touch the store.
|
||||
List<KeyPair> matches = keyPairs.scan(k -> true).stream()
|
||||
.filter(k -> region.equals(k.getRegion()))
|
||||
.filter(k -> byId ? keyPairId.equals(k.getKeyPairId()) : keyName != null && keyName.equals(k.getKeyName()))
|
||||
.toList();
|
||||
for (KeyPair match : matches) {
|
||||
keyPairs.delete(key(region, match.getKeyPairId()));
|
||||
}
|
||||
return matches.isEmpty() ? null : matches.getFirst();
|
||||
}
|
||||
|
||||
public KeyPair importKeyPair(String region, String keyName, String publicKeyMaterial) {
|
||||
ensureDefaultResources(region);
|
||||
boolean exists = keyPairs.scan(k -> true).stream()
|
||||
.anyMatch(k -> k.getRegion().equals(region) && k.getKeyName().equals(keyName));
|
||||
if (exists) {
|
||||
throw new AwsException("InvalidKeyPair.Duplicate", "The keypair '" + keyName + "' already exists", 400);
|
||||
}
|
||||
requireKeyName(keyName);
|
||||
rejectDuplicateKeyName(region, keyName);
|
||||
String keyPairId = "key-" + randomHex(17);
|
||||
KeyPair kp = new KeyPair();
|
||||
kp.setKeyPairId(keyPairId);
|
||||
@@ -4656,6 +4655,22 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
return containerManager.isContainerRunning(instance.getDockerContainerId());
|
||||
}
|
||||
|
||||
private static void requireKeyName(String keyName) {
|
||||
if (keyName == null || keyName.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter KeyName", 400);
|
||||
}
|
||||
}
|
||||
|
||||
// Compared name-first so a nameless record can never throw here. One such record, stored
|
||||
// before KeyName was validated, used to fail every later CreateKeyPair in the account (#3356).
|
||||
private void rejectDuplicateKeyName(String region, String keyName) {
|
||||
boolean exists = keyPairs.scan(k -> true).stream()
|
||||
.anyMatch(k -> region.equals(k.getRegion()) && keyName.equals(k.getKeyName()));
|
||||
if (exists) {
|
||||
throw new AwsException("InvalidKeyPair.Duplicate", "The keypair '" + keyName + "' already exists", 400);
|
||||
}
|
||||
}
|
||||
|
||||
public KeyPair findKeyPair(String region, String keyName) {
|
||||
if (keyName == null) {
|
||||
return null;
|
||||
|
||||
@@ -1948,6 +1948,55 @@ class Ec2IntegrationTest {
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidKeyPair.Duplicate"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(41)
|
||||
void createKeyPairWithoutKeyNameReturnsMissingParameter() {
|
||||
// #3356: a nameless key pair used to be stored, and its null name then broke every
|
||||
// later CreateKeyPair with an InternalFailure.
|
||||
given()
|
||||
.formParam("Action", "CreateKeyPair")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("MissingParameter"));
|
||||
|
||||
given()
|
||||
.formParam("Action", "ImportKeyPair")
|
||||
.formParam("PublicKeyMaterial", "c3NoLXJzYSBBQUFB")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("MissingParameter"));
|
||||
|
||||
given()
|
||||
.formParam("Action", "DeleteKeyPair")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("MissingParameter"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(41)
|
||||
void importKeyPairWithInvalidBase64ReturnsInvalidKeyFormat() {
|
||||
given()
|
||||
.formParam("Action", "ImportKeyPair")
|
||||
.formParam("KeyName", "bad-material-key")
|
||||
.formParam("PublicKeyMaterial", "not base64!")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidKey.Format"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(42)
|
||||
void createLaunchTemplateRejectsMalformedUserData() {
|
||||
@@ -3798,10 +3847,12 @@ class Ec2IntegrationTest {
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
.statusCode(200)
|
||||
.body("DeleteKeyPairResponse.return", equalTo("true"))
|
||||
.body("DeleteKeyPairResponse.keyPairId", equalTo(keyPairId));
|
||||
|
||||
// DeleteKeyPair always answers 200, so the delete is only proven by a
|
||||
// follow-up describe.
|
||||
// DeleteKeyPair answers 200 for a known and an unknown key pair alike, so the
|
||||
// delete is only proven by a follow-up describe.
|
||||
given()
|
||||
.formParam("Action", "DescribeKeyPairs")
|
||||
.formParam("KeyPairId.1", keyPairId)
|
||||
|
||||
@@ -1126,6 +1126,75 @@ class Ec2ServiceTest {
|
||||
service.importKeyPair("us-east-1", "pinned-ed25519", ed25519Key).getKeyFingerprint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createKeyPairRejectsMissingKeyName() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory());
|
||||
|
||||
for (String missing : new String[] {null, "", " "}) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.createKeyPair("us-east-1", missing));
|
||||
assertEquals("MissingParameter", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
assertTrue(service.describeKeyPairs("us-east-1", List.of(), List.of()).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importKeyPairRejectsMissingKeyName() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory());
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.importKeyPair("us-east-1", null, "c3NoLXJzYSBBQUFB"));
|
||||
assertEquals("MissingParameter", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createKeyPairSurvivesANamelessRecordInTheStore() {
|
||||
// Regression for #3356: a key pair stored without a name (accepted before KeyName was
|
||||
// validated) made the duplicate check throw on every later CreateKeyPair.
|
||||
AccountAwareStorageBackend<KeyPair> keyPairStore = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
KeyPair nameless = new KeyPair();
|
||||
nameless.setKeyPairId("key-nameless");
|
||||
nameless.setRegion("us-east-1");
|
||||
keyPairStore.put("us-east-1:key-nameless", nameless);
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory(Map.of("ec2-key-pairs.json", keyPairStore)));
|
||||
|
||||
KeyPair created = service.createKeyPair("us-east-1", "fresh");
|
||||
KeyPair imported = service.importKeyPair("us-east-1", "fresh-imported",
|
||||
Ec2KeyMaterial.generateRsa().openSshPublicKey());
|
||||
|
||||
assertEquals("fresh", created.getKeyName());
|
||||
assertEquals("fresh-imported", imported.getKeyName());
|
||||
assertNull(service.deleteKeyPair("us-east-1", "no-such-name", null));
|
||||
assertEquals(3, service.describeKeyPairs("us-east-1", List.of(), List.of()).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteKeyPairReturnsTheDeletedRecordOrNull() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory());
|
||||
KeyPair byName = service.createKeyPair("us-east-1", "delete-by-name");
|
||||
KeyPair byId = service.createKeyPair("us-east-1", "delete-by-id");
|
||||
|
||||
assertEquals(byName.getKeyPairId(), service.deleteKeyPair("us-east-1", "delete-by-name", null).getKeyPairId());
|
||||
assertEquals(byId.getKeyPairId(), service.deleteKeyPair("us-east-1", null, byId.getKeyPairId()).getKeyPairId());
|
||||
assertNull(service.deleteKeyPair("us-east-1", "delete-by-name", null));
|
||||
assertNull(service.deleteKeyPair("us-east-1", null, byId.getKeyPairId()));
|
||||
assertTrue(service.describeKeyPairs("us-east-1", List.of(), List.of()).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importKeyPairRejectsDuplicateKeyName() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
|
||||
Reference in new issue
Block a user