feat(paymentcryptography): a key pair signs a certificate signing request (#8832)

This commit is contained in:
Murtuza Chhil authored and GitHub committed 2026-11-18 13:35:25 -04:00
1 parent 8b7d06a9d1
commit 3f3625359a
12 files changed
+686 -45

No files matched your search

@@ -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"* ]]
}
@@ -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()));
+1 -1
View File
@@ -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 |
+25 -2
View File
@@ -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"
```
```
@@ -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.
*
* <p>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.
*
* <p>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<String, ASN1ObjectIdentifier> SUBJECT_TYPES = subjectTypes();
/**
* The members whose attribute holds an IA5String, which is ASCII alone.
*
* <p>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<String> IA5_MEMBERS = Set.of("EmailAddress");
private PaymentCryptographyCertificateRequest() {
}
private static Map<String, ASN1ObjectIdentifier> subjectTypes() {
Map<String, ASN1ObjectIdentifier> types = new LinkedHashMap<>();
types.put("Country", BCStyle.C);
types.put("StateOrProvince", BCStyle.ST);
types.put("City", BCStyle.L);
types.put("Organization", BCStyle.O);
types.put("OrganizationUnit", BCStyle.OU);
types.put("CommonName", BCStyle.CN);
types.put("EmailAddress", BCStyle.E);
return types;
}
/**
* The subject of the request, as the members the model names.
*
* <p>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<String, String> fields) {
X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
for (Map.Entry<String, ASN1ObjectIdentifier> entry : SUBJECT_TYPES.entrySet()) {
String value = fields.get(entry.getKey());
if (value != null && !value.isEmpty()) {
requireAscii(entry.getKey(), value);
builder.addRDN(entry.getValue(), value);
}
}
return builder.build();
}
/**
* The refusal of a value the attribute of a member cannot hold.
*
* @param member the member of the subject
* @param value the value the request names
*/
private static void requireAscii(String member, String value) {
if (!IA5_MEMBERS.contains(member)) {
return;
}
for (int index = 0; index < value.length(); index++) {
if (value.charAt(index) > 127) {
throw new AwsException("ValidationException",
"the " + member + " of the subject holds a character that is not ASCII, "
+ "and the attribute it is written as holds ASCII alone", 400);
}
}
}
/**
* The request, in PEM.
*
* @param subject the subject of the request
* @param publicKey the public half of the key pair
* @param privateKey the private half of the key pair
* @param digest the digest the request names
* @param rsa whether the key pair is an RSA one
* @return the request, in PEM
*/
static String pem(X500Name subject, PublicKey publicKey, PrivateKey privateKey,
String digest, boolean rsa) {
String algorithm = algorithm(digest, rsa);
try {
ContentSigner signer = new JcaContentSignerBuilder(algorithm).build(privateKey);
// The request carries the public half in the form a certificate names it, which
// is the encoded form of the key.
SubjectPublicKeyInfo publicKeyInfo =
SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
byte[] encoded = new PKCS10CertificationRequestBuilder(subject, publicKeyInfo)
.build(signer).getEncoded();
return Certificates.toPem("CERTIFICATE REQUEST", encoded);
} catch (OperatorCreationException | IOException e) {
throw new AwsException("ValidationException",
"the certificate signing request could not be signed: " + e.getMessage(), 400);
}
}
/**
* The members of the subject, as the model names them.
*
* @return the members, in the order the subject is written in
*/
static List<String> subjectMembers() {
return List.copyOf(SUBJECT_TYPES.keySet());
}
/**
* The signature algorithm a digest names.
*
* <p>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");
}
}
@@ -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.
*
* <p>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<String, Object> getCertificateSigningRequest(JsonNode request, String region) {
PaymentCryptographyKey key = requiredKey(request, region, KEY_IDENTIFIER);
String signingRequest = service.certificateSigningRequest(key,
request.path("SigningAlgorithm").asText(),
subjectOf(request.path("CertificateSubject")));
return Map.of("CertificateSigningRequest", signingRequest);
}
/** The subject of a request, as the members the model names. */
private static Map<String, String> subjectOf(JsonNode subject) {
Map<String, String> fields = new LinkedHashMap<>();
for (String member : PaymentCryptographyCertificateRequest.subjectMembers()) {
JsonNode value = subject.get(member);
if (value != null && !value.isNull()) {
fields.put(member, value.asText());
}
}
return fields;
}
// ---- helpers ------------------------------------------------------------
/**
@@ -173,7 +173,7 @@ final class PaymentCryptographyKeyExchange {
X509Certificate certificate = certificates.signCertificate(subject, subjectPublicKey,
issuer, issuerPrivateKey, List.of(), false, null, notBefore, notAfter);
byte[] der = certificate.getEncoded();
return new Certificates.Minted(der, Certificates.toPem(der));
return new Certificates.Minted(der, Certificates.toPem("CERTIFICATE", der));
} catch (IOException e) {
throw new IllegalStateException("cannot mint a certificate", e);
} catch (Exception e) {
@@ -668,12 +668,7 @@ final class PaymentCryptographyKeyExchange {
/** The name the key factory knows the key's algorithm by. */
private static String keyFactoryAlgorithm(PaymentCryptographyKey key) {
PaymentCryptographyKeyAlgorithm algorithm =
PaymentCryptographyKeyAlgorithm.from(key.getKeyAlgorithm());
if (algorithm != null && algorithm.rsa) {
return "RSA";
}
return "EC";
return PaymentCryptographyService.isRsa(key) ? "RSA" : "EC";
}
/**
@@ -749,7 +744,7 @@ final class PaymentCryptographyKeyExchange {
private static String certificatePem(String certText) {
try {
X509Certificate certificate = Certificates.parseCertificate(certText);
return Certificates.toPem(certificate.getEncoded());
return Certificates.toPem("CERTIFICATE", certificate.getEncoded());
} catch (GeneralSecurityException | RuntimeException e) {
throw validation("the public key certificate is not a certificate: " + e.getMessage());
}
@@ -1131,7 +1126,8 @@ final class PaymentCryptographyKeyExchange {
/** The import parameters of an issued token, as the answer carries them. */
private static Map<String, Object> importParameters(Issued issued) {
String certificate64 = Certificates.pemBase64(Certificates.toPem(issued.certificateDer));
String certificate64 = Certificates.pemBase64(
Certificates.toPem("CERTIFICATE", issued.certificateDer));
Map<String, Object> out = new LinkedHashMap<>();
out.put("ImportToken", issued.token);
out.put("WrappingKeyCertificate", certificate64);
@@ -1190,7 +1186,8 @@ final class PaymentCryptographyKeyExchange {
/** The export parameters of an issued token, as the answer carries them. */
private static Map<String, Object> exportParameters(Issued issued) {
String certificate64 = Certificates.pemBase64(Certificates.toPem(issued.certificateDer));
String certificate64 = Certificates.pemBase64(
Certificates.toPem("CERTIFICATE", issued.certificateDer));
Map<String, Object> out = new LinkedHashMap<>();
out.put("ExportToken", issued.token);
out.put("SigningKeyCertificate", certificate64);
@@ -13,6 +13,7 @@ import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.acm.CertificateGenerator;
import io.floci.aws.services.paymentcryptography.crypto.Certificates;
import io.floci.aws.services.paymentcryptography.crypto.DukptCrypto;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyAlias;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
@@ -21,6 +22,8 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.time.Clock;
import java.util.ArrayList;
@@ -486,6 +489,52 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
return current;
}
// ---- certificate signing requests ----------------------------------------
/**
* The certificate signing request a key pair signs.
*
* <p>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.
*
* <p>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.
*
* <p>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<String, String> subject) {
PaymentCryptographyKey current = liveKey(key);
PaymentCryptographyKeyRules.requireEnabled(current);
if (!ASYMMETRIC_CLASS.equals(current.getKeyClass())) {
throw new AwsException("ValidationException",
"the key " + current.getArn() + " is not a key pair, and a key pair is what "
+ "signs a certificate signing request", 400);
}
PublicKey publicKey = PaymentCryptographyKeyExchange.publicKeyOf(current);
PrivateKey privateKey = PaymentCryptographyKeyExchange.privateKeyOf(current);
if (publicKey == null || privateKey == null) {
throw new AwsException("ValidationException",
"the key " + current.getArn() + " has no key pair to sign a certificate "
+ "signing request with", 400);
}
return Certificates.pemBase64(PaymentCryptographyCertificateRequest.pem(
PaymentCryptographyCertificateRequest.subject(subject), publicKey, privateKey,
digest, isRsa(current)));
}
// ---- aliases ------------------------------------------------------------
/**
@@ -1183,6 +1232,19 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
+ USAGE_NAMES.keySet(), 400);
}
/**
* Whether a key is an RSA key rather than an elliptic curve one.
*
* <p>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.
*
@@ -22,7 +22,8 @@ import java.util.Base64;
*
* <p>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.
*
* <p>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();
}
@@ -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.
@@ -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<String, String> CSR_SUBJECT = Map.of(
"CommonName", "floci payment cryptography",
"Organization", "Floci",
"Country", "IE");
@Test
void aKeyPairSignsACertificateSigningRequest() {
PaymentCryptographyKey pair = signingKeyPair("RSA_2048",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", Map.of("Sign", Boolean.TRUE));
String answer = service.certificateSigningRequest(pair, "SHA256", CSR_SUBJECT);
// The answer is the PEM of the request, base64 encoded, as the reference's own
// answer carries it.
String pem = pemOf(answer);
assertTrue(pem.startsWith("-----BEGIN CERTIFICATE REQUEST-----"), pem);
assertTrue(pem.trim().endsWith("-----END CERTIFICATE REQUEST-----"), pem);
assertCertificateSigningRequestVerifies(answer, pair, "SHA256");
}
@Test
void aKeyPairSignsACertificateSigningRequestWithSha224() {
// The model names four digests, and each of them signs.
PaymentCryptographyKey pair = signingKeyPair("RSA_2048",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", Map.of("Sign", Boolean.TRUE));
String answer = service.certificateSigningRequest(pair, "SHA224", CSR_SUBJECT);
assertCertificateSigningRequestVerifies(answer, pair, "SHA224");
}
@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.
PaymentCryptographyKey pair = signingKeyPair("RSA_2048", "TR31_K2_TR34_ASYMMETRIC_KEY",
Map.of("Unwrap", Boolean.TRUE, "Decrypt", Boolean.TRUE));
String answer = service.certificateSigningRequest(pair, "SHA512", CSR_SUBJECT);
assertCertificateSigningRequestVerifies(answer, pair, "SHA512");
}
@Test
void anEllipticCurveKeyPairSignsACertificateSigningRequest() {
PaymentCryptographyKey pair = signingKeyPair("ECC_NIST_P256",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", Map.of("Sign", Boolean.TRUE));
String answer = service.certificateSigningRequest(pair, "SHA384", CSR_SUBJECT);
assertCertificateSigningRequestVerifies(answer, pair, "SHA384");
}
@Test
void theSubjectIsWrittenInTheOrderTheReferenceWritesIt() {
// The reference's own request reads C=US, ST=Virginia, L=Arlington, O=Amazon,
// OU=PaymentCryptography, CN=MyCertificateAWSUSEAST, so the members of the subject
// are written most general one first.
PaymentCryptographyKey pair = signingKeyPair("RSA_2048",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", Map.of("Sign", Boolean.TRUE));
String answer = service.certificateSigningRequest(pair, "SHA256", Map.of(
"CommonName", "MyCertificateAWSUSEAST",
"Organization", "Amazon",
"OrganizationUnit", "PaymentCryptography",
"Country", "US",
"StateOrProvince", "Virginia",
"City", "Arlington"));
List<ASN1ObjectIdentifier> types = subjectTypesOf(answer);
assertEquals(List.of(BCStyle.C, BCStyle.ST, BCStyle.L, BCStyle.O, BCStyle.OU, BCStyle.CN),
types);
}
@Test
void theEmailAddressIsWrittenAsTheCallerNamedIt() {
PaymentCryptographyKey pair = signingKeyPair("RSA_2048",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", Map.of("Sign", Boolean.TRUE));
String answer = service.certificateSigningRequest(pair, "SHA256", Map.of(
"CommonName", "floci payment cryptography",
"EmailAddress", "team@example.com"));
String subject = requestOf(answer).getSubject().toString();
assertTrue(subject.contains("team@example.com"), subject);
}
@Test
void anEmailAddressTheAttributeCannotHoldIsRefused() {
// The email address is written as an IA5String, which holds ASCII alone, so an
// address outside ASCII is refused rather than signed with a narrowed character:
// the request would otherwise carry an address the caller never named.
PaymentCryptographyKey pair = signingKeyPair("RSA_2048",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", Map.of("Sign", Boolean.TRUE));
AwsException refused = assertThrows(AwsException.class,
() -> service.certificateSigningRequest(pair, "SHA256", Map.of(
"CommonName", "floci payment cryptography",
"EmailAddress", "a\u2019b@example.com")));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void aKeyThatIsNotAKeyPairSignsNoRequest() {
PaymentCryptographyKey key = createKey("us-east-1");
AwsException refused = assertThrows(AwsException.class,
() -> service.certificateSigningRequest(key, "SHA256", CSR_SUBJECT));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void aDisabledKeySignsNoRequest() {
PaymentCryptographyKey pair = createKey("us-east-1", "RSA_2048", "ASYMMETRIC_KEY_PAIR",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", Map.of("Sign", Boolean.TRUE));
service.stopKeyUsage(pair);
AwsException refused = assertThrows(AwsException.class,
() -> service.certificateSigningRequest(pair, "SHA256", CSR_SUBJECT));
assertEquals("ValidationException", refused.getErrorCode());
}
/**
* The request a key pair signed, read back and checked.
*
* <p>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<ASN1ObjectIdentifier> subjectTypesOf(String answer) {
List<ASN1ObjectIdentifier> types = new ArrayList<>();
for (RDN rdn : requestOf(answer).getSubject().getRDNs()) {
types.add(rdn.getFirst().getType());
}
return types;
}
/**
* The request a PEM holds, read back.
*
* <p>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<String, Boolean> modes) {
return createKey("us-east-1", algorithm, "ASYMMETRIC_KEY_PAIR", usage, modes);
}
/** The attributes of a key with that algorithm and usage. */
private static Map<String, Object> attributes(String algorithm, String usage) {
return attributes(algorithm, "SYMMETRIC_KEY", usage);
@@ -92,7 +92,7 @@ public class CertificatesTest {
new X500Name("CN=" + issuerName), issuerKey,
List.of(), false, null, notBefore, notAfter);
byte[] der = certificate.getEncoded();
return new Certificates.Minted(der, Certificates.toPem(der));
return new Certificates.Minted(der, Certificates.toPem("CERTIFICATE", der));
} catch (Exception e) {
throw new IllegalStateException("cannot mint a certificate", e);
}