diff --git a/compatibility-tests/sdk-test-awscli/test/payment-cryptography-control-plane.bats b/compatibility-tests/sdk-test-awscli/test/payment-cryptography-control-plane.bats index 6e2e17d245..96e211b42e 100644 --- a/compatibility-tests/sdk-test-awscli/test/payment-cryptography-control-plane.bats +++ b/compatibility-tests/sdk-test-awscli/test/payment-cryptography-control-plane.bats @@ -191,3 +191,24 @@ create_key() { assert_success [ "$(json_get "$output" '.MpaTeamAssociation.AssociationState')" = "DELETE_PENDING" ] } + +@test "Payment Cryptography control plane: a key pair signs a certificate signing request" { + PAIR_ARN=$(aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=RSA_2048,KeyClass=ASYMMETRIC_KEY_PAIR,KeyUsage=TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE,KeyModesOfUse={Sign=true,Verify=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text) + [ -n "$PAIR_ARN" ] + + run aws_cmd payment-cryptography get-certificate-signing-request \ + --key-identifier "$PAIR_ARN" \ + --signing-algorithm SHA256 \ + --certificate-subject 'CommonName=floci payment cryptography,Organization=Floci' + assert_success + + # The answer is the PEM of the request, base64 encoded, as the reference's own answer + # carries it, so it is decoded before it is read. + local encoded + encoded=$(json_get "$output" '.CertificateSigningRequest') + [[ -n "$encoded" ]] + [[ "$(printf '%s' "$encoded" | base64 -d)" == *"BEGIN CERTIFICATE REQUEST"* ]] +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java index 963624c00a..292c301f3f 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java @@ -41,12 +41,14 @@ import software.amazon.awssdk.services.paymentcryptography.model.MultiRegionKeyT import software.amazon.awssdk.services.paymentcryptography.model.PublicPolicyException; import software.amazon.awssdk.services.paymentcryptography.model.RemoveKeyReplicationRegionsResponse; import software.amazon.awssdk.services.paymentcryptography.model.ResourceNotFoundException; +import software.amazon.awssdk.services.paymentcryptography.model.SigningAlgorithmType; import software.amazon.awssdk.services.paymentcryptography.model.Tag; import software.amazon.awssdk.services.paymentcryptography.model.Tr34KeyBlockFormat; import software.amazon.awssdk.services.paymentcryptography.model.WrappedKeyMaterialFormat; import java.io.ByteArrayInputStream; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.cert.CertificateFactory; @@ -313,6 +315,26 @@ class PaymentCryptographyTest { return key; } + /** + * A key pair that may sign, for the operations that ask a certificate authority for a + * certificate. + * + * @param algorithm the key pair's algorithm + * @return the key pair + */ + private static Key createSigningKeyPair(KeyAlgorithm algorithm) { + Key key = client.createKey(r -> r + .keyAttributes(a -> a + .keyAlgorithm(algorithm) + .keyClass(KeyClass.ASYMMETRIC_KEY_PAIR) + .keyUsage(KeyUsage.TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE) + .keyModesOfUse(m -> m.sign(true).verify(true))) + .exportable(true)) + .key(); + keyArns.add(key.keyArn()); + return key; + } + /** A key of the given algorithm, for the data the cipher protects. */ private static Key createKey(KeyAlgorithm algorithm) { return createKey(algorithm, KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY); @@ -424,6 +446,36 @@ class PaymentCryptographyTest { return arn.substring(arn.lastIndexOf('/') + 1); } + @Test + void aKeyPairSignsACertificateSigningRequest() { + Key pair = createSigningKeyPair(KeyAlgorithm.RSA_2048); + + String request = client.getCertificateSigningRequest(r -> r + .keyIdentifier(pair.keyArn()) + .signingAlgorithm(SigningAlgorithmType.SHA256) + .certificateSubject(s -> s + .commonName("floci payment cryptography") + .organization("Floci"))) + .certificateSigningRequest(); + + // The answer is the PEM of the request, base64 encoded, as the reference's own + // answer carries it. + String pem = new String(Base64.getDecoder().decode(request), StandardCharsets.US_ASCII); + assertThat(pem).startsWith("-----BEGIN CERTIFICATE REQUEST-----"); + assertThat(pem.trim()).endsWith("-----END CERTIFICATE REQUEST-----"); + } + + @Test + void aKeyThatIsNotAKeyPairSignsNoRequest() { + // A key that is not a key pair has no public half to certify. + Key key = createAesKey(); + + assertRefusedWithValidationException(() -> client.getCertificateSigningRequest(r -> r + .keyIdentifier(key.keyArn()) + .signingAlgorithm(SigningAlgorithmType.SHA256) + .certificateSubject(s -> s.commonName("floci"))), "not a key pair"); + } + @Test void aMultiPartyApprovalTeamIsAssociatedReadAndRemoved() { // The team's ARN is kept as the request names it: the emulator has no Multi-Party @@ -885,15 +937,7 @@ class PaymentCryptographyTest { @Test void aPublicKeyCertificateIsServedForAKeyPair() throws Exception { // The certificate of a key pair is how the pair is handed to a counterparty. - Key key = client.createKey(r -> r - .keyAttributes(a -> a - .keyAlgorithm(KeyAlgorithm.ECC_NIST_P256) - .keyClass(KeyClass.ASYMMETRIC_KEY_PAIR) - .keyUsage(KeyUsage.TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE) - .keyModesOfUse(m -> m.sign(true).verify(true))) - .exportable(true)) - .key(); - keyArns.add(key.keyArn()); + Key key = createSigningKeyPair(KeyAlgorithm.ECC_NIST_P256); GetPublicKeyCertificateResponse certificate = client.getPublicKeyCertificate(r -> r .keyIdentifier(key.keyArn())); diff --git a/docs/services/index.md b/docs/services/index.md index e6514cc1de..64670b9c4d 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -34,7 +34,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [CloudHSM v2](cloudhsmv2.md) | `POST /` + `X-Amz-Target: BaldrApiService.*` | JSON 1.1 | 18 | | [Kinesis](kinesis.md) | `POST /` + `X-Amz-Target: Kinesis_20131202.*` | JSON 1.1 | 32 | | [Managed Service for Apache Flink](kinesisanalytics.md) | `POST /` + `X-Amz-Target: KinesisAnalytics_20180523.*` | JSON 1.1 | 15 | -| [Payment Cryptography](payment-cryptography.md) | `POST /` + `X-Amz-Target: PaymentCryptographyControlPlane.*` | JSON 1.0 | 31 | +| [Payment Cryptography](payment-cryptography.md) | `POST /` + `X-Amz-Target: PaymentCryptographyControlPlane.*` | JSON 1.0 | 32 | | [Payment Cryptography data plane](payment-cryptography-data.md) | `POST /keys/{KeyIdentifier}/encrypt` and the rest | REST JSON | 12 | | [Secrets Manager](secrets-manager.md) | `POST /` + `X-Amz-Target: secretsmanager.*` | JSON 1.1 | 23 | | [Step Functions](step-functions.md) | `POST /` + `X-Amz-Target: AmazonStatesService.*` | JSON 1.1 | 32 | diff --git a/docs/services/payment-cryptography.md b/docs/services/payment-cryptography.md index c98e6c236f..17e795230f 100644 --- a/docs/services/payment-cryptography.md +++ b/docs/services/payment-cryptography.md @@ -30,6 +30,7 @@ | `GetDefaultKeyReplicationRegions` | The Regions the account replicates a new key to | | `EnableDefaultKeyReplicationRegions` | Replicate every new key to the Regions named | | `DisableDefaultKeyReplicationRegions` | Stop replicating every new key to the Regions named | +| `GetCertificateSigningRequest` | The certificate signing request a key pair signs | | `TagResource` | Add tags to a key | | `UntagResource` | Remove tags from a key | | `ListTagsForResource` | List the tags of a key | @@ -288,7 +289,29 @@ to start or stop: the reference does not publish the answer for that case, so the request is refused with `ConflictException`, which is the code the service uses for a request that conflicts with the state of a key. -- **Not yet emulated:** the certificate signing request. +- **The certificate signing request of a key pair:** `GetCertificateSigningRequest` answers + with a request the key pair signs, over the subject the request names and with the digest + it names. The answer is the PEM of the request, base64 encoded, which is what the + reference's own answer carries, so a caller that decodes it holds the file the + `-----BEGIN CERTIFICATE REQUEST-----` and `-----END CERTIFICATE REQUEST-----` markers are + in. The key has to be a key pair the service holds the private half of: a key that is not + a key pair has no public half to certify, a key pair the service holds no private half of + has nothing to sign with, and a key that is disabled does no work. The reference + publishes no table of the keys this operation takes, so the rules here are this service's + own: the usage and the mode of use of the key are not narrowed, and the reference's own + flows are both served, the one that signs with a key pair of the digital signature usage + whose mode of use is `Sign` and the one that signs with a key pair of the TR-34 usage + whose modes of use are `Unwrap` and `Decrypt`. The signature algorithm is the one the + key's own algorithm gives with that digest, so an RSA key signs with an RSA algorithm and + an elliptic curve one with an ECDSA algorithm. The subject's members are written in the + order the reference's own request writes them, the most general member first: the + country, the state or province, the city, the organization, the organization unit, the + common name and the email address. The email address is written as an IA5String, which + holds ASCII alone, so an address with a character outside ASCII is refused with + `ValidationException` rather than signed with that character narrowed to a byte. The + model settles what the request may name: the digest is one of the four it names and the + subject carries a common name, so a request that names another digest or leaves the + common name out is refused with `ValidationException` by the model's own check. ## Configuration @@ -318,4 +341,4 @@ aws payment-cryptography tag-resource \ # Read it back aws payment-cryptography get-key --key-identifier "$KEY_ARN" -``` +``` \ No newline at end of file diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCertificateRequest.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCertificateRequest.java new file mode 100644 index 0000000000..d7d357470f --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCertificateRequest.java @@ -0,0 +1,162 @@ +package io.floci.aws.services.paymentcryptography; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.paymentcryptography.crypto.Certificates; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x500.X500NameBuilder; +import org.bouncycastle.asn1.x500.style.BCStyle; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.operator.ContentSigner; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder; + +import java.io.IOException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * The certificate signing request a key pair signs. + * + *
The request is a PKCS#10 one: the subject and the public half of the key, signed by the + * private half. The digest is the one the request names, and the signature algorithm is the + * one the key's own algorithm gives with that digest, so an RSA key signs with an RSA + * algorithm and an elliptic curve one with an ECDSA algorithm. + */ +final class PaymentCryptographyCertificateRequest { + + /** + * The subject's members, and the attribute each is written as. + * + *
The order is the one the reference's own request carries, most general member
+ * first, so the subject of two requests with the same members is the same subject. The
+ * reference's example reads {@code C=US, ST=Virginia, L=Arlington, O=Amazon,
+ * OU=PaymentCryptography, CN=MyCertificateAWSUSEAST}, which is the order the members
+ * are written in here.
+ */
+ private static final Map A value outside ASCII cannot be written as such an attribute, and the encoder would
+ * narrow it to a byte of its own, so the request would carry an address the caller did
+ * not name. A request that names one is refused instead.
+ */
+ private static final Set A member the request does not name is not in the subject, and the one it does
+ * require, the common name, is. A member whose attribute cannot hold the value the
+ * request names is refused, because the request would otherwise carry a value the
+ * caller never wrote.
+ *
+ * @param fields the subject's members
+ * @return the subject
+ */
+ static X500Name subject(Map The digest names the digest of the signature algorithm, and the key's own
+ * algorithm gives the rest, so a SHA256 digest signs with a SHA256withRSA algorithm
+ * for an RSA key and with a SHA256withECDSA one for an elliptic curve key. The model
+ * settles the digest, so the four the model names are the four that arrive.
+ *
+ * @param digest the digest the request names
+ * @param rsa whether the key pair is an RSA one
+ * @return the signature algorithm
+ */
+ private static String algorithm(String digest, boolean rsa) {
+ return digest + "with" + (rsa ? "RSA" : "ECDSA");
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyJsonHandler.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyJsonHandler.java
index a46a71f53b..c891e27c9f 100644
--- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyJsonHandler.java
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyJsonHandler.java
@@ -84,6 +84,7 @@ public class PaymentCryptographyJsonHandler {
case "GetDefaultKeyReplicationRegions" -> () -> getDefaultKeyReplicationRegions(request, region);
case "EnableDefaultKeyReplicationRegions" -> () -> enableDefaultKeyReplicationRegions(request, region);
case "DisableDefaultKeyReplicationRegions" -> () -> disableDefaultKeyReplicationRegions(request, region);
+ case "GetCertificateSigningRequest" -> () -> getCertificateSigningRequest(request, region);
case "TagResource" -> () -> tagResource(request, region);
case "UntagResource" -> () -> untagResource(request, region);
case "ListTagsForResource" -> () -> listTagsForResource(request, region);
@@ -544,6 +545,35 @@ public class PaymentCryptographyJsonHandler {
return tags;
}
+ // ---- certificate signing requests ----------------------------------------
+
+ /**
+ * The certificate signing request a key pair signs.
+ *
+ * The subject is the metadata the request names, and the digest is the one the request
+ * names, so the request is the one the caller asked for. The answer carries the PEM of
+ * the request, base64 encoded, as the reference's own answer carries it.
+ */
+ private Map The request carries the subject and the public half of the key, and it is signed by
+ * the private half, so the key has to be a key pair the service holds the private half
+ * of: a key that is not a key pair has no public half to certify, and a key pair the
+ * service holds no private half of has nothing to sign with. A key that is disabled does
+ * no work.
+ *
+ * The usage and the mode of use of the key are not narrowed. The reference publishes
+ * no table of the keys this operation takes, and its own flows are two: one signs with a
+ * key pair of the digital signature usage whose mode of use is {@code Sign}, the other
+ * with a key pair of the TR-34 usage whose modes of use are {@code Unwrap} and
+ * {@code Decrypt}. Both are served here.
+ *
+ * The answer is the PEM of the request, base64 encoded, which is what the reference's
+ * own answer carries, so a caller that decodes it holds the file the markers are in.
+ *
+ * @param key the key pair that signs
+ * @param digest the digest the request names
+ * @param subject the subject's members
+ * @return the request, base64 encoded
+ */
+ public synchronized String certificateSigningRequest(PaymentCryptographyKey key, String digest,
+ Map The key record knows its algorithm, so the family is read from there and not guessed
+ * from the length of the material, because the two key pairs are of different lengths and
+ * the algorithm is what a certificate names.
+ */
+ static boolean isRsa(PaymentCryptographyKey key) {
+ PaymentCryptographyKeyAlgorithm algorithm =
+ PaymentCryptographyKeyAlgorithm.from(key.getKeyAlgorithm());
+ return algorithm != null && algorithm.rsa;
+ }
+
/**
* Whether a key is an AES key rather than a TDES one.
*
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Certificates.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Certificates.java
index 065477f7e8..f8083789e3 100644
--- a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Certificates.java
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Certificates.java
@@ -22,7 +22,8 @@ import java.util.Base64;
*
* The service gives a counterparty a certificate over a key pair it made for the occasion,
* and reads the certificate a counterparty brings. A certificate travels in three shapes: PEM,
- * base64 of PEM (which is how the service returns one), and base64 of DER.
+ * base64 of PEM (which is how the service returns one), and base64 of DER. The PEM of a
+ * certificate signing request is written here too, under its own label.
*
* Reading a certificate is the emulator's own business, through {@link Pem}; minting one
* belongs to ACM's generator, which the service asks for a certificate with.
@@ -121,17 +122,18 @@ public final class Certificates {
}
/**
- * Wrap DER as a PEM document.
+ * Wrap DER as a PEM document of the given label.
*
- * @param der the certificate in DER
- * @return the certificate in PEM
+ * @param label the label the document carries, such as {@code CERTIFICATE}
+ * @param der the document in DER
+ * @return the document in PEM
*/
- public static String toPem(byte[] der) {
+ public static String toPem(String label, byte[] der) {
StringWriter writer = new StringWriter();
try (JcaPEMWriter pemWriter = new JcaPEMWriter(writer)) {
- pemWriter.writeObject(new PemObject("CERTIFICATE", der));
+ pemWriter.writeObject(new PemObject(label, der));
} catch (IOException e) {
- throw new IllegalStateException("cannot write the certificate as PEM", e);
+ throw new IllegalStateException("cannot write the document as PEM", e);
}
return writer.toString();
}
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java
index 91a526f169..eb23db8555 100644
--- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java
@@ -12,7 +12,9 @@ import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
+import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -34,6 +36,7 @@ import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class PaymentCryptographyIntegrationTest {
@@ -611,6 +614,99 @@ class PaymentCryptographyIntegrationTest {
.body("message", containsString("ReplicationRegions"));
}
+
+ @Test
+ void aKeyPairSignsACertificateSigningRequest() {
+ String arn = call("CreateKey", CREATE_KEY_PAIR)
+ .then().statusCode(200)
+ .extract().path("Key.KeyArn");
+ cleanup.register(() -> call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\"}"));
+
+ // The answer is the PEM of the request, base64 encoded, as the reference's own
+ // answer carries it.
+ String answer = call("GetCertificateSigningRequest", """
+ {"KeyIdentifier":"%s","SigningAlgorithm":"SHA256",
+ "CertificateSubject":{"CommonName":"floci payment cryptography",
+ "Organization":"Floci"}}""".formatted(arn))
+ .then().statusCode(200)
+ .extract().path("CertificateSigningRequest");
+
+ String pem = new String(Base64.getDecoder().decode(answer), StandardCharsets.US_ASCII);
+ assertTrue(pem.startsWith("-----BEGIN CERTIFICATE REQUEST-----"), pem);
+ assertTrue(pem.trim().endsWith("-----END CERTIFICATE REQUEST-----"), pem);
+ }
+
+ @Test
+ void aKeyPairOfTheTr34UsageSignsACertificateSigningRequest() {
+ // The reference's own import flow signs the request with a key pair of the TR-34
+ // usage, whose modes of use are unwrapping and decrypting, so the mode of use of
+ // the key does not narrow the operation.
+ String arn = call("CreateKey", """
+ {"KeyAttributes":{"KeyAlgorithm":"RSA_2048","KeyClass":"ASYMMETRIC_KEY_PAIR",
+ "KeyUsage":"TR31_K2_TR34_ASYMMETRIC_KEY",
+ "KeyModesOfUse":{"Unwrap":true,"Decrypt":true}},
+ "Exportable":true}""")
+ .then().statusCode(200)
+ .extract().path("Key.KeyArn");
+ cleanup.register(() -> call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\"}"));
+
+ call("GetCertificateSigningRequest", """
+ {"KeyIdentifier":"%s","SigningAlgorithm":"SHA512",
+ "CertificateSubject":{"CommonName":"MyImportKRDCertAWSUSEAST"}}""".formatted(arn))
+ .then().statusCode(200)
+ .body("CertificateSigningRequest", notNullValue());
+ }
+
+ @Test
+ void aKeyThatIsNotThereSignsNoRequest() {
+ call("GetCertificateSigningRequest", """
+ {"KeyIdentifier":"arn:aws:payment-cryptography:us-east-1:000000000000:key/abcdefghijklmnop",
+ "SigningAlgorithm":"SHA256",
+ "CertificateSubject":{"CommonName":"floci"}}""")
+ .then().statusCode(400)
+ .body("__type", containsString("ResourceNotFoundException"));
+ }
+
+ @Test
+ void aKeyThatIsPendingDeletionSignsNoRequest() {
+ // The deletion disables the key, and a disabled key does no work.
+ String arn = keyArn();
+ cleanup.register(() -> call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\"}"));
+ call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\"}").then().statusCode(200);
+
+ call("GetCertificateSigningRequest", """
+ {"KeyIdentifier":"%s","SigningAlgorithm":"SHA256",
+ "CertificateSubject":{"CommonName":"floci"}}""".formatted(arn))
+ .then().statusCode(400)
+ .body("__type", containsString("ValidationException"));
+ }
+
+ @Test
+ void theModelCheckRefusesASigningAlgorithmTheModelDoesNotName() {
+ // The model names the digests, so the service does not check them again.
+ String arn = keyArn();
+ cleanup.register(() -> call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\"}"));
+
+ Response answer = call("GetCertificateSigningRequest", """
+ {"KeyIdentifier":"%s","SigningAlgorithm":"SHA1",
+ "CertificateSubject":{"CommonName":"floci"}}""".formatted(arn));
+
+ assertTheModelRefused(answer, "SigningAlgorithm");
+ }
+
+ @Test
+ void theModelCheckRefusesASubjectWithoutACommonName() {
+ // The model requires the common name of the subject.
+ String arn = keyArn();
+ cleanup.register(() -> call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\"}"));
+
+ Response answer = call("GetCertificateSigningRequest", """
+ {"KeyIdentifier":"%s","SigningAlgorithm":"SHA256",
+ "CertificateSubject":{"Organization":"Floci"}}""".formatted(arn));
+
+ assertTheModelRefused(answer, "CommonName");
+ }
+
@Test
void aMultiPartyApprovalTeamIsAssociatedReadAndRemoved() {
// The team's ARN is kept as the request names it: the emulator has no Multi-Party
@@ -1043,21 +1139,6 @@ class PaymentCryptographyIntegrationTest {
.body("__type", containsString("UnknownOperationException"));
}
- @Test
- void anOperationTheServiceDoesNotServeIsRefusedWhateverItsBodySays() {
- // The model names the operation and the service does not serve it, so it is refused
- // as the unknown operation it is. The body it carries does not change that: a body
- // that breaks the model's rules is not the answer to an operation that is not
- // served at all.
- call("GetCertificateSigningRequest", "{}")
- .then().statusCode(400)
- .body("__type", containsString("UnknownOperationException"));
- call("GetCertificateSigningRequest", "{\"KeyIdentifier\":\"arn:aws:payment-cryptography:"
- + "us-east-1:000000000000:key/abcdefghijklmnop\"}")
- .then().statusCode(400)
- .body("__type", containsString("UnknownOperationException"));
- }
-
@Test
void theCertificateOfAKeyIsServedOverTheWire() {
// The certificate of an asymmetric key, with the chain that goes with it.
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java
index 610c274f6e..8da2f9be6c 100644
--- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java
@@ -9,16 +9,25 @@ import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyAlias;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyMpaTeamAssociation;
import io.floci.aws.testing.ManualClock;
+import org.bouncycastle.asn1.ASN1ObjectIdentifier;
+import org.bouncycastle.asn1.x500.RDN;
+import org.bouncycastle.asn1.x500.style.BCStyle;
+import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
+import java.security.Signature;
import java.time.Duration;
import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Base64;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
@@ -31,6 +40,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@@ -1821,6 +1831,215 @@ class PaymentCryptographyServiceTest {
assertEquals("ResourceNotFoundException", refused.getErrorCode());
}
+ /** The subject of a certificate signing request, for the tests that need one. */
+ private static final Map The subject is the one the request named, the request carries the public half of
+ * the key that signed it, and the signature verifies under that half, so the request is
+ * the one the key signed and a certificate authority can verify it against the key it
+ * carries.
+ */
+ private static void assertCertificateSigningRequestVerifies(String answer,
+ PaymentCryptographyKey pair,
+ String digest) {
+ try {
+ PKCS10CertificationRequest request = requestOf(answer);
+ assertTrue(request.getSubject().toString().contains("Floci"),
+ request.getSubject().toString());
+ assertArrayEquals(PaymentCryptographyKeyExchange.publicKeyOf(pair).getEncoded(),
+ request.getSubjectPublicKeyInfo().getEncoded(),
+ "the request carries a public key that is not the key that signed it");
+ String algorithm = digest + (pair.getKeyAlgorithm().startsWith("ECC")
+ ? "withECDSA" : "withRSA");
+ Signature verifier = Signature.getInstance(algorithm);
+ verifier.initVerify(PaymentCryptographyKeyExchange.publicKeyOf(pair));
+ verifier.update(request.toASN1Structure().getCertificationRequestInfo().getEncoded());
+ assertTrue(verifier.verify(request.getSignature()),
+ "the signature of the request does not verify");
+ } catch (GeneralSecurityException | IOException e) {
+ throw new AssertionError("the certificate signing request does not parse", e);
+ }
+ }
+
+ /**
+ * The attributes of the subject of a request, in the order they are written in.
+ *
+ * @param answer the base64 encoded request
+ * @return the attribute of every member of the subject
+ */
+ private static List The PEM is the answer the service gives, base64 encoded, so it is decoded and the
+ * markers are taken off before the request itself is read.
+ *
+ * @param pem the request, in PEM
+ * @return the request
+ */
+ private static PKCS10CertificationRequest requestOf(String answer) {
+ byte[] der = Base64.getMimeDecoder().decode(pemOf(answer).replaceAll("-----[A-Z ]+-----", ""));
+ try {
+ return new PKCS10CertificationRequest(der);
+ } catch (IOException e) {
+ throw new AssertionError("the certificate signing request does not parse", e);
+ }
+ }
+
+ /**
+ * The PEM the answer carries, decoded.
+ *
+ * @param answer the base64 encoded request
+ * @return the request, in PEM
+ */
+ private static String pemOf(String answer) {
+ return new String(Base64.getDecoder().decode(answer), StandardCharsets.US_ASCII);
+ }
+
+ /**
+ * A key pair that may sign, for the request's tests.
+ *
+ * @param algorithm the key pair's algorithm
+ * @param usage the key pair's usage
+ * @param modes the key pair's modes of use
+ * @return the key pair
+ */
+ private PaymentCryptographyKey signingKeyPair(String algorithm, String usage,
+ Map