diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamSshPublicKeyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamSshPublicKeyTest.java new file mode 100644 index 0000000000..e601aa3174 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamSshPublicKeyTest.java @@ -0,0 +1,185 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import software.amazon.awssdk.services.iam.IamClient; +import software.amazon.awssdk.services.iam.model.CreateUserRequest; +import software.amazon.awssdk.services.iam.model.DeleteSshPublicKeyRequest; +import software.amazon.awssdk.services.iam.model.DeleteUserRequest; +import software.amazon.awssdk.services.iam.model.EncodingType; +import software.amazon.awssdk.services.iam.model.GetSshPublicKeyRequest; +import software.amazon.awssdk.services.iam.model.GetSshPublicKeyResponse; +import software.amazon.awssdk.services.iam.model.ListSshPublicKeysRequest; +import software.amazon.awssdk.services.iam.model.ListSshPublicKeysResponse; +import software.amazon.awssdk.services.iam.model.NoSuchEntityException; +import software.amazon.awssdk.services.iam.model.SSHPublicKeyMetadata; +import software.amazon.awssdk.services.iam.model.StatusType; +import software.amazon.awssdk.services.iam.model.UpdateSshPublicKeyRequest; +import software.amazon.awssdk.services.iam.model.UploadSshPublicKeyRequest; +import software.amazon.awssdk.services.iam.model.UploadSshPublicKeyResponse; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * SSH public keys driven through the AWS SDK rather than hand-written requests. + * + *
This is the check the handcrafted XML assertions cannot make: the SDK parses the response + * against its own model, so a missing required member, a mis-named element or a timestamp in the + * wrong format fails here even though the raw XML looked right. Two enums round-trip as well, + * {@code StatusType} and {@code EncodingType}, so a value the model does not know would come back + * as {@code UNKNOWN_TO_SDK_VERSION} rather than as a string that merely looked correct. + */ +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class IamSshPublicKeyTest { + + private static final String USER_NAME = "sdk-test-ssh-user"; + + /** A real 2048-bit RSA public key in the ssh-rsa form, generated with ssh-keygen. */ + private static final String SSH_RSA_BODY = + "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCw3HqlhXlIaYKbGK1G2G8Mv4o6izJVoEIG" + + "c4x3cEZlBR9XG2l905tpn0qdEiylsJj43L91ILHOgIbhh1cmFRRozbKIIOs0hCcGbdwY9le0" + + "4vO2ufw7OXDJcO7TzatJq/XgeArQ39WbJTO8FCAy5woufVwGGhqX8G55VNzQS7jE4/N/CuTF" + + "jbo6m0vFQ7gCRDwYmwslrrk71C/CfBJCeqNLeBs+5moqjpZLCEnhLJHf/hHdSTV7x+DduWrB" + + "OPejy82PUfqPBY4fi2QT/Je/NseMqEb0lCz3fxBZK9vC53dHTUHck7koWIUU9P5+KFTepZsJ" + + "pdpBHQRI+EcEgtoGRgYX"; + + private static IamClient iam; + private static String keyId; + + @BeforeAll + static void setup() { + iam = TestFixtures.iamClient(); + cleanupUser(); + iam.createUser(CreateUserRequest.builder().userName(USER_NAME).build()); + } + + @AfterAll + static void cleanup() { + cleanupUser(); + } + + private static void cleanupUser() { + if (iam == null) { + return; + } + try { + ListSshPublicKeysResponse existing = iam.listSSHPublicKeys( + ListSshPublicKeysRequest.builder().userName(USER_NAME).build()); + for (SSHPublicKeyMetadata key : existing.sshPublicKeys()) { + iam.deleteSSHPublicKey(DeleteSshPublicKeyRequest.builder() + .userName(USER_NAME) + .sshPublicKeyId(key.sshPublicKeyId()) + .build()); + } + iam.deleteUser(DeleteUserRequest.builder().userName(USER_NAME).build()); + } catch (NoSuchEntityException expected) { + // Nothing left over from an earlier run, which is the normal case. + } + } + + @Test + @Order(1) + @DisplayName("UploadSSHPublicKey returns an APKA id, a fingerprint and an Active status") + void upload() { + UploadSshPublicKeyResponse response = iam.uploadSSHPublicKey( + UploadSshPublicKeyRequest.builder() + .userName(USER_NAME) + .sshPublicKeyBody(SSH_RSA_BODY) + .build()); + + assertNotNull(response.sshPublicKey(), "the response must carry the key"); + assertEquals(USER_NAME, response.sshPublicKey().userName()); + assertEquals(StatusType.ACTIVE, response.sshPublicKey().status()); + assertNotNull(response.sshPublicKey().uploadDate(), "UploadDate must parse as a timestamp"); + assertNotNull(response.sshPublicKey().fingerprint(), "Fingerprint is a required member"); + assertTrue(response.sshPublicKey().fingerprint().matches("([0-9a-f]{2}:){15}[0-9a-f]{2}"), + "the fingerprint is colon-delimited MD5: " + response.sshPublicKey().fingerprint()); + + keyId = response.sshPublicKey().sshPublicKeyId(); + assertNotNull(keyId); + assertTrue(keyId.length() >= 20, "publicKeyIdType has a minimum of 20: " + keyId); + } + + @Test + @Order(2) + @DisplayName("GetSSHPublicKey converts to the requested encoding") + void getInBothEncodings() { + GetSshPublicKeyResponse asPem = iam.getSSHPublicKey(GetSshPublicKeyRequest.builder() + .userName(USER_NAME) + .sshPublicKeyId(keyId) + .encoding(EncodingType.PEM) + .build()); + assertTrue(asPem.sshPublicKey().sshPublicKeyBody().contains("BEGIN PUBLIC KEY"), + "PEM was asked for: " + asPem.sshPublicKey().sshPublicKeyBody()); + + GetSshPublicKeyResponse asSsh = iam.getSSHPublicKey(GetSshPublicKeyRequest.builder() + .userName(USER_NAME) + .sshPublicKeyId(keyId) + .encoding(EncodingType.SSH) + .build()); + assertTrue(asSsh.sshPublicKey().sshPublicKeyBody().startsWith("ssh-rsa "), + "SSH was asked for: " + asSsh.sshPublicKey().sshPublicKeyBody()); + + // The same key either way, so the fingerprint cannot change with the encoding. + assertEquals(asPem.sshPublicKey().fingerprint(), asSsh.sshPublicKey().fingerprint()); + } + + @Test + @Order(3) + @DisplayName("ListSSHPublicKeys returns metadata without the body or fingerprint") + void list() { + ListSshPublicKeysResponse response = iam.listSSHPublicKeys( + ListSshPublicKeysRequest.builder().userName(USER_NAME).build()); + + assertEquals(1, response.sshPublicKeys().size()); + SSHPublicKeyMetadata metadata = response.sshPublicKeys().get(0); + assertEquals(keyId, metadata.sshPublicKeyId()); + assertEquals(USER_NAME, metadata.userName()); + assertEquals(StatusType.ACTIVE, metadata.status()); + assertNotNull(metadata.uploadDate(), "UploadDate is required on the metadata shape"); + } + + @Test + @Order(4) + @DisplayName("UpdateSSHPublicKey sets the status and the SDK reads it back as an enum") + void updateStatus() { + iam.updateSSHPublicKey(UpdateSshPublicKeyRequest.builder() + .userName(USER_NAME) + .sshPublicKeyId(keyId) + .status(StatusType.INACTIVE) + .build()); + + ListSshPublicKeysResponse response = iam.listSSHPublicKeys( + ListSshPublicKeysRequest.builder().userName(USER_NAME).build()); + assertEquals(StatusType.INACTIVE, response.sshPublicKeys().get(0).status(), + "the status must come back as a value the SDK model knows"); + } + + @Test + @Order(5) + @DisplayName("DeleteSSHPublicKey removes it, and an unknown id is NoSuchEntity") + void delete() { + iam.deleteSSHPublicKey(DeleteSshPublicKeyRequest.builder() + .userName(USER_NAME) + .sshPublicKeyId(keyId) + .build()); + + ListSshPublicKeysResponse response = iam.listSSHPublicKeys( + ListSshPublicKeysRequest.builder().userName(USER_NAME).build()); + assertTrue(response.sshPublicKeys().isEmpty()); + + assertThrows(NoSuchEntityException.class, () -> iam.deleteSSHPublicKey( + DeleteSshPublicKeyRequest.builder() + .userName(USER_NAME) + .sshPublicKeyId(keyId) + .build())); + } +} diff --git a/docs/services/iam.md b/docs/services/iam.md index 753dbfb598..862ee577aa 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -578,6 +578,57 @@ Classic and CloudFront store certificate identifiers without resolving them agai [#4875](https://github.com/floci-io/floci/issues/4875), which covers both directions: rejecting a reference to a certificate that does not exist, and refusing to delete one that is in use. +### SSH Public Keys + +| Action | Description | +|--------|-------------| +| UploadSSHPublicKey | Stores an SSH public key against an IAM user and returns its generated `SSHPublicKeyId`. | +| GetSSHPublicKey | Returns a key in the encoding `Encoding` asks for, `SSH` or `PEM`. | +| ListSSHPublicKeys | Lists a user's keys as metadata, with `Marker` and `MaxItems` paging. | +| UpdateSSHPublicKey | Sets a key's status to `Active`, `Inactive` or `Expired`. | +| DeleteSSHPublicKey | Deletes one of a user's SSH public keys. | + +AWS accepts the body "encoded in ssh-rsa format or PEM format", 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 +of it. `GetSSHPublicKey` converts, because `Encoding` is required and decides the form of the +response, so a key uploaded as `ssh-rsa` comes back as PEM when PEM is asked for. + +`Fingerprint` is the MD5 of the OpenSSH blob, which is what AWS reports here. It is deliberately not +the digest EC2 reports for the same key, which is taken over the DER: both are sixteen bytes of +colon-delimited hex, so the wrong one would look entirely plausible. The value is checked against +the worked example in the IAM API Reference rather than assumed. + +Five keys per user, which the IAM service quotas give as "SSH Public keys per user" and mark as not +adjustable. A sixth upload is `LimitExceeded`, counted inside the same lock as the write so +concurrent uploads cannot both see room for the last slot. The minimum bit-length is 2048, as the +model documents. + +The two rejection errors are kept apart the way the model separates them. A body in neither accepted +encoding is `UnrecognizedPublicKeyEncoding`; a body 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 happens to base64-decode, since short words +often do. + +`DuplicateSSHPublicKey` is per user, not account-wide: AWS describes it as a key "already associated +with the specified IAM user", so two users may hold the same key. The comparison is on the +fingerprint, so the same key uploaded in the other encoding still counts as a duplicate. + +`ListSSHPublicKeys` returns metadata only. AWS documents `SSHPublicKeyMetadata` as describing a key +"without the key's body or fingerprint", so neither appears in the list even though both are stored. + +An SSH public key blocks `DeleteUser` until it is removed, which is one of the items AWS lists as a +prerequisite for deleting a user programmatically, and it follows the user across an `UpdateUser` +rename: left behind, a key would be stranded on a name that no longer exists, invisible to its owner +because listing goes through the user. + +`UserName` is required on every one of these operations except `ListSSHPublicKeys`, where the model +marks it optional and it resolves from the access key that signed the request. That is the opposite +of the signing-certificate operations, where it is optional throughout. + +Under [enforcement](#iam-enforcement-mode) these actions are evaluated against `*` rather than the +owning user's ARN, along with every other IAM action except the server-certificate operations, which +is the general gap tracked in [#4979](https://github.com/floci-io/floci/issues/4979). + ### Signing Certificates | Action | Description | diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index c8db010ae2..2f0985b02a 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -119,6 +119,8 @@ public class AwsQueryController { "CreateVirtualMFADevice", "DeleteVirtualMFADevice", "ListVirtualMFADevices", "EnableMFADevice", "DeactivateMFADevice", "ResyncMFADevice", "ListMFADevices", "TagMFADevice", "UntagMFADevice", "ListMFADeviceTags", + "UploadSSHPublicKey", "GetSSHPublicKey", "ListSSHPublicKeys", + "UpdateSSHPublicKey", "DeleteSSHPublicKey", "UploadSigningCertificate", "ListSigningCertificates", "UpdateSigningCertificate", "DeleteSigningCertificate" ); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SshPublicKeys.java b/src/main/java/io/github/hectorvent/floci/core/common/SshPublicKeys.java index ba84cd026c..5f9d2be158 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/SshPublicKeys.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/SshPublicKeys.java @@ -3,12 +3,14 @@ package io.github.hectorvent.floci.core.common; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPublicKeySpec; +import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import java.util.HexFormat; @@ -30,6 +32,8 @@ public final class SshPublicKeys { */ private static final int MAX_FIELD_LENGTH = 64 * 1024; + private static final int PEM_LINE_LENGTH = 64; + private SshPublicKeys() {} /** @@ -108,7 +112,13 @@ public final class SshPublicKeys { */ public static RSAPublicKey rsaKeyOf(byte[] blob) { Reader reader = reader(blob); - reader.readField(); + // The declared type is checked rather than skipped. Discarding it parses the exponent and + // modulus of whatever follows, so a line labelled ssh-ed25519 carrying an RSA blob would + // be read as an RSA key and stored under a type that was never supported. + String type = new String(reader.readField(), StandardCharsets.UTF_8); + if (!"ssh-rsa".equals(type)) { + throw new SshPublicKeyException("not an ssh-rsa blob: " + type); + } BigInteger exponent = new BigInteger(reader.readField()); BigInteger modulus = new BigInteger(reader.readField()); try { @@ -125,7 +135,7 @@ public final class SshPublicKeys { } /** The OpenSSH blob for a key: the type, then the exponent, then the modulus. */ - private static byte[] openSshBlob(RSAPublicKey key) { + public static byte[] openSshBlob(RSAPublicKey key) { byte[] type = "ssh-rsa".getBytes(StandardCharsets.US_ASCII); byte[] exponent = key.getPublicExponent().toByteArray(); byte[] modulus = key.getModulus().toByteArray(); @@ -137,6 +147,65 @@ public final class SshPublicKeys { return blob.array(); } + /** The key type an OpenSSH blob declares, such as {@code ssh-rsa}. */ + public static String keyType(byte[] blob) { + return new String(reader(blob).readField(), StandardCharsets.UTF_8); + } + + /** The key as a PEM SubjectPublicKeyInfo, the {@code BEGIN PUBLIC KEY} form. */ + public static String toPem(RSAPublicKey key) { + String body = Base64.getEncoder().encodeToString(key.getEncoded()); + StringBuilder pem = new StringBuilder("-----BEGIN PUBLIC KEY-----\n"); + for (int i = 0; i < body.length(); i += PEM_LINE_LENGTH) { + pem.append(body, i, Math.min(i + PEM_LINE_LENGTH, body.length())).append('\n'); + } + return pem.append("-----END PUBLIC KEY-----\n").toString(); + } + + /** + * Whether a value is a PEM public key rather than an OpenSSH line. Both markers are required: + * treating the closing one as optional accepts a truncated body, which then decodes because + * the base64 that survived is still valid base64. + */ + public static boolean looksLikePem(String value) { + return value != null + && value.contains("-----BEGIN PUBLIC KEY-----") + && value.contains("-----END PUBLIC KEY-----"); + } + + /** Whether a value opens as PEM, whether or not it is complete. */ + public static boolean opensAsPem(String value) { + return value != null && value.contains("-----BEGIN PUBLIC KEY-----"); + } + + /** The RSA public key a PEM SubjectPublicKeyInfo carries. */ + public static RSAPublicKey fromPem(String pem) { + if (!looksLikePem(pem)) { + throw new SshPublicKeyException("not a PEM public key"); + } + String body = pem.replace("-----BEGIN PUBLIC KEY-----", "") + .replace("-----END PUBLIC KEY-----", "") + .replaceAll("\\s", ""); + try { + return (RSAPublicKey) KeyFactory.getInstance("RSA") + .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(body))); + } catch (IllegalArgumentException | GeneralSecurityException | ClassCastException e) { + throw new SshPublicKeyException("not a usable RSA public key: " + e.getMessage(), e); + } + } + + /** + * The OpenSSH fingerprint: the MD5 of the blob itself, colon-delimited lowercase hex. + * + *
This is what IAM reports as an SSH public key's {@code Fingerprint}, confirmed by
+ * reproducing the worked example in the IAM API Reference. It is deliberately not the digest
+ * EC2 reports for the same key, which is taken over the DER: both are sixteen bytes of colon
+ * hex, so substituting one for the other is wrong and looks right.
+ */
+ public static String openSshFingerprint(byte[] blob) {
+ return md5ColonHex(blob);
+ }
+
/** MD5 of the given bytes as colon-delimited lowercase hex. */
public static String md5ColonHex(byte[] bytes) {
try {
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
index f83e3f3742..8565b718c0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
@@ -15,9 +15,10 @@ import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider;
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
import io.github.hectorvent.floci.services.iam.model.SAMLProvider;
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
-import io.github.hectorvent.floci.services.iam.model.SigningCertificate;
import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedEntity;
import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedJob;
+import io.github.hectorvent.floci.services.iam.model.SigningCertificate;
+import io.github.hectorvent.floci.services.iam.model.SshPublicKey;
import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -92,6 +93,11 @@ public class IamQueryHandler {
case "DeleteUser" -> handleDeleteUser(params);
case "ListUsers" -> handleListUsers(params);
case "UpdateUser" -> handleUpdateUser(params);
+ case "UploadSSHPublicKey" -> handleUploadSshPublicKey(params);
+ case "GetSSHPublicKey" -> handleGetSshPublicKey(params);
+ case "ListSSHPublicKeys" -> handleListSshPublicKeys(params, authorization);
+ case "UpdateSSHPublicKey" -> handleUpdateSshPublicKey(params);
+ case "DeleteSSHPublicKey" -> handleDeleteSshPublicKey(params);
case "UploadSigningCertificate" -> handleUploadSigningCertificate(params, authorization);
case "ListSigningCertificates" -> handleListSigningCertificates(params, authorization);
case "UpdateSigningCertificate" -> handleUpdateSigningCertificate(params, authorization);
@@ -756,6 +762,79 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("ListServerCertificates", AwsNamespaces.IAM, xml.build())).build();
}
+ /**
+ * UserName is required on every SSH public key operation but the list, which is the opposite
+ * of the signing-certificate operations: there the model marks it optional throughout.
+ */
+ private Response handleUploadSshPublicKey(MultivaluedMap The encoding is distinguished from the material, because the model separates them:
+ * something that is neither form is {@code UnrecognizedPublicKeyEncoding}, while something in
+ * a recognised form that will not parse is {@code InvalidPublicKey}.
+ */
+ public SshPublicKey uploadSshPublicKey(String userName, String body) {
+ if (body == null || body.isBlank()) {
+ throw new AwsException("ValidationError",
+ "The request must contain the parameter SSHPublicKeyBody.", 400);
+ }
+ checkMaterialLength(body, "SSHPublicKeyBody", MAX_SSH_PUBLIC_KEY_BODY_LENGTH);
+ RSAPublicKey key = readSshPublicKey(body);
+ if (key.getModulus().bitLength() < MIN_SSH_PUBLIC_KEY_BITS) {
+ throw new AwsException("InvalidPublicKey",
+ "The minimum bit-length of the public key is " + MIN_SSH_PUBLIC_KEY_BITS
+ + " bits.", 400);
+ }
+ String fingerprint = SshPublicKeys.openSshFingerprint(SshPublicKeys.openSshBlob(key));
+ synchronized (sshPublicKeyLock) {
+ // Confirmed under the lock, not before it: DeleteUser checks for keys holding the same
+ // lock, so the two cannot interleave into a key owned by a user that no longer exists.
+ getUser(userName);
+ List The body is kept as it was uploaded, in whichever of the two accepted encodings that was, and
+ * {@code GetSSHPublicKey} converts it to the encoding the request asks for. Keeping the original
+ * means a caller that uploaded PEM gets back byte-identical PEM rather than a re-encoding of it.
+ *
+ * {@code fingerprint} is the MD5 of the OpenSSH blob, which is what AWS reports here. It is not
+ * the digest EC2 reports for the same key, which is taken over the DER.
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class SshPublicKey {
+ private String userName;
+ private String sshPublicKeyId;
+ private String fingerprint;
+ /** As uploaded: either an {@code ssh-rsa} line or a PEM SubjectPublicKeyInfo. */
+ private String sshPublicKeyBody;
+ private String status = "Active";
+ private Instant uploadDate = Instant.now();
+
+ public SshPublicKey() {}
+
+ public String getUserName() { return userName; }
+ public void setUserName(String userName) { this.userName = userName; }
+ public String getSshPublicKeyId() { return sshPublicKeyId; }
+ public void setSshPublicKeyId(String sshPublicKeyId) { this.sshPublicKeyId = sshPublicKeyId; }
+ public String getFingerprint() { return fingerprint; }
+ public void setFingerprint(String fingerprint) { this.fingerprint = fingerprint; }
+ public String getSshPublicKeyBody() { return sshPublicKeyBody; }
+ public void setSshPublicKeyBody(String sshPublicKeyBody) {
+ this.sshPublicKeyBody = sshPublicKeyBody;
+ }
+ public String getStatus() { return status; }
+ public void setStatus(String status) { this.status = status; }
+ public Instant getUploadDate() { return uploadDate; }
+ public void setUploadDate(Instant uploadDate) { this.uploadDate = uploadDate; }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/SshPublicKeysTest.java b/src/test/java/io/github/hectorvent/floci/core/common/SshPublicKeysTest.java
index 5db86583ec..6b88611dc6 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/SshPublicKeysTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/SshPublicKeysTest.java
@@ -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))));
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java
index 47f2d11385..8abcb2507a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java
@@ -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);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
index f527fbb291..3b1001becb 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
@@ -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();
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateStateTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateStateTest.java
index 57af3db77d..e9207fa03d 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateStateTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateStateTest.java
@@ -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);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateStateTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateStateTest.java
index cd90a40671..7e46d78df3 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateStateTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateStateTest.java
@@ -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);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/SshPublicKeyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/SshPublicKeyIntegrationTest.java
new file mode 100644
index 0000000000..808ea4eadf
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/SshPublicKeyIntegrationTest.java
@@ -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.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * 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"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/SshPublicKeyStateTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/SshPublicKeyStateTest.java
new file mode 100644
index 0000000000..5e6e36b6d2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/SshPublicKeyStateTest.java
@@ -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