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 params) { + SshPublicKey key = iamService.uploadSshPublicKey(requireParam(params, "UserName"), + getParam(params, "SSHPublicKeyBody")); + XmlBuilder xml = new XmlBuilder() + .start("SSHPublicKey").raw(sshPublicKeyXml(key)).end("SSHPublicKey"); + return Response.ok(AwsQueryResponse.envelope("UploadSSHPublicKey", + AwsNamespaces.IAM, xml.build())).build(); + } + + private Response handleGetSshPublicKey(MultivaluedMap params) { + SshPublicKey key = iamService.getSshPublicKey(requireParam(params, "UserName"), + requireParam(params, "SSHPublicKeyId"), getParam(params, "Encoding")); + XmlBuilder xml = new XmlBuilder() + .start("SSHPublicKey").raw(sshPublicKeyXml(key)).end("SSHPublicKey"); + return Response.ok(AwsQueryResponse.envelope("GetSSHPublicKey", + AwsNamespaces.IAM, xml.build())).build(); + } + + /** + * The metadata list only. AWS documents SSHPublicKeyMetadata as carrying the key "without the + * key's body or fingerprint", so neither appears here even though both are stored. + */ + private Response handleListSshPublicKeys(MultivaluedMap params, + String authorization) { + Page page = paginate( + iamService.listSshPublicKeys(resolveUserName(params, authorization)), params); + XmlBuilder xml = new XmlBuilder().start("SSHPublicKeys"); + for (SshPublicKey key : page.items()) { + xml.start("member") + .elem("UserName", key.getUserName()) + .elem("SSHPublicKeyId", key.getSshPublicKeyId()) + .elem("Status", key.getStatus()) + .elem("UploadDate", isoDate(key.getUploadDate())) + .end("member"); + } + xml.end("SSHPublicKeys").elem("IsTruncated", page.truncated()); + if (page.marker() != null) { + xml.elem("Marker", page.marker()); + } + return Response.ok(AwsQueryResponse.envelope("ListSSHPublicKeys", + AwsNamespaces.IAM, xml.build())).build(); + } + + private Response handleUpdateSshPublicKey(MultivaluedMap params) { + iamService.updateSshPublicKey(requireParam(params, "UserName"), + requireParam(params, "SSHPublicKeyId"), getParam(params, "Status")); + return Response.ok(AwsQueryResponse.envelopeNoResult("UpdateSSHPublicKey", + AwsNamespaces.IAM)).build(); + } + + private Response handleDeleteSshPublicKey(MultivaluedMap params) { + iamService.deleteSshPublicKey(requireParam(params, "UserName"), + requireParam(params, "SSHPublicKeyId")); + return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteSSHPublicKey", + AwsNamespaces.IAM)).build(); + } + + /** The five members the model marks required on SSHPublicKey, plus UploadDate. */ + private String sshPublicKeyXml(SshPublicKey key) { + return new XmlBuilder() + .elem("UserName", key.getUserName()) + .elem("SSHPublicKeyId", key.getSshPublicKeyId()) + .elem("Fingerprint", key.getFingerprint()) + .elem("SSHPublicKeyBody", key.getSshPublicKeyBody()) + .elem("Status", key.getStatus()) + .elem("UploadDate", isoDate(key.getUploadDate())) + .build(); + } + /** * UserName is optional on every signing-certificate operation: the model says it is determined * implicitly from the access key that signed the request. diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java index 02ff57f3de..5cc89e4532 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java @@ -9,6 +9,8 @@ import io.github.hectorvent.floci.core.common.Pem; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.common.SessionAccountLookup; +import io.github.hectorvent.floci.core.common.SshPublicKeyException; +import io.github.hectorvent.floci.core.common.SshPublicKeys; import io.github.hectorvent.floci.core.common.Totp; import io.github.hectorvent.floci.core.resource.ExplorerResource; import io.github.hectorvent.floci.core.resource.ResourceProvider; @@ -31,8 +33,9 @@ import io.github.hectorvent.floci.services.iam.model.OrganizationRootFeatures; import io.github.hectorvent.floci.services.iam.model.PolicyVersion; import io.github.hectorvent.floci.services.iam.model.CallerContext; 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.SessionCredential; +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 com.fasterxml.jackson.core.type.TypeReference; import io.quarkus.runtime.Startup; @@ -47,6 +50,7 @@ import java.security.PrivateKey; import java.security.SecureRandom; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPublicKey; import java.time.Duration; import java.time.Instant; import java.time.format.DateTimeFormatter; @@ -148,15 +152,24 @@ public class IamService implements SessionAccountLookup, ResourceProvider { private static final int MAX_SERVER_CERTIFICATES = 20; /** IAM User Guide quota table, and GetAccountSummary's SigningCertificatesPerUserQuota. */ private static final int MAX_SIGNING_CERTIFICATES_PER_USER = 2; + /** AWS General Reference, IAM service quotas: "SSH Public keys per user", not adjustable. */ + private static final int MAX_SSH_PUBLIC_KEYS_PER_USER = 5; + /** publicKeyIdType is 20 to 128 of [\w]+, and AWS's own examples use the APKA prefix. */ + private static final int SSH_PUBLIC_KEY_ID_SUFFIX_LENGTH = 16; + private static final int MIN_SSH_PUBLIC_KEY_BITS = 2048; + private static final int MAX_SSH_PUBLIC_KEY_BODY_LENGTH = 16384; + /** GetSSHPublicKey's Encoding: "To retrieve the public key in ssh-rsa format, use SSH." */ + private static final Set SSH_PUBLIC_KEY_ENCODINGS = Set.of("SSH", "PEM"); /** certificateIdType is 24 to 128 of [\w]+, so a 32-character id sits inside that. */ private static final int SIGNING_CERTIFICATE_ID_LENGTH = 32; - private static final String SIGNING_CERTIFICATE_ACTIVE = "Active"; + private static final String CREDENTIAL_STATUS_ACTIVE = "Active"; /** - * UpdateSigningCertificate's Status, whose documented valid values are Active, Inactive and - * Expired. The prose explains only the first two, so the third is easy to reject by mistake. + * statusType's values, shared by signing certificates and SSH public keys: Active, Inactive + * and Expired. Each operation's prose explains only the first two, so the third is easy to + * reject by mistake, while the API Reference lists all three as valid. */ - private static final Set SIGNING_CERTIFICATE_STATUSES = - Set.of(SIGNING_CERTIFICATE_ACTIVE, "Inactive", "Expired"); + private static final Set CREDENTIAL_STATUSES = + Set.of(CREDENTIAL_STATUS_ACTIVE, "Inactive", "Expired"); /** {@code certificateBodyType} and {@code privateKeyType} are both 1 to 16384 characters. */ private static final int MAX_CERTIFICATE_BODY_LENGTH = 16384; /** {@code certificateChainType} is far larger, at 1 to 2097152. */ @@ -232,6 +245,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { /** Server certificates, keyed by name, which is unique within the account. */ private final StorageBackend serverCertificates; private final StorageBackend signingCertificates; + private final StorageBackend sshPublicKeys; /** * Guards the check-then-write on a server certificate. Upload checks the name is free before * storing, and UpdateServerCertificate checks a new name is free before moving to it, so two @@ -239,6 +253,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { */ private final Object serverCertificateLock = new Object(); private final Object signingCertificateLock = new Object(); + private final Object sshPublicKeyLock = new Object(); /** * Guards every check-then-write on an MFA device. Assignment is the reason it has to exist: * EnableMFADevice reads the device to confirm it is unassigned and reads the user's device @@ -281,6 +296,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { storageFactory.create("iam", "iam-virtual-mfa-devices.json", new TypeReference<>() {}), storageFactory.create("iam", "iam-server-certificates.json", new TypeReference<>() {}), storageFactory.create("iam", "iam-signing-certificates.json", new TypeReference<>() {}), + storageFactory.create("iam", "iam-ssh-public-keys.json", new TypeReference<>() {}), regionResolver, config.services().iam().seedDeployerPrincipal(), config.services().iam().accountAlias().orElse(null) @@ -312,6 +328,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, null); } @@ -335,6 +352,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { accountAliases, passwordPolicies, new InMemoryStorage<>(), oidcProviders, serviceLinkedRoleDeletions, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, seededAccountAlias); } @@ -356,6 +374,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { new InMemoryStorage<>(), new InMemoryStorage<>(), orgRootFeatures, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, null); } @@ -376,6 +395,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { StorageBackend virtualMfaDevices, StorageBackend serverCertificates, StorageBackend signingCertificates, + StorageBackend sshPublicKeys, RegionResolver regionResolver, boolean seedDeployerPrincipal, String seededAccountAlias) { @@ -396,6 +416,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { this.virtualMfaDevices = virtualMfaDevices; this.serverCertificates = serverCertificates; this.signingCertificates = signingCertificates; + this.sshPublicKeys = sshPublicKeys; this.regionResolver = regionResolver; this.seedDeployerPrincipal = seedDeployerPrincipal; this.seededAccountAlias = seededAccountAlias; @@ -571,20 +592,26 @@ public class IamService implements SessionAccountLookup, ResourceProvider { "Cannot delete entity, must delete access keys first.", 409); } // Both locks are held across the delete rather than just the checks: UploadSigningCertificate - // and EnableMFADevice confirm the user under their own lock, so neither can interleave into - // a credential owned by a deleted user. Taken in this order, and nowhere else in both, so - // the nesting cannot deadlock. - synchronized (signingCertificateLock) { - if (!userSigningCertificates(userName).isEmpty()) { + // UploadSigningCertificate and EnableMFADevice confirm the user under their own lock, so + // none of them can interleave into a credential owned by a deleted user. Taken in this + // order here and in UpdateUser, and nowhere else in more than one, so it cannot deadlock. + synchronized (sshPublicKeyLock) { + if (!userSshPublicKeys(userName).isEmpty()) { throw new AwsException("DeleteConflict", - "Cannot delete entity, must delete signing certificates first.", 409); + "Cannot delete entity, must delete SSH public keys first.", 409); } - synchronized (mfaDeviceLock) { - if (!mfaDevicesForUser(userName).isEmpty()) { + synchronized (signingCertificateLock) { + if (!userSigningCertificates(userName).isEmpty()) { throw new AwsException("DeleteConflict", - "Cannot delete entity, must deactivate MFA device first.", 409); + "Cannot delete entity, must delete signing certificates first.", 409); + } + synchronized (mfaDeviceLock) { + if (!mfaDevicesForUser(userName).isEmpty()) { + throw new AwsException("DeleteConflict", + "Cannot delete entity, must deactivate MFA device first.", 409); + } + users.delete(userName); } - users.delete(userName); } } LOG.infov("Deleted IAM user: {0}", userName); @@ -624,30 +651,37 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } List keysToMove = userAccessKeys(userName); // The rename publishes the user under its new name and moves the credentials that - // DeleteUser refuses to delete a user over: its MFA devices and its signing - // certificates. Each moves under the lock DeleteUser checks it with, because split + // DeleteUser refuses to delete a user over: its MFA devices, its signing + // certificates and its SSH public keys. Each moves under the lock DeleteUser checks it with, because split // across that lock a DeleteUser for the new name could land after the user is // published but before the credential follows, see none, and delete a user whose // credential is about to be reassigned to it. The two locks are taken in the same // order DeleteUser takes them, so the nesting cannot deadlock. - synchronized (signingCertificateLock) { - List certificatesToMove = userSigningCertificates(userName); - synchronized (mfaDeviceLock) { - users.delete(userName); - user.setUserName(newUserName); - if (newPath != null) { - user.setPath(normalizePath(newPath)); + synchronized (sshPublicKeyLock) { + List sshKeysToMove = userSshPublicKeys(userName); + synchronized (signingCertificateLock) { + List certificatesToMove = userSigningCertificates(userName); + synchronized (mfaDeviceLock) { + users.delete(userName); + user.setUserName(newUserName); + if (newPath != null) { + user.setPath(normalizePath(newPath)); + } + user.setArn(iamArnBeside(user.getArn(), "user", user.getPath(), newUserName)); + users.put(newUserName, user); + for (VirtualMfaDevice device : mfaDevicesForUser(userName)) { + device.setUserName(newUserName); + virtualMfaDevices.put(device.getSerialNumber(), device); + } } - user.setArn(iamArnBeside(user.getArn(), "user", user.getPath(), newUserName)); - users.put(newUserName, user); - for (VirtualMfaDevice device : mfaDevicesForUser(userName)) { - device.setUserName(newUserName); - virtualMfaDevices.put(device.getSerialNumber(), device); + for (SigningCertificate certificate : certificatesToMove) { + certificate.setUserName(newUserName); + signingCertificates.put(certificate.getCertificateId(), certificate); } } - for (SigningCertificate certificate : certificatesToMove) { - certificate.setUserName(newUserName); - signingCertificates.put(certificate.getCertificateId(), certificate); + for (SshPublicKey key : sshKeysToMove) { + key.setUserName(newUserName); + sshPublicKeys.put(key.getSshPublicKeyId(), key); } } loginProfiles.get(userName).ifPresent(profile -> { @@ -2368,7 +2402,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { stored.setUserName(userName); stored.setCertificateId(randomId(SIGNING_CERTIFICATE_ID_LENGTH)); stored.setCertificateBody(certificateBody); - stored.setStatus(SIGNING_CERTIFICATE_ACTIVE); + stored.setStatus(CREDENTIAL_STATUS_ACTIVE); stored.setUploadDate(Instant.now()); signingCertificates.put(stored.getCertificateId(), stored); LOG.infov("Uploaded signing certificate {0} for user {1}", @@ -2383,11 +2417,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } public void updateSigningCertificate(String userName, String certificateId, String status) { - if (status == null || !SIGNING_CERTIFICATE_STATUSES.contains(status)) { + if (status == null || !CREDENTIAL_STATUSES.contains(status)) { throw new AwsException("ValidationError", "Value '" + status + "' at 'status' failed to satisfy constraint: Member must " + "satisfy enum value set: [" + String.join(", ", - SIGNING_CERTIFICATE_STATUSES) + "]", 400); + CREDENTIAL_STATUSES) + "]", 400); } synchronized (signingCertificateLock) { SigningCertificate certificate = userSigningCertificate(userName, certificateId); @@ -2455,6 +2489,189 @@ public class IamService implements SessionAccountLookup, ResourceProvider { }); } + // SSH public keys + // ========================================================================= + + /** + * Stores an SSH public key against a user. AWS accepts the body in {@code 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 of it. + * + *

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 existing = userSshPublicKeys(userName); + if (existing.size() >= MAX_SSH_PUBLIC_KEYS_PER_USER) { + throw new AwsException("LimitExceeded", + "Cannot exceed quota for SSHPublicKeysPerUser: " + + MAX_SSH_PUBLIC_KEYS_PER_USER, 409); + } + // DuplicateSSHPublicKey is per user, not account-wide: "already associated with the + // specified IAM user". Compared on the fingerprint, so the same key in the other + // encoding is still the same key. + if (existing.stream().anyMatch(k -> fingerprint.equals(k.getFingerprint()))) { + // 400, not 409. DuplicateCertificate next door is 409, but the model gives + // DuplicateSSHPublicKey a 400, so the neighbouring pattern is the wrong guide. + throw new AwsException("DuplicateSSHPublicKey", + "The SSH public key is already associated with the specified IAM user.", + 400); + } + SshPublicKey stored = new SshPublicKey(); + stored.setUserName(userName); + stored.setSshPublicKeyId("APKA" + randomId(SSH_PUBLIC_KEY_ID_SUFFIX_LENGTH)); + stored.setFingerprint(fingerprint); + stored.setSshPublicKeyBody(body); + stored.setStatus(CREDENTIAL_STATUS_ACTIVE); + stored.setUploadDate(Instant.now()); + sshPublicKeys.put(stored.getSshPublicKeyId(), stored); + LOG.infov("Uploaded SSH public key {0} for user {1}", + stored.getSshPublicKeyId(), userName); + return stored; + } + } + + /** + * The key in the requested encoding. {@code Encoding} is required and is one of SSH or PEM, so + * a stored PEM key asked for as SSH is converted, and the other way round. + */ + public SshPublicKey getSshPublicKey(String userName, String keyId, String encoding) { + if (encoding == null || !SSH_PUBLIC_KEY_ENCODINGS.contains(encoding)) { + throw new AwsException("UnrecognizedPublicKeyEncoding", + "The public key encoding format is unsupported or unrecognized.", 400); + } + synchronized (sshPublicKeyLock) { + SshPublicKey stored = userSshPublicKey(userName, keyId); + String body = stored.getSshPublicKeyBody(); + boolean storedAsPem = SshPublicKeys.looksLikePem(body); + boolean wantPem = "PEM".equals(encoding); + // Returned unchanged when the encoding already matches, so a body is only ever + // rewritten to answer a request for the other form. Re-encoding it anyway would drop + // an OpenSSH line's trailing comment and re-wrap a caller's PEM. + String wanted = storedAsPem == wantPem + ? body + : convertSshPublicKey(body, wantPem); + // A copy, so re-encoding for one reader never rewrites what is stored. + SshPublicKey view = new SshPublicKey(); + view.setUserName(stored.getUserName()); + view.setSshPublicKeyId(stored.getSshPublicKeyId()); + view.setFingerprint(stored.getFingerprint()); + view.setSshPublicKeyBody(wanted); + view.setStatus(stored.getStatus()); + view.setUploadDate(stored.getUploadDate()); + return view; + } + } + + public List listSshPublicKeys(String userName) { + getUser(userName); // validates existence + return userSshPublicKeys(userName); + } + + public void updateSshPublicKey(String userName, String keyId, String status) { + if (status == null || !CREDENTIAL_STATUSES.contains(status)) { + throw new AwsException("ValidationError", + "Value '" + status + "' at 'status' failed to satisfy constraint: Member must " + + "satisfy enum value set: [" + String.join(", ", + CREDENTIAL_STATUSES) + "]", 400); + } + synchronized (sshPublicKeyLock) { + SshPublicKey stored = userSshPublicKey(userName, keyId); + stored.setStatus(status); + sshPublicKeys.put(stored.getSshPublicKeyId(), stored); + } + } + + public void deleteSshPublicKey(String userName, String keyId) { + synchronized (sshPublicKeyLock) { + SshPublicKey stored = userSshPublicKey(userName, keyId); + sshPublicKeys.delete(stored.getSshPublicKeyId()); + } + } + + /** The key re-encoded into the other accepted form. */ + private String convertSshPublicKey(String body, boolean toPem) { + RSAPublicKey key = readSshPublicKey(body); + return toPem ? SshPublicKeys.toPem(key) : SshPublicKeys.toOpenSsh(key); + } + + /** + * Reads either accepted encoding. The distinction the model draws is between an encoding it + * does not recognise and material in a recognised encoding that will not parse. + */ + private RSAPublicKey readSshPublicKey(String body) { + boolean pem = SshPublicKeys.looksLikePem(body); + // An OpenSSH line is recognised by its key-type token, not by whether something in it + // base64-decodes: splitting on whitespace and trying the second field would call any two + // words an OpenSSH key, because a short word is often valid base64. + boolean openSsh = !pem && !SshPublicKeys.opensAsPem(body) + && body.stripLeading().startsWith("ssh-"); + if (!pem && !openSsh) { + throw new AwsException("UnrecognizedPublicKeyEncoding", + "The public key encoding format is unsupported or unrecognized.", 400); + } + try { + if (pem) { + return SshPublicKeys.fromPem(body); + } + byte[] blob = SshPublicKeys.decodeBlob(body); + // The line's label has to agree with the type inside the blob, and rsaKeyOf only + // checks the blob. Without this, a line labelled ssh-ed25519 wrapped around a genuine + // ssh-rsa blob is accepted and stored under that label, and because the uploaded body + // is preserved, GetSSHPublicKey then hands the wrong label back to every reader. + String label = body.stripLeading().split("\\s+")[0]; + String blobType = SshPublicKeys.keyType(blob); + if (!label.equals(blobType)) { + throw new SshPublicKeyException( + "the line is labelled " + label + " but the blob declares " + blobType); + } + // A key type other than ssh-rsa reaches rsaKeyOf and fails there: the encoding was + // recognised, so what is wrong is the key, which is the error the model separates. + return SshPublicKeys.rsaKeyOf(blob); + } catch (SshPublicKeyException | NumberFormatException e) { + LOG.debugv("Rejected an unreadable SSH public key: {0}", e.getMessage()); + throw new AwsException("InvalidPublicKey", + "The public key is malformed or otherwise invalid.", 400); + } + } + + /** A key of that id belonging to that user, reported as missing when it belongs to another. */ + private SshPublicKey userSshPublicKey(String userName, String keyId) { + getUser(userName); // validates existence + SshPublicKey stored = sshPublicKeys.get(keyId) + .orElseThrow(() -> new AwsException("NoSuchEntity", + "The SSH Public Key with id " + keyId + " cannot be found.", 404)); + if (!userName.equals(stored.getUserName())) { + throw new AwsException("NoSuchEntity", + "The SSH Public Key with id " + keyId + " cannot be found.", 404); + } + return stored; + } + + private List userSshPublicKeys(String userName) { + return sshPublicKeys.scan(key -> true).stream() + .filter(k -> userName.equals(k.getUserName())) + .sorted(Comparator.comparing(SshPublicKey::getSshPublicKeyId)) + .toList(); + } + // Virtual MFA devices // ========================================================================= @@ -4039,7 +4256,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } private String signingCertificateActiveField(SigningCertificate certificate) { - return certificate != null && SIGNING_CERTIFICATE_ACTIVE.equals(certificate.getStatus()) + return certificate != null && CREDENTIAL_STATUS_ACTIVE.equals(certificate.getStatus()) ? "TRUE" : "FALSE"; } @@ -4053,7 +4270,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { */ private String signingCertificateRotatedField(SigningCertificate certificate) { return certificate != null - && SIGNING_CERTIFICATE_ACTIVE.equals(certificate.getStatus()) + && CREDENTIAL_STATUS_ACTIVE.equals(certificate.getStatus()) ? isoDate(certificate.getUploadDate()) : "N/A"; } diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/SshPublicKey.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/SshPublicKey.java new file mode 100644 index 0000000000..097ed169b0 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/SshPublicKey.java @@ -0,0 +1,46 @@ +package io.github.hectorvent.floci.services.iam.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** + * An SSH public key owned by one IAM user, which AWS accepts for authenticating that user to a + * CodeCommit repository. + * + *

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 requestContextFor(AtomicReference accountId) { + RequestContext rc = mock(RequestContext.class); + when(rc.getAccountId()).thenAnswer(invocation -> accountId.get()); + Instance inst = mock(Instance.class); + when(inst.get()).thenReturn(rc); + return inst; + } + + private static IamService newService(StorageBackend 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 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 second = + new PersistentStorage<>(file, new TypeReference<>() {}); + second.load(); + IamService after = newService(second, ACCOUNT_A); + after.createUser("restart-user", "/"); + List 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 account = new AtomicReference<>(ACCOUNT_A); + AccountAwareStorageBackend 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 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 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 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 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"); + } + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java index 7c64ddcae2..00ebd19c24 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java @@ -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()); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java index c04922818a..4e3b8c61ac 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java @@ -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); }