feat(iam): model SSH public keys (#5051)

UploadSSHPublicKey, GetSSHPublicKey, ListSSHPublicKeys, UpdateSSHPublicKey
and DeleteSSHPublicKey, stored per user with the documented quota of five.

AWS accepts the body in ssh-rsa form or as PEM, so both are read, and the
body is kept exactly as it arrived: a caller that uploaded PEM gets that PEM
back rather than a re-encoding. GetSSHPublicKey converts, because Encoding is
required and decides the form of the response.

Fingerprint is the MD5 of the OpenSSH blob, confirmed by reproducing the
worked example in the IAM API Reference rather than assumed. It is not the
digest EC2 reports for the same key, which is taken over the DER: both are
sixteen bytes of colon hex, so the wrong one would look right.

The two rejection errors are kept apart the way the model separates them. A
body in neither accepted encoding is UnrecognizedPublicKeyEncoding; one in a
recognised encoding that will not parse, or that carries a key type other
than ssh-rsa, is InvalidPublicKey. An OpenSSH line is recognised by its
key-type token rather than by whether part of it base64-decodes, since a
short word often does.

DuplicateSSHPublicKey is per user, unlike the account-wide rule for signing
certificates, and compares fingerprints so the same key in the other
encoding still counts. A key blocks DeleteUser until removed and follows the
user across an UpdateUser rename, both under a lock taken in the same order
DeleteUser takes it.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-04 10:37:38 -05:00
1 parent ace5cbfc63
commit fe296fda69
16 files changed
+1575 -41

No files matched your search

@@ -8,6 +8,8 @@ import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -131,4 +133,59 @@ class SshPublicKeysTest {
out.put(good).putInt(Integer.MAX_VALUE).putInt(0);
return out.array();
}
/**
* The worked {@code GetSSHPublicKey} example from the IAM API Reference returns this key with
* {@code Encoding=PEM} and reports the fingerprint below. Reproducing it is the only way to
* know, rather than assume, that IAM hashes the OpenSSH blob: the digest over the DER is a
* value of exactly the same shape, so nothing in a response would reveal the mistake.
*/
@Test
void theOpenSshFingerprintReproducesTheDocumentedAwsExample() {
String awsExamplePem = """
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsu+WpO9hhmqGTctHI1BE
SJ/pq4GtAt9JJpIsDnjeB+mLbwnVJLFaaYzzoZuPOVhUc7yHMWjBLmfSEgJKfAH3
n8m8R9D3UFoRC0rtKR2jJwAwFO3Tp9wgnqzvPtLMnG7uBEuD/nHStanrd6bbBv83
kDSy5jiuc4yEWtTAEtyp8C8BxFTxHuCQ/sX4IbjtJ8M1IKZ3hjcJO5u6ooWCxZzQ
hXXlPDniK/RZnO+YOaJR5umaAv23HAB7qx5H3A6WpyUyzXy0eTo9eAmUrET+JDXZ
vqHufiDzO/MOCfb+KV1OJos2AxNtRuIFA1cTq7NF+upTIoV+gK1YJhCvjSuRkIJ/
cwIDAQAB
-----END PUBLIC KEY-----
""";
RSAPublicKey key = SshPublicKeys.fromPem(awsExamplePem);
assertEquals("7a:1d:ea:9e:b0:80:ac:f8:ec:d8:dc:e6:a7:2c:fc:51",
SshPublicKeys.openSshFingerprint(SshPublicKeys.openSshBlob(key)));
// And the DER digest is a different value, which is why the two are separate functions.
assertNotEquals(SshPublicKeys.openSshFingerprint(SshPublicKeys.openSshBlob(key)),
SshPublicKeys.md5ColonHex(key.getEncoded()),
"if these ever agree, this test is no longer protecting anything");
}
@Test
void aKeyRoundTripsBetweenPemAndTheOpenSshForm() {
String pem = SshPublicKeys.toPem(KEY);
assertTrue(SshPublicKeys.looksLikePem(pem));
assertEquals(KEY.getModulus(), SshPublicKeys.fromPem(pem).getModulus());
RSAPublicKey viaOpenSsh = SshPublicKeys.rsaKeyOf(
SshPublicKeys.decodeBlob(SshPublicKeys.toOpenSsh(KEY)));
assertEquals(KEY.getModulus(), SshPublicKeys.fromPem(SshPublicKeys.toPem(viaOpenSsh)).getModulus());
}
@Test
void whatIsNotPemIsRefused() {
assertFalse(SshPublicKeys.looksLikePem(null));
assertFalse(SshPublicKeys.looksLikePem("ssh-rsa AAAA"));
assertThrows(SshPublicKeyException.class, () -> SshPublicKeys.fromPem("not pem"));
assertThrows(SshPublicKeyException.class, () -> SshPublicKeys.fromPem(
"-----BEGIN PUBLIC KEY-----\nnot base64\n-----END PUBLIC KEY-----\n"));
}
@Test
void theTypeIsReadFromTheBlob() {
assertEquals("ssh-rsa", SshPublicKeys.keyType(
SshPublicKeys.decodeBlob(SshPublicKeys.toOpenSsh(KEY))));
}
}
@@ -232,6 +232,7 @@ class IamServicePersistenceTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), devices, new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, null);
}
@@ -2371,6 +2371,7 @@ class IamServiceTest {
new InMemoryStorage<>(), credentialReports, new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, null);
AwsException ex = assertThrows(AwsException.class, withExpiredReport::getCredentialReport);
@@ -2390,6 +2391,7 @@ class IamServiceTest {
new InMemoryStorage<>(), credentialReports, new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, null);
IamService.CredentialReportGeneration generation = withExpiredReport.generateCredentialReport();
@@ -80,6 +80,7 @@ class ServerCertificateStateTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
certificates,
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", defaultAccount), false, null);
}
@@ -71,6 +71,7 @@ class SigningCertificateStateTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(),
certificates,
new InMemoryStorage<>(),
new RegionResolver("us-east-1", defaultAccount), false, null);
}
@@ -86,6 +87,7 @@ class SigningCertificateStateTest {
new InMemoryStorage<>(), reports, new InMemoryStorage<>(),
new InMemoryStorage<>(),
certificates,
new InMemoryStorage<>(),
new RegionResolver("us-east-1", defaultAccount), false, null);
}
@@ -0,0 +1,494 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.SshPublicKeys;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPublicKey;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The SSH public key lifecycle over the wire. Keys are generated rather than hardcoded, so the
* accept paths read real material and the reject paths reject things that genuinely are not keys.
*
* <p>Each test makes its own user, which also gives it that user's whole quota of five.
*/
@QuarkusTest
class SshPublicKeyIntegrationTest {
/** A real 2048-bit RSA blob with its type field rewritten to ssh-ed25519. */
private static final String RSA_BLOB_LABELLED_ED25519 =
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAAwEAAQAAAQEAsNx6pYV5SGmCmxitRthv"
+ "DL+KOosyVaBCBnOMd3BGZQUfVxtpfdObaZ9KnRIspbCY+Ny/dSCxzoCG4YdXJhUUaM2y"
+ "iCDrNIQnBm3cGPZXtOLztrn8OzlwyXDu082rSav14HgK0N/VmyUzvBQgMucKLn1cBhoa"
+ "l/BueVTc0Eu4xOPzfwrkxY26OptLxUO4AkQ8GJsLJa65O9QvwnwSQnqjS3gbPuZqKo6W"
+ "SwhJ4SyR3/4R3Uk1e8fg3blqwTj3o8vNj1H6jwWOH4tkE/yXvzbHjKhG9JQs938QWSvb"
+ "wud3R01B3JO5KFiFFPT+fihU3qWbCaXaQR0ESPhHBILaBkYGFw==";
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
private static RequestSpecification iam(String action) {
return given().header("Authorization", IAM_AUTH).formParam("Action", action);
}
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
private static RSAPublicKey generated() {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
return (RSAPublicKey) generator.generateKeyPair().getPublic();
} catch (Exception e) {
throw new IllegalStateException("could not generate a key", e);
}
}
private static String user() {
String name = "ssh-user-" + suffix();
iam("CreateUser").formParam("UserName", name).when().post("/").then().statusCode(200);
return name;
}
private static String upload(String userName, String body) {
return iam("UploadSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyBody", body)
.when().post("/").then().statusCode(200)
.extract().path("UploadSSHPublicKeyResponse.UploadSSHPublicKeyResult"
+ ".SSHPublicKey.SSHPublicKeyId");
}
@Test
void uploadReturnsTheKeyWithAnApkaIdAndTheOpenSshFingerprint() {
String userName = user();
RSAPublicKey key = generated();
String expectedFingerprint =
SshPublicKeys.openSshFingerprint(SshPublicKeys.openSshBlob(key));
String id = iam("UploadSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyBody", SshPublicKeys.toOpenSsh(key))
.when().post("/").then().statusCode(200)
.body("UploadSSHPublicKeyResponse.UploadSSHPublicKeyResult.SSHPublicKey.UserName",
equalTo(userName))
.body("UploadSSHPublicKeyResponse.UploadSSHPublicKeyResult.SSHPublicKey.Status",
equalTo("Active"))
// The fingerprint AWS reports is the MD5 of the OpenSSH blob, not of the DER.
.body("UploadSSHPublicKeyResponse.UploadSSHPublicKeyResult.SSHPublicKey.Fingerprint",
equalTo(expectedFingerprint))
.extract().path("UploadSSHPublicKeyResponse.UploadSSHPublicKeyResult"
+ ".SSHPublicKey.SSHPublicKeyId");
assertNotNull(id);
assertTrue(id.startsWith("APKA"), "AWS's own examples use the APKA prefix: " + id);
// publicKeyIdType is 20 to 128 characters of word characters.
assertTrue(id.length() >= 20 && id.length() <= 128, "id length: " + id.length());
assertTrue(id.matches("\\w+"), id);
}
/** "The public key must be encoded in ssh-rsa format or PEM format." Both are accepted. */
@Test
void bothAcceptedEncodingsCanBeUploaded() {
String userName = user();
upload(userName, SshPublicKeys.toOpenSsh(generated()));
upload(userName, SshPublicKeys.toPem(generated()));
iam("ListSSHPublicKeys").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.body("ListSSHPublicKeysResponse.ListSSHPublicKeysResult.SSHPublicKeys.member.size()",
equalTo(2));
}
/**
* Encoding is required and decides the form of the body in the response, so a key uploaded as
* ssh-rsa comes back as PEM when PEM is asked for. The conversion is the point of the
* parameter.
*/
@Test
void theRequestedEncodingIsWhatComesBack() {
String userName = user();
RSAPublicKey key = generated();
String id = upload(userName, SshPublicKeys.toOpenSsh(key));
String asPem = iam("GetSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyId", id)
.formParam("Encoding", "PEM")
.when().post("/").then().statusCode(200)
.extract().path("GetSSHPublicKeyResponse.GetSSHPublicKeyResult.SSHPublicKey"
+ ".SSHPublicKeyBody");
assertTrue(asPem.contains("BEGIN PUBLIC KEY"), asPem);
assertEquals(key.getModulus(), SshPublicKeys.fromPem(asPem).getModulus(),
"the converted key must be the same key");
String asSsh = iam("GetSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyId", id)
.formParam("Encoding", "SSH")
.when().post("/").then().statusCode(200)
.extract().path("GetSSHPublicKeyResponse.GetSSHPublicKeyResult.SSHPublicKey"
+ ".SSHPublicKeyBody");
assertTrue(asSsh.startsWith("ssh-rsa "), asSsh);
}
/** And the same in the other direction: a PEM upload read back as ssh-rsa. */
@Test
void aPemUploadConvertsToTheOpenSshForm() {
String userName = user();
RSAPublicKey key = generated();
String id = upload(userName, SshPublicKeys.toPem(key));
String asSsh = iam("GetSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyId", id)
.formParam("Encoding", "SSH")
.when().post("/").then().statusCode(200)
.extract().path("GetSSHPublicKeyResponse.GetSSHPublicKeyResult.SSHPublicKey"
+ ".SSHPublicKeyBody");
assertEquals(key.getModulus(),
SshPublicKeys.rsaKeyOf(SshPublicKeys.decodeBlob(asSsh)).getModulus());
}
@Test
void anUnknownEncodingIsRejected() {
String userName = user();
String id = upload(userName, SshPublicKeys.toOpenSsh(generated()));
iam("GetSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyId", id)
.formParam("Encoding", "DER")
.when().post("/").then().statusCode(400)
.body(containsString("UnrecognizedPublicKeyEncoding"));
}
/**
* The list carries metadata only: AWS documents SSHPublicKeyMetadata as describing a key
* "without the key's body or fingerprint".
*/
@Test
void theListOmitsTheBodyAndTheFingerprint() {
String userName = user();
String id = upload(userName, SshPublicKeys.toOpenSsh(generated()));
String body = iam("ListSSHPublicKeys").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.body(containsString(id))
.body("ListSSHPublicKeysResponse.ListSSHPublicKeysResult.SSHPublicKeys.member.Status",
equalTo("Active"))
.body("ListSSHPublicKeysResponse.ListSSHPublicKeysResult.SSHPublicKeys.member"
+ ".UploadDate", containsString("T"))
.extract().body().asString();
assertTrue(!body.contains("SSHPublicKeyBody"), "the list must not carry the body");
assertTrue(!body.contains("Fingerprint"), "the list must not carry the fingerprint");
}
@Test
void theStatusCanBeSetToEveryDocumentedValue() {
String userName = user();
String id = upload(userName, SshPublicKeys.toOpenSsh(generated()));
for (String status : List.of("Inactive", "Expired", "Active")) {
iam("UpdateSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyId", id)
.formParam("Status", status)
.when().post("/").then().statusCode(200);
iam("ListSSHPublicKeys").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.body("ListSSHPublicKeysResponse.ListSSHPublicKeysResult.SSHPublicKeys"
+ ".member.Status", equalTo(status));
}
}
@Test
void deleteRemovesIt() {
String userName = user();
String id = upload(userName, SshPublicKeys.toOpenSsh(generated()));
iam("DeleteSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyId", id)
.when().post("/").then().statusCode(200);
iam("ListSSHPublicKeys").formParam("UserName", userName)
.when().post("/").then().statusCode(200).body(not(containsString(id)));
}
/** Neither accepted encoding, which the model separates from material that will not parse. */
@Test
void somethingThatIsNeitherEncodingIsUnrecognised() {
String userName = user();
iam("UploadSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyBody", "this is not a key at all")
.when().post("/").then().statusCode(400)
.body(containsString("UnrecognizedPublicKeyEncoding"));
}
/** A recognised encoding carrying material that will not parse is the other error. */
@Test
void aRecognisedEncodingWithBadMaterialIsInvalid() {
String userName = user();
iam("UploadSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyBody",
"-----BEGIN PUBLIC KEY-----\nbm90IGEga2V5\n-----END PUBLIC KEY-----\n")
.when().post("/").then().statusCode(400)
.body(containsString("InvalidPublicKey"));
}
/** "The minimum bit-length of the public key is 2048 bits." */
@Test
void aKeyShorterThanTheMinimumBitLengthIsRejected() throws Exception {
String userName = user();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024);
RSAPublicKey small = (RSAPublicKey) generator.generateKeyPair().getPublic();
iam("UploadSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyBody", SshPublicKeys.toOpenSsh(small))
.when().post("/").then().statusCode(400)
.body(containsString("InvalidPublicKey"));
}
/** "SSH Public keys per user: 5", from the IAM service quotas. */
@Test
void aSixthKeyExceedsThePerUserQuota() {
String userName = user();
for (int i = 0; i < 5; i++) {
upload(userName, SshPublicKeys.toOpenSsh(generated()));
}
iam("UploadSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyBody", SshPublicKeys.toOpenSsh(generated()))
.when().post("/").then().statusCode(409)
.body(containsString("LimitExceeded"))
.body(containsString("SSHPublicKeysPerUser"));
}
/**
* DuplicateSSHPublicKey is per user: "already associated with the specified IAM user". The
* comparison is on the key rather than the text, so the same key in the other encoding counts.
*
* <p>The status is 400, which the model gives this error, and not the 409 that
* DuplicateCertificate carries: the two read alike and differ.
*/
@Test
void theSameKeyCannotBeUploadedTwiceForOneUser() {
String userName = user();
RSAPublicKey key = generated();
upload(userName, SshPublicKeys.toOpenSsh(key));
iam("UploadSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyBody", SshPublicKeys.toPem(key))
.when().post("/").then().statusCode(400)
.body(containsString("DuplicateSSHPublicKey"));
}
/** And another user may hold the same key, because the duplicate rule is per user. */
@Test
void anotherUserMayHoldTheSameKey() {
String first = user();
String second = user();
RSAPublicKey key = generated();
upload(first, SshPublicKeys.toOpenSsh(key));
upload(second, SshPublicKeys.toOpenSsh(key));
}
@Test
void aKeyOfAnotherUserCannotBeReadOrDeleted() {
String owner = user();
String other = user();
String id = upload(owner, SshPublicKeys.toOpenSsh(generated()));
iam("GetSSHPublicKey")
.formParam("UserName", other)
.formParam("SSHPublicKeyId", id)
.formParam("Encoding", "SSH")
.when().post("/").then().statusCode(404).body(containsString("NoSuchEntity"));
iam("DeleteSSHPublicKey")
.formParam("UserName", other)
.formParam("SSHPublicKeyId", id)
.when().post("/").then().statusCode(404).body(containsString("NoSuchEntity"));
}
/**
* UserName is required on every operation but the list, where the model marks it optional and
* it resolves from the signing access key.
*/
@Test
void userNameIsRequiredExceptOnTheList() {
iam("UploadSSHPublicKey")
.formParam("SSHPublicKeyBody", SshPublicKeys.toOpenSsh(generated()))
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError")).body(containsString("userName"));
iam("GetSSHPublicKey")
.formParam("SSHPublicKeyId", "APKAEXAMPLEEXAMPLEEX")
.formParam("Encoding", "SSH")
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"));
iam("DeleteSSHPublicKey")
.formParam("SSHPublicKeyId", "APKAEXAMPLEEXAMPLEEX")
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"));
}
@Test
void anAbsentKeyIdIsNoSuchEntity() {
String userName = user();
iam("DeleteSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyId", "APKAABSENTABSENTABSE")
.when().post("/").then().statusCode(404).body(containsString("NoSuchEntity"));
}
/**
* Without an Authorization header the Query controller infers the service from the action name
* alone, so these have to be in its IAM set or they fall through to SQS. The IAM namespace on
* the error is what proves the routing.
*/
@Test
void sshKeyActionsRouteViaTheActionFallbackWhenAuthHeaderAbsent() {
for (String action : List.of("UploadSSHPublicKey", "GetSSHPublicKey", "ListSSHPublicKeys",
"UpdateSSHPublicKey", "DeleteSSHPublicKey")) {
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", action)
.formParam("Version", "2010-05-08")
.when().post("/").then()
.body(containsString("iam.amazonaws.com/doc/2010-05-08"));
}
}
/**
* A real RSA blob relabelled as ssh-ed25519, which is the discriminating case: the type field
* is the only thing changed, so the exponent and modulus still parse. Skipping the declared
* type would read this as an RSA key and store it under a type that was never supported.
*
* <p>The earlier version of this test used material that was simply malformed, so it passed
* without the type ever being checked.
*/
@Test
void anRsaBlobRelabelledAsAnotherTypeIsInvalid() {
String userName = user();
iam("UploadSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyBody", RSA_BLOB_LABELLED_ED25519)
.when().post("/").then().statusCode(400)
.body(containsString("InvalidPublicKey"));
}
/**
* A PEM body whose closing marker is missing. The base64 that survives is still valid base64,
* so treating the marker as optional decodes it and stores a truncated body.
*/
@Test
void aPemBodyWithNoClosingMarkerIsRejected() {
String userName = user();
String complete = SshPublicKeys.toPem(generated());
String truncated = complete.replace("-----END PUBLIC KEY-----\n", "");
iam("UploadSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyBody", truncated)
.when().post("/").then().statusCode(400)
.body(containsString("UnrecognizedPublicKeyEncoding"));
}
/**
* Reading back in the encoding a key was uploaded in must return what was uploaded. A trailing
* comment on an OpenSSH line is the visible case: re-encoding drops it.
*/
@Test
void readingBackInTheSameEncodingReturnsTheUploadedBody() {
String userName = user();
String withComment = SshPublicKeys.toOpenSsh(generated()) + " someone@example.com";
String id = upload(userName, withComment);
String readBack = iam("GetSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyId", id)
.formParam("Encoding", "SSH")
.when().post("/").then().statusCode(200)
.extract().path("GetSSHPublicKeyResponse.GetSSHPublicKeyResult.SSHPublicKey"
+ ".SSHPublicKeyBody");
assertEquals(withComment, readBack,
"the uploaded body must come back unchanged, comment included");
}
/** And the same for PEM, whose line wrapping a re-encode would normalise. */
@Test
void aPemUploadReadBackAsPemIsUnchanged() {
String userName = user();
String pem = SshPublicKeys.toPem(generated());
String id = upload(userName, pem);
String readBack = iam("GetSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyId", id)
.formParam("Encoding", "PEM")
.when().post("/").then().statusCode(200)
.extract().path("GetSSHPublicKeyResponse.GetSSHPublicKeyResult.SSHPublicKey"
+ ".SSHPublicKeyBody");
assertEquals(pem, readBack, "the uploaded PEM must come back byte-identical");
}
/** A type token with nothing after it is recognised as the encoding and fails as the key. */
@Test
void anOpenSshLineWithNoBlobIsInvalid() {
String userName = user();
iam("UploadSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyBody", "ssh-rsa")
.when().post("/").then().statusCode(400)
.body(containsString("InvalidPublicKey"));
}
/**
* The other direction of the same mismatch: the blob is a genuine, untouched {@code ssh-rsa}
* blob and only the line's label is wrong. Checking the blob's own type field does not catch
* this, and because the uploaded body is preserved the wrong label would be handed back to
* every later reader rather than quietly re-encoded away.
*/
@Test
void anSshRsaBlobUnderTheWrongLabelIsInvalid() {
String userName = user();
String genuine = SshPublicKeys.toOpenSsh(generated());
String mislabelled = "ssh-ed25519 " + genuine.split(" ")[1];
iam("UploadSSHPublicKey")
.formParam("UserName", userName)
.formParam("SSHPublicKeyBody", mislabelled)
.when().post("/").then().statusCode(400)
.body(containsString("InvalidPublicKey"));
}
}
@@ -0,0 +1,325 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.SshPublicKeys;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.iam.model.SshPublicKey;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The properties of the SSH public key store the wire tests cannot reach: that it survives a
* restart, that one account cannot see another's, that the quota holds when uploads race, and that
* a user's keys block a delete and follow a rename.
*/
class SshPublicKeyStateTest {
private static final String ACCOUNT_A = "000000000000";
private static final String ACCOUNT_B = "111111111111";
private static RSAPublicKey generated() {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
return (RSAPublicKey) generator.generateKeyPair().getPublic();
} catch (Exception e) {
throw new IllegalStateException("could not generate a key", e);
}
}
private static String openSshKey() {
return SshPublicKeys.toOpenSsh(generated());
}
@SuppressWarnings("unchecked")
private static Instance<RequestContext> requestContextFor(AtomicReference<String> accountId) {
RequestContext rc = mock(RequestContext.class);
when(rc.getAccountId()).thenAnswer(invocation -> accountId.get());
Instance<RequestContext> inst = mock(Instance.class);
when(inst.get()).thenReturn(rc);
return inst;
}
private static IamService newService(StorageBackend<String, SshPublicKey> keys,
String defaultAccount) {
return new IamService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(),
keys,
new RegionResolver("us-east-1", defaultAccount), false, null);
}
/**
* The body is stored as uploaded, so a restart has to return the same bytes rather than a
* re-encoding of the same key: a caller that uploaded PEM must still get its PEM back.
*/
@Test
void aKeySurvivesARestart(@TempDir Path dir) {
Path file = dir.resolve("ssh-public-keys.json");
String pemBody = SshPublicKeys.toPem(generated());
PersistentStorage<String, SshPublicKey> first =
new PersistentStorage<>(file, new TypeReference<>() {});
first.load();
IamService before = newService(first, ACCOUNT_A);
before.createUser("restart-user", "/");
SshPublicKey uploaded = before.uploadSshPublicKey("restart-user", pemBody);
before.updateSshPublicKey("restart-user", uploaded.getSshPublicKeyId(), "Inactive");
PersistentStorage<String, SshPublicKey> second =
new PersistentStorage<>(file, new TypeReference<>() {});
second.load();
IamService after = newService(second, ACCOUNT_A);
after.createUser("restart-user", "/");
List<SshPublicKey> reloaded = after.listSshPublicKeys("restart-user");
assertEquals(1, reloaded.size());
assertEquals(uploaded.getSshPublicKeyId(), reloaded.getFirst().getSshPublicKeyId());
assertEquals(pemBody, reloaded.getFirst().getSshPublicKeyBody(),
"the body must come back as it was uploaded, not re-encoded");
assertEquals(uploaded.getFingerprint(), reloaded.getFirst().getFingerprint());
// A default of Active would hide the loss of this field, so it is the one to check.
assertEquals("Inactive", reloaded.getFirst().getStatus());
}
@Test
void oneAccountCannotSeeAnothersKeys() {
AtomicReference<String> account = new AtomicReference<>(ACCOUNT_A);
AccountAwareStorageBackend<SshPublicKey> store = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), requestContextFor(account), ACCOUNT_A);
IamService service = newService(store, ACCOUNT_A);
service.createUser("shared-name", "/");
service.uploadSshPublicKey("shared-name", openSshKey());
assertEquals(1, service.listSshPublicKeys("shared-name").size());
// The users store here is not account-aware, so the user is already present under the same
// name. Only the key store is scoped, so a leak is the only thing that can fail this.
account.set(ACCOUNT_B);
assertEquals(0, service.listSshPublicKeys("shared-name").size(),
"account B must not see account A's key");
// And B filling its own quota must not be refused for keys A already holds.
for (int i = 0; i < 5; i++) {
service.uploadSshPublicKey("shared-name", openSshKey());
}
assertEquals(5, service.listSshPublicKeys("shared-name").size());
account.set(ACCOUNT_A);
assertEquals(1, service.listSshPublicKeys("shared-name").size(),
"account A's view must be unchanged by account B's uploads");
}
/**
* The quota is counted inside the same lock as the write, so concurrent uploads cannot both
* see room for the last slot. Asserted by counting what actually succeeded, because an
* invariant phrased as "the store holds at most five" passes with the lock removed too.
*/
@Test
void concurrentUploadsCannotExceedTheQuota() throws Exception {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("race-user", "/");
int attempts = 12;
List<String> bodies = new ArrayList<>();
for (int i = 0; i < attempts; i++) {
bodies.add(openSshKey());
}
ExecutorService pool = Executors.newFixedThreadPool(attempts);
CountDownLatch start = new CountDownLatch(1);
AtomicInteger accepted = new AtomicInteger();
try {
for (int i = 0; i < attempts; i++) {
String body = bodies.get(i);
pool.submit(() -> {
start.await();
try {
service.uploadSshPublicKey("race-user", body);
accepted.incrementAndGet();
} catch (AwsException expected) {
// LimitExceeded for the losers, which is the point of the race.
}
return null;
});
}
start.countDown();
pool.shutdown();
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "uploads did not finish");
} finally {
pool.shutdownNow();
}
assertEquals(5, accepted.get(), "exactly the quota should have been accepted");
assertEquals(5, service.listSshPublicKeys("race-user").size());
}
/** AWS lists the SSH public key among the items to remove before deleting a user. */
@Test
void aUserWithAKeyCannotBeDeleted() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("blocked-user", "/");
String id = service.uploadSshPublicKey("blocked-user", openSshKey()).getSshPublicKeyId();
AwsException refused = assertThrows(AwsException.class,
() -> service.deleteUser("blocked-user"));
assertEquals("DeleteConflict", refused.getErrorCode());
assertTrue(refused.getMessage().contains("SSH public key"),
"the message should name what is in the way: " + refused.getMessage());
service.deleteSshPublicKey("blocked-user", id);
service.deleteUser("blocked-user");
}
/**
* A rename must carry the keys with it. Left behind, a key is stranded on a user name that no
* longer exists: invisible to its owner, because listing goes through the user, and so
* undeletable.
*/
@Test
void aRenameCarriesTheKeys() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("before-rename", "/");
String id = service.uploadSshPublicKey("before-rename", openSshKey()).getSshPublicKeyId();
service.updateUser("before-rename", "after-rename", null);
List<SshPublicKey> moved = service.listSshPublicKeys("after-rename");
assertEquals(1, moved.size(), "the key should have followed the rename");
assertEquals(id, moved.getFirst().getSshPublicKeyId());
assertEquals("after-rename", moved.getFirst().getUserName());
service.deleteSshPublicKey("after-rename", id);
service.deleteUser("after-rename");
}
/**
* An upload must never land on a user DeleteUser has just removed. Both hold the SSH lock, so
* only two orders exist: the delete is refused because a key is there, or the upload fails
* because the user is gone. A key owned by a user that does not exist is the state neither
* order may produce, and nothing in the API would report it, so this asserts against the store.
*/
@Test
void anUploadNeverStrandsAKeyOnADeletedUser() throws Exception {
// One key for every trial: each gets a fresh store, so uniqueness is not what is under
// test, and generating RSA per trial would be the whole runtime.
String body = openSshKey();
for (int trial = 0; trial < 60; trial++) {
InMemoryStorage<String, SshPublicKey> store = new InMemoryStorage<>();
IamService service = newService(store, ACCOUNT_A);
service.createUser("delete-race", "/");
ExecutorService pool = Executors.newFixedThreadPool(2);
CountDownLatch start = new CountDownLatch(1);
try {
pool.submit(() -> {
start.await();
try {
service.uploadSshPublicKey("delete-race", body);
} catch (AwsException expected) {
// NoSuchEntity when the delete won.
}
return null;
});
pool.submit(() -> {
start.await();
try {
service.deleteUser("delete-race");
} catch (AwsException expected) {
// DeleteConflict when the upload won.
}
return null;
});
start.countDown();
pool.shutdown();
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "trial did not finish");
} finally {
pool.shutdownNow();
}
boolean userExists;
try {
service.getUser("delete-race");
userExists = true;
} catch (AwsException gone) {
userExists = false;
}
if (!userExists) {
assertTrue(store.scan(key -> true).isEmpty(),
"trial " + trial + ": key left behind on a deleted user");
}
}
}
/**
* The same hazard on the rename path. Ran many times because the window between capturing the
* keys to move and republishing the user is a few statements wide: at thirty trials this
* passed even with the rename's lock removed, which would have made it a test that guarded
* nothing.
*/
@Test
void anUploadNeverStrandsAKeyOnTheOldNameDuringARename() throws Exception {
String body = openSshKey();
for (int trial = 0; trial < 300; trial++) {
InMemoryStorage<String, SshPublicKey> store = new InMemoryStorage<>();
IamService service = newService(store, ACCOUNT_A);
service.createUser("rename-race-from", "/");
ExecutorService pool = Executors.newFixedThreadPool(2);
CountDownLatch start = new CountDownLatch(1);
try {
pool.submit(() -> {
start.await();
try {
service.uploadSshPublicKey("rename-race-from", body);
} catch (AwsException expected) {
// NoSuchEntity when the rename landed first.
}
return null;
});
pool.submit(() -> {
start.await();
service.updateUser("rename-race-from", "rename-race-to", null);
return null;
});
start.countDown();
pool.shutdown();
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "trial did not finish");
} finally {
pool.shutdownNow();
}
for (SshPublicKey key : store.scan(k -> true)) {
assertEquals("rename-race-to", key.getUserName(),
"trial " + trial + ": key stranded on the pre-rename name");
}
}
}
}
@@ -52,6 +52,7 @@ class VirtualMfaAccountScopeTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), devices,
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", ACCOUNT_A), false, null);
VirtualMfaDevice device = service.createVirtualMfaDevice("shared-name", "/", Map.of());
@@ -91,6 +92,7 @@ class VirtualMfaAccountScopeTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), devices,
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", ACCOUNT_A), false, null);
VirtualMfaDevice inA = service.createVirtualMfaDevice("same-name", "/", Map.of());
@@ -39,6 +39,7 @@ class VirtualMfaConcurrencyTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("eu-central-1", "000000000000"), false, null);
}